hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cae84a603c57abf08c19870047ccb549991766cb
1,962
cpp
C++
theforgottenserver/rsa.cpp
eclipse606/TFS-Exclusive-0.5.2
beb8e40341f97933b0f42bc43fe7579b14723adc
[ "Unlicense" ]
null
null
null
theforgottenserver/rsa.cpp
eclipse606/TFS-Exclusive-0.5.2
beb8e40341f97933b0f42bc43fe7579b14723adc
[ "Unlicense" ]
null
null
null
theforgottenserver/rsa.cpp
eclipse606/TFS-Exclusive-0.5.2
beb8e40341f97933b0f42bc43fe7579b14723adc
[ "Unlicense" ]
1
2022-01-18T01:08:43.000Z
2022-01-18T01:08:43.000Z
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2016 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "rsa.h" RSA::RSA() { mpz_init(n); mpz_init2(d, 1024); } RSA::~RSA() { mpz_clear(n); mpz_clear(d); } void RSA::setKey(const char* pString, const char* qString) { mpz_t p, q, e; mpz_init2(p, 1024); mpz_init2(q, 1024); mpz_init(e); mpz_set_str(p, pString, 10); mpz_set_str(q, qString, 10); // e = 65537 mpz_set_ui(e, 65537); // n = p * q mpz_mul(n, p, q); mpz_t p_1, q_1, pq_1; mpz_init2(p_1, 1024); mpz_init2(q_1, 1024); mpz_init2(pq_1, 1024); mpz_sub_ui(p_1, p, 1); mpz_sub_ui(q_1, q, 1); // pq_1 = (p -1)(q - 1) mpz_mul(pq_1, p_1, q_1); // d = e^-1 mod (p - 1)(q - 1) mpz_invert(d, e, pq_1); mpz_clear(p_1); mpz_clear(q_1); mpz_clear(pq_1); mpz_clear(p); mpz_clear(q); mpz_clear(e); } void RSA::decrypt(char* msg) const { mpz_t c, m; mpz_init2(c, 1024); mpz_init2(m, 1024); mpz_import(c, 128, 1, 1, 0, 0, msg); // m = c^d mod n mpz_powm(m, c, d, n); size_t count = (mpz_sizeinbase(m, 2) + 7) / 8; memset(msg, 0, 128 - count); mpz_export(msg + (128 - count), nullptr, 1, 1, 0, 0, m); mpz_clear(c); mpz_clear(m); }
20.87234
74
0.662589
eclipse606
caeed278fc90efce74f22ffac0ae1dbb88996e04
2,886
cpp
C++
vbox/src/VBox/Runtime/r3/posix/time-posix.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/Runtime/r3/posix/time-posix.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/Runtime/r3/posix/time-posix.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
/* $Id: time-posix.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */ /** @file * IPRT - Time, POSIX. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #define LOG_GROUP RTLOGGROUP_TIME #define RTTIME_INCL_TIMEVAL #include <sys/time.h> #include <time.h> #include <iprt/time.h> #include "internal/time.h" DECLINLINE(uint64_t) rtTimeGetSystemNanoTS(void) { #if defined(CLOCK_MONOTONIC) && !defined(RT_OS_L4) && !defined(RT_OS_OS2) /* check monotonic clock first. */ static bool s_fMonoClock = true; if (s_fMonoClock) { struct timespec ts; if (!clock_gettime(CLOCK_MONOTONIC, &ts)) return (uint64_t)ts.tv_sec * RT_NS_1SEC_64 + ts.tv_nsec; s_fMonoClock = false; } #endif /* fallback to gettimeofday(). */ struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * RT_NS_1SEC_64 + (uint64_t)(tv.tv_usec * RT_NS_1US); } /** * Gets the current nanosecond timestamp. * * This differs from RTTimeNanoTS in that it will use system APIs and not do any * resolution or performance optimizations. * * @returns nanosecond timestamp. */ RTDECL(uint64_t) RTTimeSystemNanoTS(void) { return rtTimeGetSystemNanoTS(); } /** * Gets the current millisecond timestamp. * * This differs from RTTimeNanoTS in that it will use system APIs and not do any * resolution or performance optimizations. * * @returns millisecond timestamp. */ RTDECL(uint64_t) RTTimeSystemMilliTS(void) { return rtTimeGetSystemNanoTS() / RT_NS_1MS; }
32.066667
130
0.616771
Nurzamal
caf2bc15a7f3e198804f3348a3325093db8435bc
12,547
cpp
C++
duilib/Control/List.cpp
colinjiang007/NIM_Duilib_Mini
d3784824b15c812787dd19c652db817b2793b265
[ "BSD-2-Clause", "MIT" ]
null
null
null
duilib/Control/List.cpp
colinjiang007/NIM_Duilib_Mini
d3784824b15c812787dd19c652db817b2793b265
[ "BSD-2-Clause", "MIT" ]
null
null
null
duilib/Control/List.cpp
colinjiang007/NIM_Duilib_Mini
d3784824b15c812787dd19c652db817b2793b265
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include "StdAfx.h" namespace ui { ListBox::ListBox(Layout* pLayout) : ScrollableBox(pLayout), m_bScrollSelect(false), m_iCurSel(-1), m_pCompareFunc(nullptr), m_pCompareData(NULL), m_bSelNextWhenRemoveActive(true) { } void ListBox::SetAttribute(LPCTSTR szName, LPCTSTR szValue) { CUiString strName(szName); CUiString strValue(szValue); if( strName == _T("scrollselect") ) { SetScrollSelect(strValue == _T("true")); } else { ScrollableBox::SetAttribute(szName, szValue); } } void ListBox::HandleMessage(EventArgs& event) { if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) { if (m_pParent != NULL) m_pParent->HandleMessageTemplate(event); else ScrollableBox::HandleMessage(event); return; } switch (event.Type) { case kEventMouseButtonDown: case kEventMouseButtonUp: return; case kEventKeyDown: switch (event.chKey) { case VK_UP: SelectItem(FindSelectable(m_iCurSel - 1, false), true); return; case VK_DOWN: SelectItem(FindSelectable(m_iCurSel + 1, true), true); return; case VK_HOME: SelectItem(FindSelectable(0, false), true); return; case VK_END: SelectItem(FindSelectable(GetCount() - 1, true), true); return; } break; case kEventMouseScrollWheel: { int detaValue = event.wParam; if (detaValue > 0) { if (m_bScrollSelect) { SelectItem(FindSelectable(m_iCurSel - 1, false), true); return; } break; } else { if (m_bScrollSelect) { SelectItem(FindSelectable(m_iCurSel + 1, true), true); return; } break; } } break; } ScrollableBox::HandleMessage(event); } void ListBox::HandleMessageTemplate(EventArgs& event) { ScrollableBox::HandleMessageTemplate(event); } int ListBox::GetCurSel() const { return m_iCurSel; } void ListBox::SelectNextWhenActiveRemoved(bool bSelectNextItem) { m_bSelNextWhenRemoveActive = bSelectNextItem; } bool ListBox::SelectItem(int iIndex, bool bTakeFocus, bool bTrigger) { //if( iIndex == m_iCurSel ) return true; int iOldSel = m_iCurSel; // We should first unselect the currently selected item if (m_iCurSel >= 0) { Control* pControl = GetItemAt(m_iCurSel); if (pControl != NULL) { ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if (pListItem != NULL) pListItem->OptionTemplate<Box>::Selected(false, bTrigger); } m_iCurSel = -1; } if (iIndex < 0) return false; Control* pControl = GetItemAt(iIndex); if (pControl == NULL) return false; if (!pControl->IsVisible()) return false; if (!pControl->IsEnabled()) return false; ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if (pListItem == NULL) return false; m_iCurSel = iIndex; pListItem->OptionTemplate<Box>::Selected(true, bTrigger); if (GetItemAt(m_iCurSel)) { CUiRect rcItem = GetItemAt(m_iCurSel)->GetPos(); EnsureVisible(rcItem); } if (bTakeFocus) pControl->SetFocus(); if (m_pWindow != NULL && bTrigger) { m_pWindow->SendNotify(this, kEventSelect, m_iCurSel, iOldSel); } return true; } void ListBox::EnsureVisible(const CUiRect& rcItem) { CUiRect rcNewItem = rcItem; rcNewItem.Offset(-GetScrollPos().cx, -GetScrollPos().cy); CUiRect rcList = GetPos(); CUiRect rcListInset = m_pLayout->GetPadding(); rcList.left += rcListInset.left; rcList.top += rcListInset.top; rcList.right -= rcListInset.right; rcList.bottom -= rcListInset.bottom; ScrollBar* pHorizontalScrollBar = GetHorizontalScrollBar(); if (pHorizontalScrollBar && pHorizontalScrollBar->IsVisible()) rcList.bottom -= pHorizontalScrollBar->GetFixedHeight(); if (rcNewItem.left >= rcList.left && rcNewItem.top >= rcList.top && rcNewItem.right <= rcList.right && rcNewItem.bottom <= rcList.bottom) { if (m_pParent && dynamic_cast<ListContainerElement*>(m_pParent) != NULL) { dynamic_cast<ListContainerElement*>(m_pParent)->GetOwner()->EnsureVisible(rcNewItem); } return; } int dx = 0; if (rcNewItem.left < rcList.left) dx = rcNewItem.left - rcList.left; if (rcNewItem.right > rcList.right) dx = rcNewItem.right - rcList.right; int dy = 0; if (rcNewItem.top < rcList.top) dy = rcNewItem.top - rcList.top; if (rcNewItem.bottom > rcList.bottom) dy = rcNewItem.bottom - rcList.bottom; CUiSize sz = GetScrollPos(); SetScrollPos(CUiSize(sz.cx + dx, sz.cy + dy)); } void ListBox::StopScroll() { m_scrollAnimation.Reset(); } bool ListBox::ButtonDown(EventArgs& msg) { bool ret = __super::ButtonDown(msg); StopScroll(); return ret; } bool ListBox::ScrollItemToTop(LPCTSTR strItemName) { for (auto it = m_items.begin(); it != m_items.end(); it++) { if ((*it)->GetName() == strItemName) { if (GetScrollRange().cy != 0) { CUiSize scrollPos = GetScrollPos(); scrollPos.cy = (*it)->GetPos().top - m_pLayout->GetInternalPos().top; if (scrollPos.cy >= 0) { SetScrollPos(scrollPos); return true; } else { return false; } } else { return false; } } } return false; } Control* ListBox::GetTopItem() { int listTop = GetPos().top + m_pLayout->GetPadding().top + GetScrollPos().cy; for (auto it = m_items.begin(); it != m_items.end(); it++) { if ((*it)->IsVisible() && !(*it)->IsFloat() && (*it)->GetPos().bottom >= listTop) { return (*it); } } return nullptr; } bool ListBox::SetItemIndex(Control* pControl, std::size_t iIndex) { int iOrginIndex = GetItemIndex(pControl); if( iOrginIndex == -1 ) return false; if( iOrginIndex == (int)iIndex ) return true; ListContainerElement* pSelectedListItem = NULL; if( m_iCurSel >= 0 ) pSelectedListItem = dynamic_cast<ListContainerElement*>(GetItemAt(m_iCurSel)); if( !ScrollableBox::SetItemIndex(pControl, iIndex) ) return false; std::size_t iMinIndex = min((std::size_t)iOrginIndex, iIndex); std::size_t iMaxIndex = max((std::size_t)iOrginIndex, iIndex); for(std::size_t i = iMinIndex; i < iMaxIndex + 1; ++i) { Control* pItemControl = GetItemAt(i); ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pItemControl); if( pListItem != NULL ) { pListItem->SetIndex((int)i); } } if( m_iCurSel >= 0 && pSelectedListItem != NULL ) m_iCurSel = pSelectedListItem->GetIndex(); return true; } void ListBox::Previous() { if (m_iCurSel > 0) { SelectItem(m_iCurSel - 1); } } void ListBox::Next() { int count = GetCount(); if (m_iCurSel < count - 1) { SelectItem(m_iCurSel + 1); } } void ListBox::ActiveItem() { if (m_iCurSel >= 0) { ListContainerElement* item = dynamic_cast<ListContainerElement*>( GetItemAt(m_iCurSel) ); item->InvokeDoubleClickEvent(); } } bool ListBox::Add(Control* pControl) { // Override the Add() method so we can add items specifically to // the intended widgets. Headers are assumed to be // answer the correct interface so we can add multiple list headers. // The list items should know about us ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if( pListItem != NULL ) { pListItem->SetOwner(this); pListItem->SetIndex(GetCount()); } return ScrollableBox::Add(pControl); } bool ListBox::AddAt(Control* pControl, int iIndex) { // Override the AddAt() method so we can add items specifically to // the intended widgets. Headers and are assumed to be // answer the correct interface so we can add multiple list headers. if (!ScrollableBox::AddAt(pControl, iIndex)) return false; // The list items should know about us ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if( pListItem != NULL ) { pListItem->SetOwner(this); pListItem->SetIndex(iIndex); } for(int i = iIndex + 1; i < GetCount(); ++i) { Control* p = GetItemAt(i); pListItem = dynamic_cast<ListContainerElement*>(p); if( pListItem != NULL ) { pListItem->SetIndex(i); } } if( m_iCurSel >= iIndex ) m_iCurSel += 1; return true; } bool ListBox::Remove(Control* pControl) { int iIndex = GetItemIndex(pControl); if (iIndex == -1) return false; return RemoveAt(iIndex); } bool ListBox::RemoveAt(int iIndex) { if (!ScrollableBox::RemoveAt(iIndex)) return false; for(int i = iIndex; i < GetCount(); ++i) { Control* p = GetItemAt(i); ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(p); if( pListItem != NULL ) pListItem->SetIndex(i); } if( iIndex == m_iCurSel && m_iCurSel >= 0 ) { if (m_bSelNextWhenRemoveActive) SelectItem(FindSelectable(m_iCurSel--, false)); else m_iCurSel = -1; } else if( iIndex < m_iCurSel ) m_iCurSel -= 1; return true; } void ListBox::RemoveAll() { m_iCurSel = -1; ScrollableBox::RemoveAll(); } bool ListBox::SortItems(PULVCompareFunc pfnCompare, UINT_PTR dwData) { if (!pfnCompare) return false; if (m_items.size() == 0) { return true; } m_pCompareFunc = pfnCompare; m_pCompareData = dwData; qsort_s(&(*m_items.begin()), m_items.size(), sizeof(Control*), ListBox::ItemComareFunc, this); ListContainerElement *pItem = NULL; for (int i = 0; i < (int)m_items.size(); ++i) { pItem = dynamic_cast<ListContainerElement*>(static_cast<Control*>(m_items[i])); if (pItem) { pItem->SetIndex(i); pItem->Selected(false, true); } } SelectItem(-1); SetPos(GetPos()); Invalidate(); return true; } int __cdecl ListBox::ItemComareFunc(void *pvlocale, const void *item1, const void *item2) { ListBox *pThis = (ListBox*)pvlocale; if (!pThis || !item1 || !item2) return 0; return pThis->ItemComareFunc(item1, item2); } int __cdecl ListBox::ItemComareFunc(const void *item1, const void *item2) { Control *pControl1 = *(Control**)item1; Control *pControl2 = *(Control**)item2; return m_pCompareFunc((UINT_PTR)pControl1, (UINT_PTR)pControl2, m_pCompareData); } bool ListBox::GetScrollSelect() { return m_bScrollSelect; } void ListBox::SetScrollSelect(bool bScrollSelect) { m_bScrollSelect = bScrollSelect; } ///////////////////////////////////////////////////////////////////////////////////// // // ListContainerElement::ListContainerElement() : m_iIndex(-1), m_pOwner(nullptr) { m_uTextStyle = DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS | DT_NOCLIP | DT_SINGLELINE; SetReceivePointerMsg(false); } void ListContainerElement::SetVisible(bool bVisible) { __super::SetVisible(bVisible); if (!IsVisible() && m_bSelected) { m_bSelected = false; if (m_pOwner != NULL) m_pOwner->SelectItem(-1); } } void ListContainerElement::Selected(bool bSelected, bool trigger) { if (!IsEnabled()) return; if (bSelected && m_pOwner != NULL) m_pOwner->SelectItem(m_iIndex, false, trigger); } void ListContainerElement::HandleMessage(EventArgs& event) { if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) { if (m_pOwner != NULL) m_pOwner->HandleMessageTemplate(event); else Box::HandleMessage(event); return; } else if (event.Type == kEventInternalDoubleClick) { if (IsActivatable()) { InvokeDoubleClickEvent(); } return; } else if (event.Type == kEventKeyDown && IsEnabled()) { if (event.chKey == VK_RETURN) { if (IsActivatable()) { if (m_pWindow != NULL) m_pWindow->SendNotify(this, kEventReturn); } return; } } else if (event.Type == kEventInternalMenu && IsEnabled()) { Selected(true, true); m_pWindow->SendNotify(this, kEventMouseMenu); Invalidate(); return; } __super::HandleMessage(event); // An important twist: The list-item will send the event not to its immediate // parent but to the "attached" list. A list may actually embed several components // in its path to the item, but key-presses etc. needs to go to the actual list. //if( m_pOwner != NULL ) m_pOwner->HandleMessage(event); else Control::HandleMessage(event); } IListOwner* ListContainerElement::GetOwner() { return m_pOwner; } void ListContainerElement::SetOwner(IListOwner* pOwner) { m_pOwner = pOwner; } int ListContainerElement::GetIndex() const { return m_iIndex; } void ListContainerElement::SetIndex(int iIndex) { m_iIndex = iIndex; } void ListContainerElement::InvokeDoubleClickEvent() { if( m_pWindow != NULL ) m_pWindow->SendNotify(this, kEventMouseDoubleClick); } } // namespace ui
26.248954
121
0.672193
colinjiang007
caf3b10159b57f6601c90caf58f83e1ebb851db5
714
cpp
C++
Array/zhanchengguo/0711-BiNode/BiNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
39
2020-05-31T06:14:39.000Z
2021-01-09T11:06:39.000Z
Array/zhanchengguo/0711-BiNode/BiNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
7
2020-06-02T11:04:14.000Z
2020-06-11T14:11:58.000Z
Array/zhanchengguo/0711-BiNode/BiNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
20
2020-05-31T06:21:57.000Z
2020-10-01T04:48:38.000Z
#include <iostream> #include <stack> #include <list> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *convertBiNode(TreeNode *root); void reversion(TreeNode *root); int main() { return 0; } TreeNode *ans = new TreeNode(-1); TreeNode *cur = ans; /** * * @param root * @return */ TreeNode *convertBiNode(TreeNode *root) { reversion(root); return ans->right; } /** * 遍历树结构 * @param root */ void reversion(TreeNode *root) { if (root == NULL) { return; } dfs(root->left); root->left = NULL; cur->right = root; cur = root; dfs(root->right); }
14.571429
56
0.596639
JessonYue
caf3f99cca726a33c339a3d00fcccd4e7813deb4
348
cxx
C++
examples/01_SimpleExamples/05_MultiObjects/src/main.cxx
GailKabala/LearnVulkan
672ee38755413889f2e1fe4d226e200955da9278
[ "MIT" ]
null
null
null
examples/01_SimpleExamples/05_MultiObjects/src/main.cxx
GailKabala/LearnVulkan
672ee38755413889f2e1fe4d226e200955da9278
[ "MIT" ]
null
null
null
examples/01_SimpleExamples/05_MultiObjects/src/main.cxx
GailKabala/LearnVulkan
672ee38755413889f2e1fe4d226e200955da9278
[ "MIT" ]
null
null
null
#include "multiobjects.h" int main(int argc,char** argv){ bool debug=false; MultiImageSampler* pMultiImageSampler=new MultiImageSampler(debug); pMultiImageSampler->initVulkan(); pMultiImageSampler->initWindow(); pMultiImageSampler->prepare(); pMultiImageSampler->renderLoop(); delete pMultiImageSampler; return 1; }
29
71
0.735632
GailKabala
caf45f6a9261e65fa1422e9e8156dd01b0e5fcba
8,688
cpp
C++
barcode.cpp
GimmeDanger/barcode_reader
26685effc10521f9e6daccee62f0ad82a6168f69
[ "MIT" ]
null
null
null
barcode.cpp
GimmeDanger/barcode_reader
26685effc10521f9e6daccee62f0ad82a6168f69
[ "MIT" ]
null
null
null
barcode.cpp
GimmeDanger/barcode_reader
26685effc10521f9e6daccee62f0ad82a6168f69
[ "MIT" ]
null
null
null
#include "barcode.h" #include <algorithm> constexpr uchar Barcode::black_color; constexpr uchar Barcode::white_color; constexpr int Barcode::left_guards_size; constexpr int Barcode::middle_guards_size; constexpr int Barcode::right_guards_size; constexpr int Barcode::left_code_size; constexpr int Barcode::right_code_size; constexpr int Barcode::barcode_number_size; constexpr int Barcode::check_sum_coeffs[]; Barcode::Barcode (const cv::Mat * const gray_im) : image (gray_im), max_image_index (gray_im->cols) { if (image->channels () > 1) { barcode_exceptions::not_gray_image_exception notgray_im_ex; throw notgray_im_ex; } decode (); } void Barcode::decode () { for (int row_i = 0; row_i < image->rows; row_i++) { const uchar *test_row = image->ptr (row_i); decode_row (test_row); if (is_correct) return; clear_data (); } return; } void Barcode::decode_row (const uchar * const test_row) { constract_row_structure (test_row); identify_barcode_number (); check_control_number (); } void Barcode::clear_data () { memset (left_guards, 0, sizeof (int) * left_guards_size); memset (left_code, 0, sizeof (int) * left_code_size); memset (middle_guards, 0, sizeof (int) * middle_guards_size); memset (right_code, 0, sizeof (int) * right_code_size); memset (right_guards, 0, sizeof (int) * right_guards_size); memset (barcode_number, 0, sizeof (int) * barcode_number_size); } void Barcode::print_barcode () const { if (!is_correct) return; std::cout << barcode_number[0] << " "; for (int i = 0; i < 6; i++) std::cout << barcode_number[1 + i]; std::cout << " "; for (int i = 0; i < 6; i++) std::cout << barcode_number[7 + i]; std::cout << std::endl; } long long Barcode::get_barcode_number () const { long long ans = 0; long long decimals = 1; for (int i = 0; i < barcode_number_size; i++) { ans += barcode_number[barcode_number_size - 1 - i] * decimals; decimals *= 10; } return ans; } void Barcode::constract_row_structure (const uchar * const test_row) { bool is_left_guards_filled = false; bool is_middle_guards_filled = false; bool is_right_guards_filled = false; bool is_left_code_filled = false; bool is_right_code_filled = false; int left_guards_beg = find_row_structure_part_beg (test_row, 0, black_color); int left_code_beg = constract_row_structure_part (test_row, left_guards_beg, black_color, left_guards_size, left_guards, is_left_guards_filled); int middle_guards_beg = constract_row_structure_part (test_row, left_code_beg, white_color, left_code_size, left_code, is_left_code_filled); int right_code_beg = constract_row_structure_part (test_row, middle_guards_beg, white_color, middle_guards_size, middle_guards, is_middle_guards_filled); int right_guards_beg = constract_row_structure_part (test_row, right_code_beg, black_color, right_code_size, right_code, is_right_code_filled); int right_guards_end = constract_row_structure_part (test_row, right_guards_beg , black_color, right_guards_size, right_guards, is_right_guards_filled); if (is_left_guards_filled && is_left_code_filled && is_middle_guards_filled && is_right_code_filled && is_right_guards_filled) { has_barcode_structure = true; } return; } int Barcode::find_row_structure_part_beg (const uchar * const test_row, const int beg_index, const int part_color) { for (int index = beg_index; index < max_image_index; index++) if (test_row[index] == part_color) return index; return max_image_index; } int Barcode::constract_row_structure_part (const uchar * const test_row, const int beg_index, const uchar first_color, const int part_size, int *part, bool &part_filled) { int index, part_index; for (part_index = 0; part_index < part_size; part_index++) part[part_index] = 0; uchar curr_color = first_color; uchar prev_color = (first_color == black_color) ? white_color : black_color; for (index = beg_index, part_index = 0; index < max_image_index && part_index < part_size; index++) { if (test_row[index] == prev_color) { std::swap (curr_color, prev_color); part_index++; } part[part_index]++; } if (part_index != part_size) index = max_image_index; if (index < max_image_index) part_filled = true; return index; } void Barcode::identify_barcode_number () { if (!has_barcode_structure) return; std::string EAN_13; // guard length float h = 0.f; for (int i = 0; i < left_guards_size; i++) h += left_guards[i]; for (int i = 0; i < middle_guards_size; i++) h += middle_guards[i]; for (int i = 0; i < right_guards_size; i++) h += right_guards[i]; h /= left_guards_size + middle_guards_size + right_guards_size; // std::cout << "decode left code" << std::endl; for (int i = 0; i < left_code_size; i += 4) { int n = decode_single_number (h, left_code[i], left_code[i + 1], left_code[i + 2], left_code[i + 3]); auto got = LG_EAN_map.find (n); if (got == LG_EAN_map.end ()) { // std::cout << "Can`t decode number " << i / 4 + 1 << " in L-code." << std::endl; return; } else { barcode_number[i / 4 + 1] = (got->second).first; EAN_13 += (got->second).second; } } // std::cout << "decode right code" << std::endl; for (int i = 0; i < right_code_size; i += 4) { int n = decode_single_number (h, right_code[i], right_code[i + 1], right_code[i + 2], right_code[i + 3]); auto got = R_EAN_map.find (n); if (got == R_EAN_map.end ()) { // std::cout << "Can`t decode number " << i / 4 + 1 << " in R-code." << std::endl; return; } else barcode_number[i / 4 + 7] = (got->second).first; } // std::cout << "decode 13-th number" << std::endl; auto got = EAN_13_map.find (EAN_13); if (got == EAN_13_map.end ()) { // std::cout << "Can`t decode 13-th number!" << std::endl; return; } else barcode_number[0] = got->second; is_identified = true; } int Barcode::decode_single_number (const float h, const int l_0, const int l_1, const int l_2, const int l_3) { int max_bit_num = 7; float hl_0 = l_0 / h; float hl_1 = l_1 / h; float hl_2 = l_2 / h; float hl_3 = l_3 / h; // std::cout << hl_0 << " " << hl_1 << " " << hl_2 << " " << hl_3 << " " << std::endl; float hl_0_1 = hl_0 + hl_1; float hl_2_3 = hl_2 + hl_3; if (hl_0 < 1.f || hl_1 < 1.f) { if (hl_0 < 1.f) { hl_0 = 1.f; hl_1 = hl_0_1 - 1; hl_1 = (int) hl_1; } else if (hl_1 < 1.f) { hl_1 = 1.f; hl_0 = hl_0_1 - 1; hl_0 = (int) hl_0; } } else if ((int) hl_0_1 > (int) hl_0 + (int) hl_1) { if (hl_0 - (int) hl_0 > hl_1 - (int) hl_1) hl_0 = (int) hl_0 + 1, hl_1 = (int) hl_1; else if (hl_0 - (int) hl_0 < hl_1 - (int) hl_1) hl_1 = (int) hl_1 + 1, hl_0 = (int) hl_0; else { if ((int) (hl_1 + hl_2) > (int) hl_1 + (int) hl_2) hl_0 = (int) hl_0 + 1, hl_1 = (int) hl_1; else hl_1 = (int) hl_1 + 1, hl_0 = (int) hl_0; } } if (hl_2 < 1.f || hl_3 < 1.f) { if (hl_2 < 1.f) { hl_2 = 1.f; hl_3 = hl_2_3 - 1; hl_3 = (int) hl_3; } else if (hl_3 < 1.f) { hl_3 = 1.f; hl_2 = hl_2_3 - 1; hl_2 = (int) hl_2; } } else if ((int) hl_2_3 > (int) hl_2 + (int) hl_3) { if (hl_2 - (int) hl_2 > hl_3 - (int) hl_3) hl_2 = (int) hl_2 + 1, hl_3 = (int) hl_3; else hl_3 = (int) hl_3 + 1, hl_2 = (int) hl_2; } hl_0 = std::min (4.f, hl_0); hl_1 = std::min (4.f, hl_1); hl_2 = std::min (4.f, hl_2); hl_3 = std::min (4.f, hl_3); return (int) hl_0 * 1000 + (int) hl_1 * 100 + (int) hl_2 * 10 + (int) hl_3; } void Barcode::check_control_number () { if (!is_identified) return; int check_sum = 0; for (int i = 0; i < 13; i++) check_sum += barcode_number[i] * check_sum_coeffs[i]; if (check_sum % 10 == 0) is_correct = true; }
30.699647
118
0.581722
GimmeDanger
caf595b951216a3f914c7bb1f4fb18703cbebd7f
5,671
cpp
C++
src/comm/serialport.cpp
robertrau/libpifly
c69e0161f85668637ef5eb1387f48929b247964a
[ "MIT" ]
null
null
null
src/comm/serialport.cpp
robertrau/libpifly
c69e0161f85668637ef5eb1387f48929b247964a
[ "MIT" ]
null
null
null
src/comm/serialport.cpp
robertrau/libpifly
c69e0161f85668637ef5eb1387f48929b247964a
[ "MIT" ]
null
null
null
/* Author: Robert F. Rau II Copyright (C) 2017 Robert F. Rau II */ #include "comm/serialport.h" #include "comm/commexception.h" #include <iostream> #include <unistd.h> namespace PiFly { namespace Comm { SerialPort::SerialPort(string devPath, Baudrate baud, bool blocking) : mBlocking(blocking) { if(mBlocking) { serialFd = open(devPath.c_str(), O_RDWR); } else { serialFd = open(devPath.c_str(), O_RDWR | O_NONBLOCK | O_NDELAY); } if(serialFd < 0) { throw CommFdException(errno); } memset(&serialTTY, 0, sizeof(termios)); if(tcgetattr(serialFd, &serialTTY) != 0) { throw CommFdException(errno); } if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } // make a raw serial port cfmakeraw(&serialTTY); if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) { throw CommFdException(errno); } } SerialPort::~SerialPort() { if(serialFd >= 0) { close(serialFd); } } size_t SerialPort::read(SerialBuffer::iterator first, size_t readBytes) { if(!mBlocking) { int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes); if(resp > 0) { return resp; } else if((resp < 0) && (errno != EAGAIN)) { throw CommFdException(errno); } else { return 0; } } else { int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes); if(resp > 0) { return resp; } else if(resp == 0) { throw CommFdException(errno); } else { throw CommFdException(resp); } } } void SerialPort::write(const SerialBuffer& buffer) { size_t bytesWritten = 0; ssize_t resp; do { resp = ::write(serialFd, static_cast<const void*>(buffer.data()), buffer.size()); if(resp > 0) { bytesWritten += resp; } else if(resp == 0) { throw CommFdException(errno); } else { throw CommFdException(resp); } } while(bytesWritten < buffer.size()); } void SerialPort::setBaudrate(Baudrate baud) { if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) { throw CommFdException(errno); } } SerialPort::Baudrate SerialPort::getBaudrate() { speed_t currentBaud = cfgetispeed(&serialTTY); return linuxBaudrateMap(currentBaud); } void SerialPort::flush() { tcflush(serialFd, TCIOFLUSH); } SerialPort::Baudrate SerialPort::linuxBaudrateMap(speed_t baud) { switch(baud) { case B0: return Baudrate_0; case B50: return Baudrate_50; case B75: return Baudrate_75; case B110: return Baudrate_110; case B134: return Baudrate_134; case B150: return Baudrate_150; case B200: return Baudrate_200; case B300: return Baudrate_300; case B600: return Baudrate_600; case B1200: return Baudrate_1200; case B1800: return Baudrate_1800; case B2400: return Baudrate_2400; case B4800: return Baudrate_4800; case B9600: return Baudrate_9600; case B19200: return Baudrate_19200; case B38400: return Baudrate_38400; case B57600: return Baudrate_57600; case B115200: return Baudrate_115200; case B230400: return Baudrate_230400; default: std::cout << "linuxBaudrateMap speed_t Input baud: " << baud << "\n"; throw CommException("Unsupported baudrate"); } } speed_t SerialPort::linuxBaudrateMap(Baudrate baud) { switch(baud) { case Baudrate_0: return B0; case Baudrate_50: return B50; case Baudrate_75: return B75; case Baudrate_110: return B110; case Baudrate_134: return B134; case Baudrate_150: return B150; case Baudrate_200: return B200; case Baudrate_300: return B300; case Baudrate_600: return B600; case Baudrate_1200: return B1200; case Baudrate_1800: return B1800; case Baudrate_2400: return B2400; case Baudrate_4800: return B4800; case Baudrate_9600: return B9600; case Baudrate_19200: return B19200; case Baudrate_38400: return B38400; case Baudrate_57600: return B57600; case Baudrate_115200: return B115200; case Baudrate_230400: return B230400; default: std::cout << "linuxBaudrateMap Baudrate Input baud: " << baud << "\n"; throw CommException("Unsupported baudrate"); } } string SerialPort::baudrateString(Baudrate baud) { switch(baud) { case Baudrate_0: return "0"; case Baudrate_50: return "50"; case Baudrate_75: return "75"; case Baudrate_110: return "110"; case Baudrate_134: return "134"; case Baudrate_150: return "150"; case Baudrate_200: return "200"; case Baudrate_300: return "300"; case Baudrate_600: return "600"; case Baudrate_1200: return "1200"; case Baudrate_1800: return "1800"; case Baudrate_2400: return "2400"; case Baudrate_4800: return "4800"; case Baudrate_9600: return "9600"; case Baudrate_19200: return "19200"; case Baudrate_38400: return "38400"; case Baudrate_57600: return "57600"; case Baudrate_115200: return "115200"; case Baudrate_230400: return "230400"; default: return "unsupported"; } } } }
22.152344
85
0.631811
robertrau
caf83c749a0090f67d34ad9943669a21bbb4264c
2,578
hpp
C++
include/atma/hash.hpp
omnigoat/atma
73833f41373fac2af695587786c00a307046de64
[ "MIT" ]
7
2016-04-08T03:53:42.000Z
2020-07-06T05:52:35.000Z
include/atma/hash.hpp
omnigoat/atma
73833f41373fac2af695587786c00a307046de64
[ "MIT" ]
1
2018-04-14T13:56:06.000Z
2018-04-14T13:56:06.000Z
include/atma/hash.hpp
omnigoat/atma
73833f41373fac2af695587786c00a307046de64
[ "MIT" ]
null
null
null
#pragma once import atma.types; namespace atma { struct hasher_t; template <typename T> struct hash_t { auto operator()(T const& x) const -> size_t; auto operator()(hasher_t& hsh, T const& x) const -> void; }; struct hasher_t { hasher_t(uint64 seed = 0); template <typename T> auto operator ()(T const& t) -> hasher_t&; auto operator ()(void const* datav, size_t size) -> hasher_t&; auto result() -> uint64; private: auto mmix(uint64& h, uint64 k) const -> void { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; } void mix_tail(const uchar*& data, size_t& size) { while (size && (size < 8 || count_)) { tail_ |= *data << (count_ * 8); ++data; ++count_; --size; if (count_ == 8) { mmix(hash_, tail_); tail_ = 0; count_ = 0; } } } private: static const uint64 m = 0xc6a4a7935bd1e995ull; static const int r = 47; uint64 hash_; uint64 tail_; uint64 count_; size_t size_; }; inline auto hash(void const* key, size_t size, uint seed) -> uint64 { return hasher_t(seed)(key, size).result(); } template <typename T> inline auto hash(T const& t) -> uint64 { auto hasher = hasher_t{}; hash_t<T>{}(hasher, t); return hasher.result(); } struct std_hash_functor_adaptor_t { template <typename T> auto operator ()(T const& x) const -> size_t { return hasher_t()(&x, sizeof(T)).result(); } }; template <typename T> inline auto hash_t<T>::operator()(T const& x) const -> size_t { return hasher_t{}(x).result(); } template <typename T> inline auto hash_t<T>::operator()(hasher_t& hsh, T const& x) const -> void { hsh(&x, sizeof(T)); } inline hasher_t::hasher_t(uint64 seed) : hash_(seed) , tail_() , count_() , size_() { } inline auto hasher_t::operator ()(void const* datav, size_t size) -> hasher_t& { auto data = reinterpret_cast<uchar const*>(datav); size_ += size; mix_tail(data, size); while (size >= 8) { uint64 k = *(uint64*)data; mmix(hash_, k); data += 8; size -= 8; } mix_tail(data, size); return *this; } inline auto hasher_t::result() -> uint64 { mmix(hash_, tail_); mmix(hash_, size_); hash_ ^= hash_ >> r; hash_ *= m; hash_ ^= hash_ >> r; return hash_; } template <typename T> inline auto hasher_t::operator ()(T const& t) -> hasher_t& { hash_t<T>()(*this, t); return *this; } }
16.960526
80
0.557797
omnigoat
caf9506bec8989b42c3c560844f90f1c57e823e2
2,178
hpp
C++
schmidt.hpp
deakinYellow/utility-math
7b465ca7031fe85579c13d81732d8b20bbbf1acb
[ "Apache-2.0" ]
null
null
null
schmidt.hpp
deakinYellow/utility-math
7b465ca7031fe85579c13d81732d8b20bbbf1acb
[ "Apache-2.0" ]
null
null
null
schmidt.hpp
deakinYellow/utility-math
7b465ca7031fe85579c13d81732d8b20bbbf1acb
[ "Apache-2.0" ]
null
null
null
#include <iostream> //#define USING_MLOGD #include "utility/tool.h" #include <Eigen/Core> //#include <Eigen/Geometry> // Eigen 几何模块 /** * @brief 使用Gramy-Schmidt方法实现向量正交化,并单位化 * @param [in] a 向量a * @param [in] b 向量b * @param [in] c 向量c * @param [out] An 标准化后的向量A * @param [out] Bn 标准化后的向量B * @param [out] Cn 标准化后的向量C * @retval * @note a,b,c必须为线性无关组 */ static void schmidtOrthogonalV3D( Eigen::Vector3d a, Eigen::Vector3d b, Eigen::Vector3d c, Eigen::Vector3d* An, Eigen::Vector3d* Bn, Eigen::Vector3d* Cn ){ Eigen::Vector3d A,B,C; //A直接赋值为a A = a; //MLOGD("vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() ); //求B double xab = A.dot(b) / A.dot( A ); B = b - xab * A; //MLOGD("vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() ); //求C double xac = A.dot( c ) / A.dot( A ); double xbc = B.dot( c ) / B.dot( B ); C = c - ( xac * A ) - ( xbc * B ); //MLOGD("vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() ); //单位化并输出 *An = A.normalized(); *Bn = B.normalized(); *Cn = C.normalized(); //MLOGD("normalized vector A: %.3lf %.3f %.3f", An->x(), An->y(), An->z() ); //MLOGD("normalized vector B: %.3lf %.3f %.3f", Bn->x(), Bn->y(), Bn->z() ); //MLOGD("normalized vector C: %.3lf %.3f %.3f", Cn->x(), Cn->y(), Cn->z() ); } //--------------------测试函数---------------------------- static void schmidtOrthogonalTest( void ) { //线性无关组1 Eigen::Vector3d a(1,1.2,0); Eigen::Vector3d b(1,2,0); Eigen::Vector3d c(0,1,1); //线性无关组2 Eigen::Vector3d v1(9,1.2,2.4); Eigen::Vector3d v2(1,2,6.7); Eigen::Vector3d v3(5,1.5,1); Eigen::Vector3d A,B,C; schmidtOrthogonalV3D( a, b, c, &A, &B, &C ); //schmidtOrthogonalV3D( v1, v2, v3, &A, &B, &C ); TPLOGI("normalized vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() ); TPLOGI("normalized vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() ); TPLOGI("normalized vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() ); }
30.25
80
0.472452
deakinYellow
cafe1defafe566eabcedc1c9ed23b2f8a0be029f
7,579
cc
C++
src/utils/dexai_log.cc
DexaiRobotics/drake-franka-driver
856b2e029ade04b164c889975c167c8bdebea7af
[ "BSD-3-Clause" ]
5
2020-12-07T18:12:26.000Z
2022-03-17T23:27:42.000Z
src/utils/dexai_log.cc
DexaiRobotics/drake-franka-driver
856b2e029ade04b164c889975c167c8bdebea7af
[ "BSD-3-Clause" ]
18
2020-12-01T03:02:19.000Z
2022-03-11T22:36:45.000Z
src/utils/dexai_log.cc
DexaiRobotics/drake-franka-driver
856b2e029ade04b164c889975c167c8bdebea7af
[ "BSD-3-Clause" ]
null
null
null
/* * BSD 3-Clause License * * Copyright (c) 2021, Dexai Robotics * 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 copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // @file dexai/log_dexai.cc #include "utils/dexai_log.h" #include <iostream> #include "utils/utils.h" namespace { // static drake::never_destroyed<std::shared_ptr<slogger>> s_logger = nullptr; static std::shared_ptr<slogger> s_logger = nullptr; static slogger* d_logger = nullptr; } // namespace unsigned DexaiLogger::log_id_size(spdlog::level::level_enum ll_enum) { switch (ll_enum) { case spdlog::level::warn: return log_id_error_size_ + 2; case spdlog::level::info: return log_id_error_size_ - 1; // case spdlog::level::debug: // case spdlog::level::err: // NOTE spdlog::level::error does not // exist. case spdlog::level::trace: default: return log_id_error_size_; } } namespace dexai { // Returns true IFF the logger object is NULL, // meaning that either is has not yet been created, or it was nullified. bool is_log_null() { return s_logger == nullptr; } spdlog::logger* log(int warn_if_null) { if (is_log_null()) { if (warn_if_null) { std::cerr << "WARNING: Call to uninitialized dexai::logging::logger log()" << std::endl; std::cerr << "WARNING: Using all defaults in dexai::logging::logger log()" << std::endl; } create_log(); } assert(s_logger && "FATAL: s_logger still not set after calling dexai::create_log()"); return s_logger.get(); } /// Convenience function to get the "current" logger's log directory. @see /// log_dexai.h std::string log_dir() { try { DexaiLogger* dexai_logger = dynamic_cast<DexaiLogger*>(dexai::log()); return dexai_logger == nullptr ? "" : dexai_logger->log_dir(); } catch (const std::exception& ex) { dexai::log()->warn("Error in dexai::log_dir: {}", ex.what()); } return ""; } // Convenience function to get the "current" logger's log message ID size. @see // log_dexai.h Example usage: log()->error("This is a test of // dexai::DexaiLogger::log_id_size:\n{:>{}}" // "This line shall line up with the line up one line.", // "", dexai::log_id_size() // ); unsigned log_id_size(spdlog::level::level_enum ll_enum) { try { DexaiLogger* dexai_logger = dynamic_cast<DexaiLogger*>(dexai::log(ll_enum)); return dexai_logger == nullptr ? 42 : dexai_logger->log_id_size(); } catch (const std::exception& ex) { dexai::log()->debug("Error in dexai::log_id_size({}): {}", (unsigned)ll_enum, ex.what()); } return 42; } bool create_log(const std::string& program_in, const std::string& base_path, const std::string& prefix_in, bool use_stdout, bool create_once) { if (s_logger != nullptr && create_once) { s_logger->warn("dexai::create_log: s_logger already created!"); return false; } std::string program = program_in; if (program.empty()) { program = "dexai"; } std::string base_dir = base_path; if (base_dir.empty()) { base_dir = utils::get_home_dir() + "/log_robot"; } std::string prefix = prefix_in; if (prefix.empty()) { prefix = program; } std::string log_dir; bool got_base = utils::sub_dir_path(log_dir, base_dir, program); //$ append extra date and datetime subfolders to log output path std::string date_string = utils::get_date_string(); std::string date_time_string = utils::date_time_string(); got_base = utils::sub_dir_path(log_dir, log_dir, date_string); got_base = utils::sub_dir_path(log_dir, log_dir, date_time_string); // NOTE: We cannot call drake::log or dexai::log here; they're uninitialized. if (got_base) { // NOTE: Caution: Calling log here may stackoverflow. } else { drake::log()->error( "::::::::::: dexai::create_log: fatal error -- no base directory for " "logs!"); return false; } std::vector<spdlog::sink_ptr> sinks; if (use_stdout) { sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); } else { sinks.push_back(std::make_shared<spdlog::sinks::stderr_color_sink_mt>()); } std::string log_file_name = utils::date_time_string() + "_" + program + ".log"; std::string log_file_path = log_dir + "/" + log_file_name; sinks.push_back( std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file_path)); // NOTE: We don't necessarily need a DexaiLogger; we could just use one // spd::logger. std::shared_ptr<DexaiLogger> logger = std::make_shared<DexaiLogger>(prefix, log_dir, begin(sinks), end(sinks)); spdlog::register_logger( logger); // register it if you need to access it globally logger->set_level(spdlog::level::info); s_logger = logger; return true; } } // namespace dexai #if OVERRIDE_DRAKE_LOG namespace drake { logging::logger* log() { #ifdef ASSERT_TRUE // To be compiled only in a test context. std::cerr << "\t<<<< Call to drake::log() got the override log() >>>>" << std::endl << std::endl; #endif // TODO: Would prefer to assert rather than conpensate for failing // to initialize the logger, but then every executable that includes // log_dexai.h with OVERRIDE_DRAKE_LOG defined as truthy must either call // dexai::create_log or work around it. // assert(s_logger && "s_logger not set; call dexai::create_log() first!"); if (dexai::is_log_null()) { std::cerr << "WARNING: Call to uninitialized drake::logging::logger log()" << std::endl; dexai::create_log(); std::cerr << "WARNING: Used all defaults for drake::logging::logger log()" << std::endl; } assert(s_logger && "FATAL: s_logger still not set after calling dexai::create_log()"); return s_logger.get(); } } // namespace drake // TODO: If possible and worthwhile, provide access to the original result of // drake::log() that we overrode. drake::logging::logger* original_drake_log() { if (d_logger == nullptr) { d_logger = drake::log(); } return d_logger; } #endif // OVERRIDE_DRAKE_LOG
36.090476
80
0.679377
DexaiRobotics
cafe7f9a3dcf63e01d84bde0d9fcec87c6cea065
927
cpp
C++
codes/sub/src/comms/comms.cpp
tofu-micom/RCJ2021_Exhibition
55877e2dd6be3ef1b660f98725a83c3aaef21cb1
[ "MIT" ]
null
null
null
codes/sub/src/comms/comms.cpp
tofu-micom/RCJ2021_Exhibition
55877e2dd6be3ef1b660f98725a83c3aaef21cb1
[ "MIT" ]
null
null
null
codes/sub/src/comms/comms.cpp
tofu-micom/RCJ2021_Exhibition
55877e2dd6be3ef1b660f98725a83c3aaef21cb1
[ "MIT" ]
null
null
null
// // Created by 平地浩一 on 2021/03/23. // #include "comms.h" DigitalIn a(PA_7); DigitalIn b(PA_6); DigitalOut RA(PB_0); DigitalOut RB(PA_12); DigitalOut LA(PB_3); // PB_7 許さん!!! DigitalOut LB(PB_6); BufferedSerial pc(USBTX, USBRX); void comms_init() { RA.write(0); RB.write(0); LA.write(0); LB.write(0); } void comms_read() { bool A = a.read(); bool B = b.read(); static bool AA; static bool BB; if (A != AA || B != BB) { if (A && !B) { // 左超信地 RA.write(0); RB.write(1); LA.write(1); LB.write(0); } else if (!A && B) { // 右超信地 RA.write(1); RB.write(0); LA.write(0); LB.write(1); } else if (!A && !B) { // 停止 RA.write(1); RB.write(1); LA.write(1); LB.write(1); } else if (A && B) { // 前進 RA.write(0); RB.write(1); LA.write(0); LB.write(1); } } AA = A; BB = B; }
15.982759
33
0.483279
tofu-micom
1b07e3b6b1ec908923f117c4a99d023bcf522190
2,933
hpp
C++
inc/Tester.hpp
kotabrog/ft_containers
527f2b3c3aa73549cce912421f8e722af8b36ca0
[ "MIT" ]
null
null
null
inc/Tester.hpp
kotabrog/ft_containers
527f2b3c3aa73549cce912421f8e722af8b36ca0
[ "MIT" ]
null
null
null
inc/Tester.hpp
kotabrog/ft_containers
527f2b3c3aa73549cce912421f8e722af8b36ca0
[ "MIT" ]
null
null
null
#ifndef TESTER_HPP #define TESTER_HPP #include <string> #include <iostream> #include <sstream> #include <vector> #include <time.h> class Tester { private: struct StrTime { std::string str; clock_t time; /** Skip output when put_all_time */ bool skip; }; /** Number of hours that can be saved in time measurement */ static const size_t TIME_BUF = 1000; /** Stream when outputting in batches */ std::stringstream _ss; /** Saved time vector */ std::vector<StrTime> _time_vec; /** * @brief Calculate the elapsed time from the last save time * @param i Index of _time_vec * @return double Elapsed time */ double _calc_elapsed_time(size_t i); public: Tester(); /** * @brief The output will look like this: str/n * @param str */ void print(std::string str); /** * @brief The output will look like this: str v/n * @tparam T Classes that can flow directly to stream * @param str * @param v */ template <typename T> void print(std::string str, T v) { std::cout << str << " " << v << std::endl; } /** * @brief The output will look like this: str v1 v2/n * @tparam T Classes that can flow directly to stream * @param str * @param v1 * @param v2 */ template <typename T1, typename T2> void print(std::string str, T1 v1, T2 v2) { std::cout << str << " " << v1 << " " << v2 << std::endl; } /** * @brief Change the output depending on the authenticity of tf. * The output will look like this: str true_str/n or str false_str/n * @param str * @param tf * @param true_str * @param false_str */ void if_print(std::string str, bool tf, std::string true_str = "true", std::string false_str = "false"); /** * @brief Filling a stream with data * @param data */ template <typename T> void set_stream(T data) { _ss << data << " "; } /** * @brief Output the data put in by set_stream */ void put_all_stream(); /** * @brief Save description and time * @param str */ void set_time(std::string str, bool skip = false); /** * @brief Outputs the most recent measurement time * @param verbose 0: Time only, 1: Output with str */ void put_recent_time(int verbose = 1); /** * @brief Output all measurement results * @param verbose 0: Time only, 1: Output with str */ void put_all_time(int verbose = 1); /** * @brief Return the elapsed time from the last save time * @param index Index of _time_vec * @return double Elapsed time */ double get_elapsed_time(size_t index); /** * @brief Returns the size of the stored time * @return size_t */ size_t get_saved_time_size(); }; #endif
22.914063
108
0.577907
kotabrog
1b083c392d9a102b70f99fbfab61f86ef34ef17d
8,170
cpp
C++
app/viewport/render/task.cpp
mbd-shift/nodecad
cd8203c4b53608d015632a2b2fc324bcf6dec4b0
[ "MIT", "Unlicense" ]
2,059
2015-01-18T16:21:33.000Z
2022-03-25T21:54:24.000Z
app/viewport/render/task.cpp
hzeller/antimony
37324614f873d653594f25c2b8ee05fd4782e1d8
[ "Unlicense", "MIT" ]
209
2015-01-22T22:37:45.000Z
2021-04-14T20:49:40.000Z
app/viewport/render/task.cpp
hzeller/antimony
37324614f873d653594f25c2b8ee05fd4782e1d8
[ "Unlicense", "MIT" ]
187
2015-02-04T16:19:43.000Z
2022-02-12T17:12:24.000Z
#include <boost/python.hpp> #include <boost/format.hpp> #include "viewport/render/task.h" #include "viewport/render/instance.h" #include "fab/types/shape.h" #include "fab/util/region.h" #include "fab/tree/render.h" RenderTask::RenderTask(RenderInstance* parent, PyObject* s, QMatrix4x4 M, QVector2D clip, int refinement) : shape(s), M(M), clip(clip), refinement(refinement) { Py_INCREF(shape); future = QtConcurrent::run(this, &RenderTask::async); watcher.setFuture(future); connect(&watcher, &decltype(watcher)::finished, parent, &RenderInstance::onTaskFinished); } RenderTask::~RenderTask() { Py_DECREF(shape); } void RenderTask::halt() { halt_flag = 1; } RenderTask* RenderTask::getNext(RenderInstance* parent) const { return refinement > 1 ? new RenderTask(parent, shape, M, clip, refinement - 1) : NULL; } void RenderTask::async() { QTime timer; timer.start(); boost::python::extract<const Shape&> get_shape(shape); Q_ASSERT(get_shape.check()); const Shape& s = get_shape(); if (!std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax) && !std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax)) { if (std::isinf(s.bounds.zmin) || std::isinf(s.bounds.zmax)) { render2d(s); } else { render3d(s); } } // Set color from shape or to white color = (s.r != -1 && s.g != -1 && s.g != -1) ? QColor(s.r, s.g, s.b) : QColor(255, 255, 255); // Compensate for screen scale float scale = sqrt(pow(M(0, 0), 2) + pow(M(0, 1), 2) + pow(M(0, 2), 2)); size /= scale; render_time = timer.elapsed(); } void RenderTask::render3d(const Shape& s) { Transform T = getTransform(M); Shape transformed = s.map(T); Bounds b = render(&transformed, transformed.bounds, 1.0 / refinement); { // Apply a transform-less mapping to the bounds auto m = M; m.setColumn(3, {0, 0, 0, m(3,3)}); pos = m.inverted() * QVector3D( (b.xmin + b.xmax)/2, (b.ymin + b.ymax)/2, (b.zmin + b.zmax)/2); } size = {b.xmax - b.xmin, b.ymax - b.ymin, b.zmax - b.zmin}; flat = false; } void RenderTask::render2d(const Shape& s) { QMatrix4x4 matrix_flat = M; matrix_flat(0, 2) = 0; matrix_flat(1, 2) = 0; matrix_flat(2, 0) = 0; matrix_flat(2, 1) = 0; matrix_flat(2, 2) = 1; Shape s_flat(s.math, Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0)); Transform T_flat = getTransform(matrix_flat); Shape transformed = s_flat.map(T_flat); // Render the flattened shape, but with bounds equivalent to the shape's // position in a 3D bounding box. Bounds b3d_ = Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0.0001). map(getTransform(M)); Bounds b3d = render(&transformed, b3d_, 1.0 / refinement); { // Apply a transform-less mapping to the bounds auto m = M; m.setColumn(3, {0, 0, 0, m(3, 3)}); pos = m.inverted() * QVector3D((b3d.xmin + b3d.xmax)/2, (b3d.ymin + b3d.ymax)/2, (b3d.zmin + b3d.zmax)/2); } size = {b3d.xmax - b3d.xmin, b3d.ymax - b3d.ymin, b3d.zmax - b3d.zmin}; // Apply a gradient to the depth-map based on tilt if (M(1,2)) { bool direction = M(2,2) > 0; for (int j=0; j < depth.height(); ++j) { for (int i=0; i < depth.width(); ++i) { uint8_t pix = depth.pixel(i, j) & 0xff; if (pix) { if (direction) pix *= j / float(depth.height()); else pix *= 1 - j / float(depth.height()); depth.setPixel(i, j, pix | (pix << 8) | (pix << 16)); } } } } { // Set normals to a flat value (rather than derivatives) float xy = sqrt(pow(M(0,2),2) + pow(M(1,2),2)); float z = fabs(M(2,2)); float len = sqrt(pow(xy, 2) + pow(z, 2)); xy /= len; z /= len; shaded.fill((int(z * 255) << 16) | int(xy * 255)); } flat = true; } Transform RenderTask::getTransform(QMatrix4x4 m) { QMatrix4x4 mf = m.inverted(); QMatrix4x4 mi = mf.inverted(); Transform T = Transform( (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(0,0) % mf(0,1) % mf(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(1,0) % mf(1,1) % mf(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(2,0) % mf(2,1) % mf(2,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(0,0) % mi(0,1) % mi(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(1,0) % mi(1,1) % mi(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(2,0) % mi(2,1) % mi(2,2)).str()); return T; } //////////////////////////////////////////////////////////////////////////////// Bounds RenderTask::render(Shape* shape, Bounds b_, float scale) { // Screen-space clipping: // x and y are clipped to the window; // z is clipped assuming a voxel depth of max(width, height) const float xmin = -M(0,3) - clip.x() / 2; const float xmax = -M(0,3) + clip.x() / 2; const float ymin = -M(1,3) - clip.y() / 2; const float ymax = -M(1,3) + clip.y() / 2; const float zmin = -M(2,3) - fmax(clip.x(), clip.y()) / 2; const float zmax = -M(2,3) + fmax(clip.x(), clip.y()) / 2; Bounds b(fmax(xmin, b_.xmin), fmax(ymin, b_.ymin), fmax(zmin, b_.zmin), fmin(xmax, b_.xmax), fmin(ymax, b_.ymax), fmin(zmax, b_.zmax)); depth = QImage((b.xmax - b.xmin) * scale, (b.ymax - b.ymin) * scale, QImage::Format_RGB32); shaded = QImage(depth.width(), depth.height(), depth.format()); depth.fill(0x000000); uint16_t* d16(new uint16_t[depth.width() * depth.height()]); uint16_t** d16_rows(new uint16_t*[depth.height()]); uint8_t (*s8)[3] = new uint8_t[depth.width() * depth.height()][3]; uint8_t (**s8_rows)[3] = new decltype(s8)[depth.height()]; for (int i=0; i < depth.height(); ++i) { d16_rows[i] = &d16[depth.width() * i]; s8_rows[i] = &s8[depth.width() * i]; } memset(d16, 0, depth.width() * depth.height() * 2); memset(s8, 0, depth.width() * depth.height() * 3); Region r = (Region) { .imin=0, .jmin=0, .kmin=0, .ni=(uint32_t)depth.width(), .nj=(uint32_t)depth.height(), .nk=uint32_t(fmax(1, (b.zmax - b.zmin) * scale)) }; build_arrays(&r, b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax); render16(shape->tree.get(), r, d16_rows, &halt_flag, nullptr); shaded8(shape->tree.get(), r, d16_rows, s8_rows, &halt_flag, nullptr); free_arrays(&r); // Copy from bitmap arrays into a QImage for (int j=0; j < depth.height(); ++j) { for (int i=0; i < depth.width(); ++i) { uint16_t pix16 = d16_rows[j][i]; uint8_t pix8 = pix16 >> 8; uint8_t* norm = s8_rows[j][i]; if (pix8) { depth.setPixel(i, j, pix8 | (pix8 << 8) | (pix8 << 16)); if (pix16 < UINT16_MAX) { shaded.setPixel(i, j, norm[0] | (norm[1] << 8) | (norm[2] << 16)); } else { shaded.setPixel(i, j, 0 | (0 << 8) | (255 << 16)); } } } } delete [] s8; delete [] s8_rows; delete [] d16; delete [] d16_rows; return b; }
29.92674
80
0.487271
mbd-shift
db44cfafea70e2b41266ec35540566e5b8b146fb
8,579
cpp
C++
plugins/single_plugins/command.cpp
DurandA/wayfire
f7d3c51552684ac7527d58210d8ebdff2a4bbca1
[ "MIT" ]
1
2021-05-04T18:28:20.000Z
2021-05-04T18:28:20.000Z
plugins/single_plugins/command.cpp
paullinuxthemer/wayfire
b2e244949783e92e97f5197b0e29ae2ca2868b29
[ "MIT" ]
null
null
null
plugins/single_plugins/command.cpp
paullinuxthemer/wayfire
b2e244949783e92e97f5197b0e29ae2ca2868b29
[ "MIT" ]
null
null
null
#include <wayfire/plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/core.hpp> #include <linux/input.h> #include <linux/input-event-codes.h> #include <wayfire/signal-definitions.hpp> #include <wayfire/util/log.hpp> static bool begins_with(std::string word, std::string prefix) { if (word.length() < prefix.length()) return false; return word.substr(0, prefix.length()) == prefix; } /* Initial repeat delay passed */ static int repeat_delay_timeout_handler(void *callback) { (*reinterpret_cast<std::function<void()>*> (callback)) (); return 1; // disconnect }; /* Between each repeat */ static int repeat_once_handler(void *callback) { (*reinterpret_cast<std::function<void()>*> (callback)) (); return 1; // continue timer } /* Provides a way to bind specific commands to activator bindings. * * It supports 2 modes: * * 1. Regular bindings * 2. Repeatable bindings - for example, if the user binds a keybinding, then * after a specific delay the command begins to be executed repeatedly, until * the user released the key. In the config file, repeatable bindings have the * prefix repeatable_ * 3. Always bindings - bindings that can be executed even if a plugin is already * active, or if the screen is locked. They have a prefix always_ * */ class wayfire_command : public wf::plugin_interface_t { std::vector<wf::activator_callback> bindings; struct { uint32_t pressed_button = 0; uint32_t pressed_key = 0; std::string repeat_command; } repeat; wl_event_source *repeat_source = NULL, *repeat_delay_source = NULL; enum binding_mode { BINDING_NORMAL, BINDING_REPEAT, BINDING_ALWAYS, }; bool on_binding(std::string command, binding_mode mode, wf::activator_source_t source, uint32_t value) { /* We already have a repeatable command, do not accept further bindings */ if (repeat.pressed_key || repeat.pressed_button) return false; uint32_t act_flags = 0; if (mode == BINDING_ALWAYS) act_flags |= wf::PLUGIN_ACTIVATION_IGNORE_INHIBIT; if (!output->activate_plugin(grab_interface, act_flags)) return false; wf::get_core().run(command.c_str()); /* No repeat necessary in any of those cases */ if (mode != BINDING_REPEAT || source == wf::ACTIVATOR_SOURCE_GESTURE || value == 0) { output->deactivate_plugin(grab_interface); return true; } repeat.repeat_command = command; if (source == wf::ACTIVATOR_SOURCE_KEYBINDING) { repeat.pressed_key = value; } else { repeat.pressed_button = value; } repeat_delay_source = wl_event_loop_add_timer(wf::get_core().ev_loop, repeat_delay_timeout_handler, &on_repeat_delay_timeout); wl_event_source_timer_update(repeat_delay_source, wf::option_wrapper_t<int>("input/kb_repeat_delay")); wf::get_core().connect_signal("pointer_button", &on_button_event); wf::get_core().connect_signal("keyboard_key", &on_key_event); return true; } std::function<void()> on_repeat_delay_timeout = [=] () { repeat_delay_source = NULL; repeat_source = wl_event_loop_add_timer(wf::get_core().ev_loop, repeat_once_handler, &on_repeat_once); on_repeat_once(); }; std::function<void()> on_repeat_once = [=] () { uint32_t repeat_rate = wf::option_wrapper_t<int> ("input/kb_repeat_rate"); if (repeat_rate <= 0 || repeat_rate > 1000) return reset_repeat(); wl_event_source_timer_update(repeat_source, 1000 / repeat_rate); wf::get_core().run(repeat.repeat_command.c_str()); }; void reset_repeat() { if (repeat_delay_source) { wl_event_source_remove(repeat_delay_source); repeat_delay_source = NULL; } if (repeat_source) { wl_event_source_remove(repeat_source); repeat_source = NULL; } repeat.pressed_key = repeat.pressed_button = 0; output->deactivate_plugin(grab_interface); wf::get_core().disconnect_signal("pointer_button", &on_button_event); wf::get_core().disconnect_signal("keyboard_key", &on_key_event); } wf::signal_callback_t on_button_event = [=] (wf::signal_data_t *data) { auto ev = static_cast< wf::input_event_signal<wlr_event_pointer_button>*>(data); if (ev->event->button == repeat.pressed_button && ev->event->state == WLR_BUTTON_RELEASED) { reset_repeat(); } }; wf::signal_callback_t on_key_event = [=] (wf::signal_data_t *data) { auto ev = static_cast< wf::input_event_signal<wlr_event_keyboard_key>*>(data); if (ev->event->keycode == repeat.pressed_key && ev->event->state == WLR_KEY_RELEASED) { reset_repeat(); } }; public: void setup_bindings_from_config() { auto section = wf::get_core().config.get_section("command"); std::vector<std::string> command_names; const std::string exec_prefix = "command_"; for (auto command : section->get_registered_options()) { if (begins_with(command->get_name(), exec_prefix)) { command_names.push_back( command->get_name().substr(exec_prefix.length())); } } bindings.resize(command_names.size()); const std::string norepeat = "...norepeat..."; const std::string noalways = "...noalways..."; for (size_t i = 0; i < command_names.size(); i++) { auto command = exec_prefix + command_names[i]; auto regular_binding_name = "binding_" + command_names[i]; auto repeat_binding_name = "repeatable_binding_" + command_names[i]; auto always_binding_name = "always_binding_" + command_names[i]; auto check_activator = [&] (const std::string& name) { auto opt = section->get_option_or(name); if (opt) { auto value = wf::option_type::from_string< wf::activatorbinding_t> (opt->get_value_str()); if (value) return wf::create_option(value.value()); } return wf::option_sptr_t<wf::activatorbinding_t>{}; }; auto executable = section->get_option(command)->get_value_str(); auto repeatable_opt = check_activator(repeat_binding_name); auto regular_opt = check_activator(regular_binding_name); auto always_opt = check_activator(always_binding_name); using namespace std::placeholders; if (repeatable_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_REPEAT, _1, _2); output->add_activator(repeatable_opt, &bindings[i]); } else if (always_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_ALWAYS, _1, _2); output->add_activator(always_opt, &bindings[i]); } else if (regular_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_NORMAL, _1, _2); output->add_activator(regular_opt, &bindings[i]); } } } void clear_bindings() { for (auto& binding : bindings) output->rem_binding(&binding); bindings.clear(); } wf::signal_callback_t reload_config; void init() { grab_interface->name = "command"; grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT; using namespace std::placeholders; setup_bindings_from_config(); reload_config = [=] (wf::signal_data_t*) { clear_bindings(); setup_bindings_from_config(); }; wf::get_core().connect_signal("reload-config", &reload_config); } void fini() { wf::get_core().disconnect_signal("reload-config", &reload_config); clear_bindings(); } }; DECLARE_WAYFIRE_PLUGIN(wayfire_command);
31.892193
90
0.6038
DurandA
db46a53f1b80be09f414f81993846f8b94a43480
3,749
cpp
C++
Server/shared/SocketMgr.cpp
APistole/KnightOnline
80268e2fa971389a3e94c430966a7943c2631dbf
[ "MIT" ]
191
2016-03-05T16:44:15.000Z
2022-03-09T00:52:31.000Z
Server/shared/SocketMgr.cpp
APistole/KnightOnline
80268e2fa971389a3e94c430966a7943c2631dbf
[ "MIT" ]
128
2016-08-31T04:09:06.000Z
2022-01-14T13:42:56.000Z
Server/shared/SocketMgr.cpp
APistole/KnightOnline
80268e2fa971389a3e94c430966a7943c2631dbf
[ "MIT" ]
165
2016-03-05T16:43:59.000Z
2022-01-22T00:52:25.000Z
#include "stdafx.h" #include "SocketMgr.h" bool SocketMgr::s_bRunningCleanupThread = true; std::recursive_mutex SocketMgr::s_disconnectionQueueLock; std::queue<Socket *> SocketMgr::s_disconnectionQueue; Thread SocketMgr::s_cleanupThread; Atomic<uint32_t> SocketMgr::s_refCounter; uint32_t THREADCALL SocketCleanupThread(void * lpParam) { while (SocketMgr::s_bRunningCleanupThread) { SocketMgr::s_disconnectionQueueLock.lock(); while (!SocketMgr::s_disconnectionQueue.empty()) { Socket *pSock = SocketMgr::s_disconnectionQueue.front(); if (pSock->GetSocketMgr()) pSock->GetSocketMgr()->DisconnectCallback(pSock); SocketMgr::s_disconnectionQueue.pop(); } SocketMgr::s_disconnectionQueueLock.unlock(); sleep(100); } return 0; } SocketMgr::SocketMgr() : m_threadCount(0), m_bWorkerThreadsActive(false), m_bShutdown(false) { static bool bRefCounterInitialised = false; if (!bRefCounterInitialised) { s_refCounter = 0; bRefCounterInitialised = true; } IncRef(); Initialise(); } void SocketMgr::SpawnWorkerThreads() { if (m_bWorkerThreadsActive) return; m_bWorkerThreadsActive = true; m_thread = new Thread(SocketWorkerThread, this); if (!s_cleanupThread.isStarted()) s_cleanupThread.start(SocketCleanupThread); } uint32_t THREADCALL SocketMgr::SocketWorkerThread(void * lpParam) { SocketMgr *socketMgr = (SocketMgr *)lpParam; HANDLE cp = socketMgr->GetCompletionPort(); DWORD len; Socket * s = nullptr; OverlappedStruct * ov = nullptr; LPOVERLAPPED ol_ptr; while (socketMgr->m_bWorkerThreadsActive) { if (!GetQueuedCompletionStatus(cp, &len, (PULONG_PTR)&s, &ol_ptr, INFINITE)) { if (s != nullptr) s->Disconnect(); continue; } ov = CONTAINING_RECORD(ol_ptr, OverlappedStruct, m_overlap); if (ov->m_event == SOCKET_IO_THREAD_SHUTDOWN) { delete ov; return 0; } if (ov->m_event < NUM_SOCKET_IO_EVENTS) ophandlers[ov->m_event](s, len); } return 0; } void SocketMgr::Initialise() { m_completionPort = nullptr; } void SocketMgr::CreateCompletionPort() { SetCompletionPort(CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, (ULONG_PTR)0, 0)); } void SocketMgr::SetupWinsock() { WSADATA wsaData; WSAStartup(MAKEWORD(2,0), &wsaData); } void HandleReadComplete(Socket * s, uint32_t len) { if (s->IsDeleted()) return; s->m_readEvent.Unmark(); if (len) { s->GetReadBuffer().IncrementWritten(len); s->OnRead(); s->SetupReadEvent(); } else { // s->Delete(); // Queue deletion. s->Disconnect(); } } void HandleWriteComplete(Socket * s, uint32_t len) { if (s->IsDeleted()) return; s->m_writeEvent.Unmark(); s->BurstBegin(); // Lock s->GetWriteBuffer().Remove(len); if( s->GetWriteBuffer().GetContiguousBytes() > 0 ) s->WriteCallback(); else s->DecSendLock(); s->BurstEnd(); // Unlock } void HandleShutdown(Socket * s, uint32_t len) {} void SocketMgr::OnConnect(Socket *pSock) {} void SocketMgr::DisconnectCallback(Socket *pSock) {} void SocketMgr::OnDisconnect(Socket *pSock) { Guard lock(s_disconnectionQueueLock); s_disconnectionQueue.push(pSock); } void SocketMgr::ShutdownThreads() { OverlappedStruct * ov = new OverlappedStruct(SOCKET_IO_THREAD_SHUTDOWN); PostQueuedCompletionStatus(m_completionPort, 0, (ULONG_PTR)0, &ov->m_overlap); m_bWorkerThreadsActive = false; m_thread->waitForExit(); delete m_thread; } void SocketMgr::Shutdown() { if (m_bShutdown) return; ShutdownThreads(); DecRef(); m_bShutdown = true; } void SocketMgr::SetupSockets() { SetupWinsock(); } void SocketMgr::CleanupSockets() { if (s_cleanupThread.isStarted()) { s_bRunningCleanupThread = false; s_cleanupThread.waitForExit(); } WSACleanup(); } SocketMgr::~SocketMgr() { Shutdown(); }
19.42487
91
0.721792
APistole
db48a0c83037ef203780e5c422d63b26c3d86677
5,303
cpp
C++
src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtNetwork> class ClientServer : public QUdpSocket { Q_OBJECT public: enum Type { ConnectedClient, UnconnectedClient, Server }; ClientServer(Type type, const QString &host, quint16 port) : type(type) { switch (type) { case Server: if (bind(0, ShareAddress | ReuseAddressHint)) { printf("%d\n", localPort()); } else { printf("XXX\n"); } break; case ConnectedClient: connectToHost(host, port); startTimer(250); printf("ok\n"); break; case UnconnectedClient: peerAddress = host; peerPort = port; if (bind(QHostAddress::Any, port + 1, ShareAddress | ReuseAddressHint)) { startTimer(250); printf("ok\n"); } else { printf("XXX\n"); } break; } fflush(stdout); connect(this, SIGNAL(readyRead()), this, SLOT(readTestData())); } protected: void timerEvent(QTimerEvent *event) { static int n = 0; switch (type) { case ConnectedClient: write(QByteArray::number(n++)); break; case UnconnectedClient: writeDatagram(QByteArray::number(n++), peerAddress, peerPort); break; default: break; } QUdpSocket::timerEvent(event); } private slots: void readTestData() { printf("readData()\n"); switch (type) { case ConnectedClient: { while (bytesAvailable() || hasPendingDatagrams()) { QByteArray data = readAll(); printf("got %d\n", data.toInt()); } break; } case UnconnectedClient: { while (hasPendingDatagrams()) { QByteArray data; data.resize(pendingDatagramSize()); readDatagram(data.data(), data.size()); printf("got %d\n", data.toInt()); } break; } case Server: { while (hasPendingDatagrams()) { QHostAddress sender; quint16 senderPort; QByteArray data; data.resize(pendingDatagramSize()); readDatagram(data.data(), data.size(), &sender, &senderPort); printf("got %d\n", data.toInt()); printf("sending %d\n", data.toInt() * 2); writeDatagram(QByteArray::number(data.toInt() * 2), sender, senderPort); } break; } } fflush(stdout); } private: Type type; QHostAddress peerAddress; quint16 peerPort; }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); ClientServer::Type type; if (app.arguments().size() < 4) { qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]); return 1; } QString arg = app.arguments().at(1).trimmed().toLower(); if (arg == "connectedclient") { type = ClientServer::ConnectedClient; } else if (arg == "unconnectedclient") { type = ClientServer::UnconnectedClient; } else if (arg == "server") { type = ClientServer::Server; } else { qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]); return 1; } ClientServer clientServer(type, app.arguments().at(2), app.arguments().at(3).toInt()); return app.exec(); } #include "main.moc"
31.754491
112
0.561192
power-electro
db4a5dd01fea6491f5006a190a1ebe1138736b9a
872
cpp
C++
experiments/step_crawling/cpp_robot_server/server_node.cpp
yifan-hou/hybrid_servoing
4d3a2cc047a3bad5ded19934247b5ab5e598f911
[ "MIT" ]
16
2020-04-15T04:45:02.000Z
2022-01-13T03:28:46.000Z
experiments/step_crawling/cpp_robot_server/server_node.cpp
yifan-hou/hybrid_servoing
4d3a2cc047a3bad5ded19934247b5ab5e598f911
[ "MIT" ]
null
null
null
experiments/step_crawling/cpp_robot_server/server_node.cpp
yifan-hou/hybrid_servoing
4d3a2cc047a3bad5ded19934247b5ab5e598f911
[ "MIT" ]
null
null
null
#include "step_crawling.h" #include <RobotUtilities/utilities.h> #include <ati_netft/ati_netft.h> #include <abb_egm/abb_egm.h> #include <ur_socket/ur_socket.h> using namespace std; using namespace RUT; int main(int argc, char* argv[]) { ROS_INFO_STREAM("Step crawling task server node starting"); ros::init(argc, argv, "step_crawling_node"); ros::NodeHandle hd; Clock::time_point time0 = std::chrono::high_resolution_clock::now(); ATINetft ati; cout << "[test] initializing ft sensor:\n"; ati.init(hd, time0); cout << "[test] initializing robot:\n"; URSocket *robot = URSocket::Instance(); robot->init(hd, time0); StepCrawlingTaskServer task_server; task_server.init(&hd, time0, &ati, robot); task_server.initStepCrawlingTaskServer(); task_server.hostServices(); ROS_INFO_STREAM(endl << "[MAIN] Rest in Peace." << endl); return 0; }
26.424242
70
0.716743
yifan-hou
db4d1277a1b457e6e3ef93a80a16b4171e2ff0ee
6,543
cpp
C++
src/writers/r_writer.cpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
src/writers/r_writer.cpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
src/writers/r_writer.cpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
#include "stats/analyzer.hpp" #include "writers/r_writer.hpp" using namespace Anaquin; // Defined in main.cpp extern Path __output__; // Defined in resources.cpp extern Scripts PlotLinear(); // Defined in resources.cpp extern Scripts PlotFold(); // Defined in resources.cpp extern Scripts PlotLogistic(); Scripts RWriter::createLogistic(const FileName &file, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, bool showLOQ) { return (boost::format(PlotLogistic()) % date() % __full_command__ % __output__ % file % title % xlab % ylab % ("log2(data$" + expected + ")") % ("data$" + measured) % (showLOQ ? "TRUE" : "FALSE")).str(); } Scripts RWriter::createFold(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, bool shouldLog, const std::string &extra) { const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected); const auto obs = shouldLog ? ("log2(data$" + measured + ")") : ("data$" + measured); return (boost::format(PlotFold()) % date() % __full_command__ % path % file % title % xlab % ylab % exp % obs % "TRUE" % extra).str(); } Scripts RWriter::createMultiLinear(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, const std::string &xname, bool showLOQ, bool shouldLog, const std::string &extra) { const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected); const auto obs = shouldLog ? ("log2(data[,3:ncol(data)])") : ("data[,3:ncol(data)]"); return (boost::format(PlotLinear()) % date() % __full_command__ % path % file % title % xlab % ylab % exp % obs % xname % (showLOQ ? "TRUE" : "FALSE") % extra).str(); } Scripts RWriter::createRConjoint(const FileName &file, const Scripts &script, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &x, const std::string &y) { return (boost::format(script) % date() % __full_command__ % path % file % title % xlab % ylab % x % y).str(); } Scripts RWriter::createRLinear(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, const std::string &xname, bool showLOQ, const std::string &script) { return (boost::format(script.empty() ? PlotLinear() : script) % date() % __full_command__ % path % file % title % xlab % ylab % expected % measured % xname % (showLOQ ? "TRUE" : "FALSE")).str(); } Scripts RWriter::createScript(const FileName &file, const Scripts &script) { return (boost::format(script) % date() % __full_command__ % __output__ % file).str(); } Scripts RWriter::createScript(const FileName &file, const Scripts &script, const std::string &x) { return (boost::format(script) % date() % __full_command__ % __output__ % file % x).str(); }
42.487013
96
0.32508
danielnavarrogomez
db4e7ed1ba533943e6b3cde934a3bab7d6e3157a
2,209
cpp
C++
src/bug_10.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_10.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_10.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
#include "advent.h" inline void reverse(std::vector<int>& vect, int from, int length) { int const vsize = vect.size(); if (length > vsize) return; for (int i = 0; i < length / 2; ++i) std::swap(vect[(from + i) % vsize], vect[(from + length - i - 1) % vsize]); } inline std::string knotHash(std::string const& input) { int const numRounds = 64; int const seqLength = 256; int const xorLength = 16; std::vector<int> sequence; std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); }); std::vector<int> lengths; std::transform(input.begin(), input.end(), std::back_inserter(lengths), [](char symbol) { return static_cast<int>(symbol); }); for (int n : { 17, 31, 73, 47, 23 }) lengths.push_back(n); int curInd = 0; int skipSize = 0; for (int r = 0; r < numRounds; ++r) { for (int length : lengths) { if (length > static_cast<int>(sequence.size())) continue; reverse(sequence, curInd, length); curInd += (length + skipSize) % seqLength; skipSize = (skipSize + 1) % seqLength; } } std::string xored(2 * seqLength / xorLength, 0); for (int i = 0; i < seqLength / xorLength; ++i) { int xorResult = 0; for (int j = 0; j < xorLength; ++j) { xorResult ^= sequence[i * xorLength + j]; } char hex1 = (xorResult / 16) % 16; char hex0 = xorResult % 16; if (hex1 < 10) xored[i * 2] = hex1 + '0'; else xored[i * 2] = hex1 - 10 + 'a'; if (hex0 < 10) xored[i * 2 + 1] = hex0 + '0'; else xored[i * 2 + 1] = hex0 - 10 + 'a'; } return xored; } void BugFix<10>::solve1st() { int const seqLength = 256; std::vector<int> sequence; std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); }); std::string word; int curInd = 0; int skipSize = 0; while (std::getline(*mIn, word, ',')) { int const length = std::stoi(word); if (length > static_cast<int>(sequence.size())) continue; reverse(sequence, curInd, length); curInd += (length + skipSize) % seqLength; ++skipSize; } *mOut << sequence[0] * sequence[1] << std::endl; } void BugFix<10>::solve2nd() { std::string input; *mIn >> input; *mOut << knotHash(input) << std::endl; }
22.773196
127
0.609325
happanda
db4eb7d9e27d1699f6a72d0cf9816180da7d0803
4,626
cpp
C++
util/generic/yexception_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
39
2015-03-12T19:49:24.000Z
2020-11-11T09:58:15.000Z
util/generic/yexception_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
null
null
null
util/generic/yexception_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
11
2016-01-14T16:42:00.000Z
2022-01-17T11:47:33.000Z
#include "yexception.h" static inline void Throw1DontMove() { ythrow yexception() << "blabla"; //dont move this line } static inline void Throw2DontMove() { ythrow yexception() << 1 << " qw " << 12.1; //dont move this line } #include <library/unittest/registar.h> #include <util/stream/ios.h> #include "yexception_ut.h" #if defined (_MSC_VER) # pragma warning(disable:4702) /*unreachable code*/ #endif static void CallbackFun(int i) { throw i; } static TOutputStream* OUTS = 0; class TExceptionTest: public TTestBase { UNIT_TEST_SUITE(TExceptionTest); UNIT_TEST_EXCEPTION(TestException, yexception) UNIT_TEST_EXCEPTION(TestLineInfo, yexception) UNIT_TEST(TestFormat1) UNIT_TEST(TestRaise1) UNIT_TEST(TestVirtuality) UNIT_TEST(TestVirtualInheritance) UNIT_TEST(TestMixedCode) UNIT_TEST_SUITE_END(); private: inline void TestVirtualInheritance() { TStringStream ss; OUTS = &ss; class TA { public: inline TA() { *OUTS << "A"; } }; class TB { public: inline TB() { *OUTS << "B"; } }; class TC: public virtual TB, public virtual TA { public: inline TC() { *OUTS << "C"; } }; class TD: public virtual TA { public: inline TD() { *OUTS << "D"; } }; class TE: public TC, public TD { public: inline TE() { *OUTS << "E"; } }; TE e; UNIT_ASSERT_EQUAL(ss.Str(), "BACDE"); } inline void TestVirtuality() { try { ythrow TFileError() << "1"; UNIT_ASSERT(false); } catch (const TIoException&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << 1; UNIT_ASSERT(false); } catch (const TSystemError&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << '1'; UNIT_ASSERT(false); } catch (const yexception&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << 1.0; UNIT_ASSERT(false); } catch (const TFileError&) { } catch (...) { UNIT_ASSERT(false); } } inline void TestFormat1() { try { throw yexception() << 1 << " qw " << 12.1; UNIT_ASSERT(false); } catch (...) { const Stroka err = CurrentExceptionMessage(); UNIT_ASSERT_VALUES_EQUAL(err, "1 qw 12.1"); } } inline void TestRaise1() { try { Throw2DontMove(); UNIT_ASSERT(false); } catch (...) { Stroka err = CurrentExceptionMessage(); char *ptr = err.begin(); while ((ptr = strchr(ptr, '\\')) != 0) *ptr = '/'; UNIT_ASSERT_VALUES_EQUAL(err, "util/generic/yexception_ut.cpp:8: 1 qw 12.1"); } } inline void TestException() { ythrow yexception() << "blablabla"; } inline void TestLineInfo() { try { Throw1DontMove(); } catch (...) { UNIT_ASSERT_VALUES_EQUAL(CurrentExceptionMessage(), "yexception_ut.cpp:4: blabla"); throw; } } //! tests propagation of an exception through C code //! @note on some platforms, for example GCC on 32-bit Linux without -fexceptions option, //! throwing an exception from a C++ callback through C code aborts program inline void TestMixedCode() { const int N = 26082009; try { TestCallback(&CallbackFun, N); UNIT_ASSERT(false); } catch (int i) { UNIT_ASSERT_VALUES_EQUAL(i, N); } } }; UNIT_TEST_SUITE_REGISTRATION(TExceptionTest);
27.211765
99
0.444877
jjzhang166
db52b53a633360f262474ffbf9e3a3fb7a3ee542
11,578
cpp
C++
lib/orvis/Scene.cpp
f-schroeder/orvis
440de86bc4331100f24efb192d8781240a59f80e
[ "MIT" ]
null
null
null
lib/orvis/Scene.cpp
f-schroeder/orvis
440de86bc4331100f24efb192d8781240a59f80e
[ "MIT" ]
null
null
null
lib/orvis/Scene.cpp
f-schroeder/orvis
440de86bc4331100f24efb192d8781240a59f80e
[ "MIT" ]
null
null
null
#include "Scene.hpp" #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/config.h> #include <numeric> #include <execution> #include "Util.hpp" #include "stb/stb_image.h" Scene::Scene(const std::filesystem::path& filename) { const auto path = util::resourcesPath / filename; const auto pathString = path.string(); Assimp::Importer importer; std::cout << "Loading model from " << filename.string() << std::endl; // aiComponent_TANGENTS_AND_BITANGENTS flips the winding order (assimp-internal bug) const aiScene * assimpScene = importer.ReadFile(pathString.c_str(), aiProcess_GenSmoothNormals | aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_JoinIdenticalVertices | aiProcess_RemoveComponent | aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS | aiComponent_CAMERAS | aiComponent_LIGHTS /*| aiComponent_TANGENTS_AND_BITANGENTS*/ | aiComponent_COLORS | aiProcess_SplitLargeMeshes | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_OptimizeMeshes | aiProcess_SortByPType | aiProcess_FindDegenerates | aiProcess_FindInvalidData); if (!assimpScene || assimpScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) { const std::string err = importer.GetErrorString(); throw std::runtime_error("Assimp import failed: " + err); } std::cout << "Assimp import complete. Processing Model..." << std::endl; // - - - M E S H E S - - - if (assimpScene->HasMeshes()) { const auto numMeshes = assimpScene->mNumMeshes; m_meshes.resize(numMeshes); for (int i = 0; i < static_cast<int>(numMeshes); ++i) { m_meshes[i] = std::shared_ptr<Mesh>(new Mesh(assimpScene->mMeshes[i], assimpScene->mMaterials[assimpScene->mMeshes[i]->mMaterialIndex], path)); } } // - - - M O D E L M A T R I C E S - - - static_assert(sizeof(aiMatrix4x4) == sizeof(glm::mat4)); std::function<void(aiNode* node, glm::mat4 trans)> traverseChildren = [this, &traverseChildren](aiNode* node, glm::mat4 trans) { // check if transformation exists if (std::none_of(&node->mTransformation.a1, (&node->mTransformation.d4) + 1, [](float f) { return std::isnan(f) || std::isinf(f); })) { // accumulate transform const glm::mat4 transform = reinterpret_cast<glm::mat4&>(node->mTransformation); trans *= transform; } // assign transformation to meshes #pragma omp parallel for for (int i = 0; i < static_cast<int>(node->mNumMeshes); ++i) { m_meshes[node->mMeshes[i]]->modelMatrix = trans; } // recursively work on the child nodes #pragma omp parallel for for (int i = 0; i < static_cast<int>(node->mNumChildren); ++i) { traverseChildren(node->mChildren[i], trans); } }; const auto root = assimpScene->mRootNode; std::thread modelMatThread([&]() { traverseChildren(root, glm::mat4(1.0f)); calculateBoundingBox(); }); { // running in parallel --> no model-matrices available in this scope! updateMultiDrawBuffers(); updateMaterialBuffer(); m_cullingProgram.attachNew(GL_COMPUTE_SHADER, ShaderFile::load("compute/viewFrustumCulling.comp")); m_lightIndexBuffer.resize(1, GL_DYNAMIC_STORAGE_BIT); } modelMatThread.join(); updateModelMatrices(); updateBoundingBoxBuffer(); std::cout << "Loading complete: " << filename.string() << std::endl; importer.FreeScene(); } void Scene::render(const Program& program, bool overwriteCameraBuffer) const { // BINDINGS m_indirectDrawBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::indirectDraw); m_bBoxBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::boundingBoxes); m_modelMatBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::modelMatrices); m_materialBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::materials); m_lightBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::lights); if (overwriteCameraBuffer) m_camera->uploadToGpu(); // CULLING m_cullingProgram.use(); glDispatchCompute(static_cast<GLuint>(glm::ceil(m_indirectDrawBuffer.size() / 64.0f)), 1, 1); glMemoryBarrier(GL_COMMAND_BARRIER_BIT | GL_SHADER_STORAGE_BARRIER_BIT); // DRAW program.use(); m_multiDrawVao.bind(); glBindBuffer(GL_DRAW_INDIRECT_BUFFER, *m_indirectDrawBuffer.id()); glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, nullptr, static_cast<GLsizei>(m_indirectDrawBuffer.size()), 0); } const Bounds& Scene::calculateBoundingBox() { struct Reduction { Bounds operator()(Bounds b, const std::shared_ptr<Mesh>& x) const { return b + Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f)); } Bounds operator()(const std::shared_ptr<Mesh>& x, Bounds b) const { return b + Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f)); } Bounds operator()(const std::shared_ptr<Mesh>& a, const std::shared_ptr<Mesh>& b) const { Bounds bounds; bounds = bounds + Bounds(a->modelMatrix * glm::vec4(a->bounds.min, 1.0f), a->modelMatrix * glm::vec4(a->bounds.max, 1.0f)); return bounds + Bounds(b->modelMatrix * glm::vec4(b->bounds.min, 1.0f), b->modelMatrix * glm::vec4(b->bounds.max, 1.0f)); } Bounds operator()(Bounds b, const Bounds& x) const { return b + x; } }; bounds = std::reduce(std::execution::par_unseq, m_meshes.begin(), m_meshes.end(), Bounds(), Reduction()); if (m_camera) m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0])); return bounds; } void Scene::updateModelMatrices() { std::vector<glm::mat4> modelMatrices(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(modelMatrices.size()); ++i) modelMatrices[i] = m_meshes[i]->modelMatrix; if (modelMatrices.size() != static_cast<size_t>(m_modelMatBuffer.size())) m_modelMatBuffer.resize(modelMatrices.size(), GL_DYNAMIC_STORAGE_BIT); m_modelMatBuffer.assign(modelMatrices); } void Scene::updateBoundingBoxBuffer() { std::vector<Bounds> boundingBoxes(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(boundingBoxes.size()); ++i) boundingBoxes[i] = m_meshes[i]->bounds; if (boundingBoxes.size() != static_cast<size_t>(m_bBoxBuffer.size())) m_bBoxBuffer.resize(boundingBoxes.size(), GL_DYNAMIC_STORAGE_BIT); m_bBoxBuffer.assign(boundingBoxes); } void Scene::updateMaterialBuffer() { std::vector<Material> materials(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(materials.size()); ++i) materials[i] = m_meshes[i]->material; if (materials.size() != static_cast<size_t>(m_materialBuffer.size())) m_materialBuffer.resize(materials.size(), GL_DYNAMIC_STORAGE_BIT); m_materialBuffer.assign(materials); } void Scene::updateLightBuffer() { std::vector<Light> lights(m_lights.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(lights.size()); ++i) { m_lights[i]->recalculateLightSpaceMatrix(*this); lights[i] = *m_lights[i]; } if (lights.size() != static_cast<size_t>(m_lightBuffer.size())) m_lightBuffer.resize(lights.size(), GL_DYNAMIC_STORAGE_BIT); m_lightBuffer.assign(lights); } void Scene::updateShadowMaps() { for (int i = 0; i < static_cast<int>(m_lights.size()); ++i) { m_lightIndexBuffer.assign(i); m_lightIndexBuffer.bind(GL_UNIFORM_BUFFER, BufferBinding::lightIndex); m_lights[i]->updateShadowMap(*this); } } void Scene::addMesh(const std::shared_ptr<Mesh>& mesh) { m_meshes.push_back(mesh); std::thread bBoxThread([&]() { calculateBoundingBox(); }); updateModelMatrices(); updateMultiDrawBuffers(); updateBoundingBoxBuffer(); updateMaterialBuffer(); bBoxThread.join(); } void Scene::addLight(const std::shared_ptr<Light>& light) { m_lights.push_back(light); updateLightBuffer(); updateShadowMaps(); } void Scene::setCamera(const std::shared_ptr<Camera>& camera) { m_camera = camera; m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0])); } std::shared_ptr<Camera> Scene::getCamera() const { return m_camera; } const std::deque<std::shared_ptr<Mesh>>& Scene::getMeshes() const { return m_meshes; } void Scene::reorderMeshes() { std::deque<std::shared_ptr<Mesh>> orderedMeshes; for (const auto& mesh : m_meshes) { if (mesh->isTransparent()) orderedMeshes.push_back(mesh); else orderedMeshes.push_front(mesh); } m_meshes = orderedMeshes; updateModelMatrices(); updateMultiDrawBuffers(); updateBoundingBoxBuffer(); updateMaterialBuffer(); } void Scene::updateMultiDrawBuffers() { std::vector<GLuint> allIndices; std::vector<glm::vec4> allVertices; std::vector<glm::vec4> allNormals; std::vector<glm::vec2> allUVs; std::vector<IndirectDrawCommand> indirectDrawParams; GLuint start = 0; GLuint baseVertexOffset = 0; for (const auto& mesh : m_meshes) { allIndices.insert(allIndices.end(), mesh->indices.begin(), mesh->indices.end()); allVertices.insert(allVertices.end(), mesh->vertices.begin(), mesh->vertices.end()); allNormals.insert(allNormals.end(), mesh->normals.begin(), mesh->normals.end()); allUVs.insert(allUVs.end(), mesh->uvs.begin(), mesh->uvs.end()); const auto count = static_cast<GLuint>(mesh->indices.size()); indirectDrawParams.push_back({ count, 1U, start, baseVertexOffset, 0U }); start += count; baseVertexOffset += static_cast<GLuint>(mesh->vertices.size()); } m_multiDrawIndexBuffer.resize(allIndices.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawIndexBuffer.assign(allIndices); m_multiDrawVertexBuffer.resize(allVertices.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawVertexBuffer.assign(allVertices); m_multiDrawNormalBuffer.resize(allNormals.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawNormalBuffer.assign(allNormals); m_multiDrawUVBuffer.resize(allUVs.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawUVBuffer.assign(allUVs); m_indirectDrawBuffer.resize(indirectDrawParams.size(), GL_DYNAMIC_STORAGE_BIT); m_indirectDrawBuffer.assign(indirectDrawParams); m_multiDrawVao.format(VertexAttributeBinding::vertices, 4, GL_FLOAT, false, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawVertexBuffer, VertexAttributeBinding::vertices, 0, sizeof(glm::vec4)); m_multiDrawVao.binding(VertexAttributeBinding::vertices); m_multiDrawVao.format(VertexAttributeBinding::normals, 4, GL_FLOAT, true, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawNormalBuffer, VertexAttributeBinding::normals, 0, sizeof(glm::vec4)); m_multiDrawVao.binding(VertexAttributeBinding::normals); m_multiDrawVao.format(VertexAttributeBinding::texCoords, 2, GL_FLOAT, false, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawUVBuffer, VertexAttributeBinding::texCoords, 0, sizeof(glm::vec2)); m_multiDrawVao.binding(VertexAttributeBinding::texCoords); m_multiDrawVao.setElementBuffer(m_multiDrawIndexBuffer); }
34.561194
155
0.682156
f-schroeder
db57a0d8321b3e7228a9299300d4758815940177
58
cpp
C++
contests/Codeforces Round #599 Div 2/Character_swap_hard.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
2
2020-08-27T18:21:04.000Z
2020-08-30T13:24:39.000Z
contests/Codeforces Round #599 Div 2/Character_swap_hard.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
contests/Codeforces Round #599 Div 2/Character_swap_hard.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
// @TODO // https://codeforces.com/contest/1243/problem/B2
29
49
0.724138
Razdeep
db58527125571dfd22175d05ec81f1e14c2605fd
3,485
cpp
C++
GeneratorSource/Source/Panels/PanelList.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
GeneratorSource/Source/Panels/PanelList.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
GeneratorSource/Source/Panels/PanelList.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
/* List of all Panels * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <QFile> #include <QTextStream> #include <QMessageBox> #include "Common/Qt/StringException.h" #include "Common/Qt/QtJsonTools.h" #include "JsonSettings.h" #include "JsonProgram.h" #include "Tools/PersistentSettings.h" #include "PanelList.h" #include <iostream> using std::cout; using std::endl; namespace PokemonAutomation{ const std::vector<std::unique_ptr<ConfigSet>>& SETTINGS_LIST(){ static std::vector<std::unique_ptr<ConfigSet>> list; if (!list.empty()){ return list; } QString path = settings.path + CONFIG_FOLDER_NAME + "/SettingsList.txt"; QFile file(path); if (!file.open(QFile::ReadOnly)){ // QMessageBox box; // box.critical(nullptr, "Error", "Unable to open settings list: " + settings_path); return list; } cout << "File = " << path.toUtf8().data() << endl; QTextStream stream(&file); while (!stream.atEnd()){ QString line = stream.readLine(); if (line.isEmpty()){ continue; } cout << "Open: " << line.toUtf8().data() << endl; try{ QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json"; list.emplace_back(new Settings_JsonFile(path)); }catch (const StringException& str){ cout << "Error: " << str.message().toUtf8().data() << endl; } } file.close(); return list; } const std::map<QString, ConfigSet*>& SETTINGS_MAP(){ static std::map<QString, ConfigSet*> map; if (!map.empty()){ return map; } for (const auto& program : SETTINGS_LIST()){ auto ret = map.emplace(program->name(), program.get()); if (!ret.second){ throw StringException("Duplicate program name: " + program->name()); } } return map; } const std::vector<std::unique_ptr<Program>>& PROGRAM_LIST(){ static std::vector<std::unique_ptr<Program>> list; if (!list.empty()){ return list; } QString path = settings.path + CONFIG_FOLDER_NAME + "/ProgramList.txt"; QFile file(path); if (!file.open(QFile::ReadOnly)){ // QMessageBox box; // box.critical(nullptr, "Error", "Unable to open programs list: " + settings_path); return list; } cout << "File = " << path.toUtf8().data() << endl; QTextStream stream(&file); while (!stream.atEnd()){ QString line = stream.readLine(); if (line.isEmpty()){ continue; } cout << "Open: " << line.toUtf8().data() << endl; try{ QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json"; list.emplace_back(new Program_JsonFile(path)); }catch (const StringException& str){ cout << "Error: " << str.message().toUtf8().data() << endl; } } file.close(); return list; } const std::map<QString, Program*>& PROGRAM_MAP(){ static std::map<QString, Program*> map; if (map.empty()){ for (const auto& program : PROGRAM_LIST()){ auto ret = map.emplace(program->name(), program.get()); if (!ret.second){ throw StringException("Duplicate program name: " + program->name()); } } } return map; } }
28.104839
92
0.55868
ercdndrs
db5b4cd53cee3cd795f7a29cf3eeea0d2529fa5a
3,580
cpp
C++
third_party/libosmium/test/t/basic/test_node.cpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
1
2016-11-29T15:02:40.000Z
2016-11-29T15:02:40.000Z
third_party/libosmium/test/t/basic/test_node.cpp
aaronbenz/osrm-backend
758d4023050d1f49971f919cea872a2276dafe14
[ "BSD-2-Clause" ]
1
2019-02-04T18:10:57.000Z
2019-02-04T18:10:57.000Z
third_party/libosmium/test/t/basic/test_node.cpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
null
null
null
#include "catch.hpp" #include <boost/crc.hpp> #include <osmium/osm/crc.hpp> #include <osmium/osm/node.hpp> #include "helper.hpp" TEST_CASE("Basic_Node") { osmium::CRC<boost::crc_32_type> crc32; SECTION("node_builder") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); node.set_id(17) .set_version(3) .set_visible(true) .set_changeset(333) .set_uid(21) .set_timestamp(123); REQUIRE(osmium::item_type::node == node.type()); REQUIRE(node.type_is_in(osmium::osm_entity_bits::node)); REQUIRE(node.type_is_in(osmium::osm_entity_bits::nwr)); REQUIRE(17l == node.id()); REQUIRE(17ul == node.positive_id()); REQUIRE(3 == node.version()); REQUIRE(true == node.visible()); REQUIRE(false == node.deleted()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); REQUIRE(std::string("foo") == node.user()); REQUIRE(123 == node.timestamp()); REQUIRE(osmium::Location(3.5, 4.7) == node.location()); REQUIRE(2 == node.tags().size()); crc32.update(node); REQUIRE(crc32().checksum() == 0xc696802f); node.set_visible(false); REQUIRE(false == node.visible()); REQUIRE(true == node.deleted()); } SECTION("node_default_attributes") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); REQUIRE(0l == node.id()); REQUIRE(0ul == node.positive_id()); REQUIRE(0 == node.version()); REQUIRE(true == node.visible()); REQUIRE(0 == node.changeset()); REQUIRE(0 == node.uid()); REQUIRE(std::string("") == node.user()); REQUIRE(0 == node.timestamp()); REQUIRE(osmium::Location() == node.location()); REQUIRE(0 == node.tags().size()); } SECTION("set_node_attributes_from_string") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); node.set_id("-17") .set_version("3") .set_visible(true) .set_changeset("333") .set_uid("21"); REQUIRE(-17l == node.id()); REQUIRE(17ul == node.positive_id()); REQUIRE(3 == node.version()); REQUIRE(true == node.visible()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); } SECTION("large_id") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); int64_t id = 3000000000l; node.set_id(id); REQUIRE(id == node.id()); REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id()); node.set_id(-id); REQUIRE(-id == node.id()); REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id()); } SECTION("tags") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); REQUIRE(nullptr == node.tags().get_value_by_key("fail")); REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity")); REQUIRE(std::string("pub") == node.get_value_by_key("amenity")); REQUIRE(std::string("default") == node.tags().get_value_by_key("fail", "default")); REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity", "default")); REQUIRE(std::string("pub") == node.get_value_by_key("amenity", "default")); } }
28.412698
87
0.603631
Mapotempo
db5b6d341ba5c92e5aad480e3a7e19853caf3240
1,051
cpp
C++
dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp
MrCarZ/cses-solutions
9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7
[ "MIT" ]
null
null
null
dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp
MrCarZ/cses-solutions
9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7
[ "MIT" ]
null
null
null
dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp
MrCarZ/cses-solutions
9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int MAXN = 2E+5 + 5; const int MAXX = 1E+9 + 7; int n, vec[MAXN],vec2[MAXN],dp[MAXN]; vector<int> fenwick(MAXN, 0); void add(int pos, int val){ for(int i = pos; i<=n; i+=i&(-i)){ fenwick[i] = max(val, fenwick[i]); } } int get(int pos){ int ans = -MAXX; for(int i = pos; i>0; i-=i&(-i)){ ans = max(ans, fenwick[i]); } return ans; } int main(){ ios::sync_with_stdio(0); cin>>n; map<int,int> comp; for(int i = 1; i<=n; i++){ cin>>vec[i]; vec2[i] = vec[i]; } sort(vec2, vec2+n+1); int counter = 1; for(int i = 1; i<=n; i++){ if(comp[vec2[i]] == 0){ comp[vec2[i]] = counter++; } } for(int i = 1; i<=n; i++) {vec[i] = comp[vec[i]];} int ans = -MAXX; for(int i = 1; i<=n; i++){ dp[i] = 1; dp[i] = max(get(vec[i]-1)+1, dp[i]); add(vec[i], dp[i]); ans = max(ans, dp[i]); } cout<<ans<<'\n'; return 0; }
17.229508
54
0.444339
MrCarZ
db6005fb4b088d339a2014db33c55affca188efe
7,852
cpp
C++
training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp
asct/industrial_training
f69c54cad966382ce93b34138696a99abc66f444
[ "Apache-2.0" ]
324
2015-01-31T07:35:37.000Z
2022-03-27T09:30:14.000Z
training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp
asct/industrial_training
f69c54cad966382ce93b34138696a99abc66f444
[ "Apache-2.0" ]
226
2015-01-20T17:15:56.000Z
2022-01-19T04:55:23.000Z
training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp
asct/industrial_training
f69c54cad966382ce93b34138696a99abc66f444
[ "Apache-2.0" ]
219
2015-03-29T03:05:11.000Z
2022-03-23T11:12:43.000Z
/* * OpenCloseGraspActionServer.cpp * * Created on: Apr 19, 2013 * Author: jnicho */ /* * Software License Agreement (BSD License) * * Copyright (c) 2011, Southwest Research Institute * 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 Southwest Research Institute, 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. */ #include <ros/ros.h> #include <actionlib/server/action_server.h> #include <object_manipulation_msgs/GraspHandPostureExecutionAction.h> #include <object_manipulation_msgs/GraspHandPostureExecutionGoal.h> #include <robot_io/DigitalOutputUpdate.h> #include <soem_beckhoff_drivers/DigitalMsg.h> using namespace object_manipulation_msgs; using namespace actionlib; typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType; static const std::string OUTPUT_TOPIC = "/digital_outputs"; static const std::string INPUT_TOPIC = "/digital_inputs"; static const std::string OUTPUT_SERVICE = "/digital_output_update"; class SimpleGraspActionServer { private: typedef ActionServer<GraspHandPostureExecutionAction> GEAS; typedef GEAS::GoalHandle GoalHandle; public: SimpleGraspActionServer(ros::NodeHandle &n) : node_(n), action_server_(node_, "grasp_execution_action", boost::bind(&SimpleGraspActionServer::goalCB, this, _1), boost::bind(&SimpleGraspActionServer::cancelCB, this, _1), false), use_sensor_feedback_(false), suction_on_output_channel_(DigitalOutputType::SUCTION1_ON), suction_check_input_channel_(DigitalOutputType::SUCTION1_ON) { } ~SimpleGraspActionServer() { } void init() { ros::NodeHandle pn("/"); std::string nodeName = ros::this_node::getName(); // service client service_client_ = pn.serviceClient<robot_io::DigitalOutputUpdate>(OUTPUT_SERVICE); while(!service_client_.waitForExistence(ros::Duration(5.0f))) { ROS_INFO_STREAM(nodeName<<": Waiting for "<<OUTPUT_SERVICE<<" to start"); } if(!fetchParameters() ) { ROS_ERROR_STREAM(nodeName<<": Did not find required ros parameters, exiting"); ros::shutdown(); return; } if(!validateChannelIndices()) { ROS_ERROR_STREAM(nodeName<<": One or more parameter values are invalid"); ros::shutdown(); return; } action_server_.start(); ROS_INFO_STREAM(nodeName<<": Grasp execution action node started"); } private: void goalCB(GoalHandle gh) { std::string nodeName = ros::this_node::getName(); ROS_INFO("%s",(nodeName + ": Received grasping goal").c_str()); robot_io::DigitalOutputUpdate::Request req; robot_io::DigitalOutputUpdate::Response res; bool success; switch(gh.getGoal()->goal) { case GraspHandPostureExecutionGoal::PRE_GRASP: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = true; if(service_client_.call(req,res)) { gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command succeeded"); } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command aborted"); } break; case GraspHandPostureExecutionGoal::GRASP: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Grasp command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = false; success = service_client_.call(req,res); if(success) { if(use_sensor_feedback_ && !checkSensorState()) { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Grasp command aborted"); break; } } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Grasp command aborted"); break; } gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Grasp command succeeded"); break; case GraspHandPostureExecutionGoal::RELEASE: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Release command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = true; if(service_client_.call(req,res)) { gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Release command succeeded"); } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Release command aborted"); } break; default: ROS_WARN_STREAM(nodeName + ": Unidentified grasp request, rejecting request"); gh.setRejected(); break; } } void cancelCB(GoalHandle gh) { std::string nodeName = ros::this_node::getName(); ROS_INFO_STREAM(nodeName + ": Canceling current grasp action"); gh.setCanceled(); ROS_INFO_STREAM(nodeName + ": Current grasp action has been canceled"); } bool fetchParameters() { ros::NodeHandle nh; bool success = true; nh.getParam("use_sensor_feedback",use_sensor_feedback_); success = success && nh.getParam("suction_on_output_channel",suction_on_output_channel_); success = success && nh.getParam("suction_check_output_channel",suction_check_input_channel_); return success; } bool validateChannelIndices() { typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType; if(suction_on_output_channel_ >= (int)DigitalOutputType::COUNT || suction_on_output_channel_ == (int)DigitalOutputType::COLLISION) { return false; } if(suction_check_input_channel_ >= int(DigitalOutputType::COUNT)) { return false; } return true; } bool checkSensorState() { ros::NodeHandle nh("/"); soem_beckhoff_drivers::DigitalMsg::ConstPtr input_msg_ = ros::topic::waitForMessage<soem_beckhoff_drivers::DigitalMsg>(INPUT_TOPIC,nh,ros::Duration(2.0f)); if(!input_msg_) { ROS_ERROR_STREAM(ros::this_node::getName()<<": Input message received invalid"); return true; } else { return ((input_msg_->values[suction_check_input_channel_] == 1) ? true : false); } } // ros comm ros::NodeHandle node_; GEAS action_server_; ros::ServiceClient service_client_; // ros parameters int suction_on_output_channel_; // index value to output channel for suction int suction_check_input_channel_; // index value to input channel for vacuum sensor bool use_sensor_feedback_; }; int main(int argc, char** argv) { ros::init(argc, argv, "grasp_execution_action_node"); ros::NodeHandle node(""); SimpleGraspActionServer ge(node); ge.init(); ros::spin(); return 0; }
27.550877
133
0.710265
asct
db61705d57f0223b23905967953c5dffa451a9b5
1,651
cpp
C++
Intro/program_10/asciiDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
Intro/program_10/asciiDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
Intro/program_10/asciiDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
#include <iostream.h> #include <conio.h> void convert (char letter); main() { int x = 2; //for the do/while char b; //to accept letter input do{ cout<<"Welcome to the Letter Converter Program. \n"; cout<<"This program will accept a letter and convert it between \n"; //introduction cout<<"uppercase and lower case. \n"; cout<<"\nEnter a letter to convert. -> "; cin>>b; convert(b); //sends b to the function convert, doesn't return. do{ cout<<"\nTo stop the program, enter 1. To rerun the program, enter 2. -> "; cin>>x; cout<<endl; // this makes it so only 1 or 2 can be entered - cannot enter 3 to quit for instance. }while((x != 1) && (x != 2)); clrscr(); }while(x==2); return 0; } void convert (char letter) { //The letter must be between 65-90 and 97-122 to be 'a to z'. //Which is why 91-96 is not allowed. if(letter >= 65 && letter <= 122) { //uppercase to lower case. if(letter >= 65 && letter <= 90) { letter = letter + 32; cout<<endl<<letter<<endl; letter = letter - 32; //without this it seems to convert it back to uppercase, but this fixes that issue. } //for 91 to 96, which are not letters. if(letter >=91 && letter <= 96) { cout<<"\nYou didn't enter a letter; try again. \n"; } //lower case to upper case. if(letter >= 97 && letter <= 122) { letter = letter - 32; cout<<endl<<letter<<endl; } } else //if the user enters something else that isn't letter (65-90 or 97-122), the program prints this. { cout<<"\nYou didn't enter a letter; try again. \n"; } }
23.253521
109
0.591157
JasonD94
db6284dcd32eddc392b02ba99bff03b49c104764
1,617
cpp
C++
src/adcs/state_estimators/b_dot_estimator.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
10
2018-04-28T04:44:56.000Z
2022-02-06T21:12:13.000Z
src/adcs/state_estimators/b_dot_estimator.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
null
null
null
src/adcs/state_estimators/b_dot_estimator.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
3
2019-02-16T03:22:26.000Z
2022-02-03T14:54:22.000Z
#include <src/adcs/state_estimators/b_dot_estimator.h> #include <src/util/matrix.h> #include <src/util/msp_exception.h> #include <src/util/physical_constants.h> BDotEstimator::BDotEstimator(uint16_t sample_period_millis, uint16_t time_constant_millis) : smoother_x(time_constant_millis, sample_period_millis), smoother_y(time_constant_millis, sample_period_millis), smoother_z(time_constant_millis, sample_period_millis), differentiator_x(sample_period_millis), differentiator_y(sample_period_millis), differentiator_z(sample_period_millis) {} void BDotEstimator::Estimate(const Matrix &magnetometer_reading, Matrix &estimate_output) { if (!estimate_output.SameSize(magnetometer_reading) || estimate_output.GetNRows() != geomagnetic_field_vector_nrows || estimate_output.GetNColumns() != geomagnetic_field_vector_ncolumns) { throw MspException("BDotEstimator::Estimate arguments not 3x1", kBdotEstimatorArgumentFail, __FILE__, __LINE__); } estimate_output.Set(0, 0, differentiator_x.ProcessSample(smoother_x.ProcessSample( magnetometer_reading.Get(0, 0)))); estimate_output.Set(1, 0, differentiator_y.ProcessSample(smoother_y.ProcessSample( magnetometer_reading.Get(1, 0)))); estimate_output.Set(2, 0, differentiator_z.ProcessSample(smoother_z.ProcessSample( magnetometer_reading.Get(2, 0)))); }
49
80
0.672851
MelbourneSpaceProgram
db62ba0d5f57df2c12966c8786cb2e9cb9316b26
4,108
cc
C++
extensions/gen/mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
// mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.cc is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #endif #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/hash/md5_constexpr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/task/common/task_annotator.h" #include "base/trace_event/trace_event.h" #include "mojo/public/cpp/bindings/lib/generated_code_util.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "third_party/perfetto/include/perfetto/tracing/traced_value.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-params-data.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-shared-message-ids.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink-import-headers.h" #include "mojo/public/cpp/bindings/lib/wtf_serialization.h" #ifndef MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_DESERIALIZER_TEST_MOJOM_BLINK_JUMBO_H_ #define MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_DESERIALIZER_TEST_MOJOM_BLINK_JUMBO_H_ #endif namespace deserializer { namespace blink { TestStruct::TestStruct() : v1(), v2(), v3() {} TestStruct::TestStruct( int32_t v1_in, int32_t v2_in, int64_t v3_in) : v1(std::move(v1_in)), v2(std::move(v2_in)), v3(std::move(v3_in)) {} TestStruct::~TestStruct() = default; size_t TestStruct::Hash(size_t seed) const { seed = mojo::internal::WTFHash(seed, this->v1); seed = mojo::internal::WTFHash(seed, this->v2); seed = mojo::internal::WTFHash(seed, this->v3); return seed; } void TestStruct::WriteIntoTracedValue(perfetto::TracedValue context) const { auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v1"), this->v1, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int32_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v2"), this->v2, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int32_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v3"), this->v3, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int64_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); } bool TestStruct::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } } // namespace blink } // namespace deserializer namespace mojo { // static bool StructTraits<::deserializer::blink::TestStruct::DataView, ::deserializer::blink::TestStructPtr>::Read( ::deserializer::blink::TestStruct::DataView input, ::deserializer::blink::TestStructPtr* output) { bool success = true; ::deserializer::blink::TestStructPtr result(::deserializer::blink::TestStruct::New()); if (success) result->v1 = input.v1(); if (success) result->v2 = input.v2(); if (success) result->v3 = input.v3(); *output = std::move(result); return success; } } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #endif
31.6
135
0.738559
blockspacer
db662d6c5f0eb595ee36d2a14c810f6bc26fd9b0
7,656
cpp
C++
src/HLM.cpp
Shicheng-Guo/regenie
0feb9f7cfab38b9af4ec322d7888a71293223baf
[ "MIT" ]
89
2020-06-23T05:36:33.000Z
2022-03-26T13:50:42.000Z
src/HLM.cpp
Shicheng-Guo/regenie
0feb9f7cfab38b9af4ec322d7888a71293223baf
[ "MIT" ]
254
2020-06-23T15:45:33.000Z
2022-03-31T18:49:20.000Z
src/HLM.cpp
Shicheng-Guo/regenie
0feb9f7cfab38b9af4ec322d7888a71293223baf
[ "MIT" ]
36
2020-06-23T04:43:36.000Z
2022-03-05T01:29:21.000Z
/* This file is part of the regenie software package. Copyright (c) 2020-2021 Joelle Mbatchou, Andrey Ziyatdinov & Jonathan Marchini 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 "Regenie.hpp" #include "Files.hpp" #include "Geno.hpp" #include "Step1_Models.hpp" #include "Pheno.hpp" #include "HLM.hpp" using namespace std; using namespace Eigen; using namespace boost; using namespace LBFGSpp; using boost::math::normal; using boost::math::chi_squared; HLM::HLM(){ } HLM::~HLM(){ } void HLM::prep_run(struct phenodt const* pheno_data, struct param const* params){ // store Vlin = (1, E) allocate_mat(Vlin, pheno_data->interaction_cov.rows(), params->ncov_interaction + 1); Vlin << MatrixXd::Ones(pheno_data->interaction_cov.rows(),1), pheno_data->interaction_cov; if(params->hlm_vquad && params->int_add_extra_term){ // set V = (1, E, E^2) [ apply QR to U = (E,E^2), center & scale, and set V = (1, U)] MatrixXd Vtmp (Vlin.rows(), params->ncov_interaction * 2); Vtmp << pheno_data->interaction_cov, pheno_data->interaction_cov.array().square().matrix(); //cerr << "pre:\n" << Vtmp.topRows(5) << "\n\n"; apply_QR(Vtmp, params, true); allocate_mat(V, Vtmp.rows(), Vtmp.cols() + 1); V << MatrixXd::Ones(Vtmp.rows(),1), Vtmp; //cerr << "post:\n" << V.topRows(5) << "\n\n"; } else { // set V = (1, E) and center & scale E allocate_mat(V, Vlin.rows(), Vlin.cols()); V = Vlin; rescale_mat(V.rightCols(params->ncov_interaction), params); } // set X = (covs, E^2?, blup) - covs may include E MatrixXd Xtmp (pheno_data->new_cov.rows(), params->ncov + (params->int_add_extra_term && !params->add_homdev ? params->ncov_interaction : 0 )); if(params->int_add_extra_term && !params->add_homdev) { //cerr << "pre:\n" << Xtmp.topRows(5) << "\n\n"; Xtmp << pheno_data->new_cov, pheno_data->interaction_cov.array().square().matrix(); apply_QR(Xtmp, params, false); } else Xtmp = pheno_data->new_cov; //cerr << "post:\n" << Xtmp.topRows(5) << "\n\n"; allocate_mat(X, Xtmp.rows(), Xtmp.cols() + (params->skip_blups ? 0 : 1) ); X.leftCols(Xtmp.cols()) = Xtmp; // for projection under null Px.resize(params->n_pheno); allocate_mat(yres, pheno_data->interaction_cov.rows(), params->n_pheno); } // For each phenotype, fit the null HLM // Y = Xa + e, where e ~ N(0, exp(Vb) ) // Have this be outside of the class so can use LBFGS solver void HLM_fitNull(HLM& nullHLM, struct ests const& m_ests, struct phenodt const& pheno_data, struct in_files const& files, struct param const& params, mstream& sout){ // if no blup predictions are given, this should only be ran once if(params.skip_blups && !nullHLM.first_fit) return; sout << " -fitting null HLMs for each trait..." << flush; auto t1 = std::chrono::high_resolution_clock::now(); double fx; VectorXd beta(nullHLM.V.cols()); allocate_mat(nullHLM.Dinv_sqrt, pheno_data.phenotypes_raw.rows(), pheno_data.phenotypes_raw.cols()); LBFGSParam<double> bfgs_param; bfgs_param.max_iterations = nullHLM.max_iter; bfgs_param.max_linesearch = nullHLM.linesearch_try; // use more lenient number LBFGSSolver<double> solver(bfgs_param); for(int i = 0; i < params.n_pheno; i++){ nullHLM.n = pheno_data.Neff(i); nullHLM.mask = pheno_data.masked_indivs.col(i); nullHLM.y = pheno_data.phenotypes_raw.col(i); if(!params.skip_blups) // add blup as a covariate nullHLM.X.rightCols(1) = m_ests.blups.col(i); beta.array() = 0; try { // get starting value for b nullHLM.get_alpha(beta); nullHLM.get_beta_approx(beta); // LBFGS solver.minimize(nullHLM, beta, fx); nullHLM.store_null_est(i); } catch(...){ // redo with higher number of line search trials try { if(params.verbose) sout << "Retrying HLM null model fitting for " << files.pheno_names[i] << endl; LBFGSParam<double> bfgs_param_retry; bfgs_param_retry.max_iterations = nullHLM.max_iter_retry; bfgs_param_retry.max_linesearch = nullHLM.linesearch_retry; bfgs_param_retry.max_step = nullHLM.max_step_retry; LBFGSSolver<double> solver_retry(bfgs_param_retry); // get starting value for b beta.array() = 0; nullHLM.get_alpha(beta); nullHLM.get_beta_approx(beta); // LBFGS solver_retry.minimize(nullHLM, beta, fx); nullHLM.store_null_est(i); } catch(...){ throw "LFBGS could not fit HLM null model for trait " + files.pheno_names[i]; } } //cerr << "\nFinal--\nalpha=\n"<<nullHLM.alpha << "\n\nbeta=\n" << beta <<"\n\nfx=" << fx << "\t" << std::boolalpha << isnan(fx); } //cerr << "\n\n" << nullHLM.yres.topRows(5)<<"\n\n"; sout << "done"; auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); sout << " (" << duration.count() << "ms) "<< endl; nullHLM.first_fit = false; } void HLM::get_alpha(VectorXd const& beta){ Vb = (V * beta).array(); Dinv = (-Vb).exp() * mask.cast<double>(); if( (Dinv == 0).all() ) // will cause Xd = 0 throw std::underflow_error("D=0 occurred"); MatrixXd Xd = (X.array().colwise() * Dinv).matrix().transpose(); alpha = (Xd * X).colPivHouseholderQr().solve( Xd * y ); } void HLM::get_beta_approx(VectorXd& beta){ ArrayXd esq = ((y - X * alpha).array() * mask.cast<double>()).square(); //cerr << "\nE=\n" << esq.head(10) << "\n\n"; beta = (V.transpose() * esq.matrix().asDiagonal() * V).colPivHouseholderQr().solve( V.transpose() * ((esq - 1) * mask.cast<double>()).matrix() ); //cerr << "alpha:\n" << alpha << "\n\nbeta:\n" << beta <<"\n\n"; } // get projection matrix void HLM::store_null_est(int const& ph){ Dinv_sqrt.col(ph) = Dinv.sqrt().matrix(); MatrixXd Xd = (X.array().colwise() * Dinv_sqrt.col(ph).array()).matrix(); SelfAdjointEigenSolver<MatrixXd> es(Xd.transpose() * Xd); VectorXd eigD = es.eigenvalues(); Px[ph] = ((Xd * es.eigenvectors()).array().rowwise() / eigD.transpose().array().sqrt()).matrix(); //cerr << "\nP=\n" << Px[ph].topRows(5) << "\n\n"; residualize(ph, y, yres.col(ph)); } void HLM::residualize(int const& ph, Ref<MatrixXd> mat_orig, Ref<MatrixXd> mat_res){ MatrixXd m = (mat_orig.array().colwise() * Dinv_sqrt.col(ph).array()).matrix(); //cerr << "Y" << ph+1 << "\norig:\n" << print_mat_dims(mat_orig) << // "\nm:\n" << print_mat_dims(m) << "\nPx:\n" << print_mat_dims(Px[ph]) << endl; mat_res = m - Px[ph] * (Px[ph].transpose() * m); }
35.281106
165
0.654911
Shicheng-Guo
db6928888c41642c0d0513eef87cf53a30644bc7
5,098
cpp
C++
PCMLIA-ADE-Pseu/src/MPI_localIni.cpp
Johnzhjw/evoIT2FRNN-GEP
5dbeea33e64c36cd43807cf3c8f9980a39198cd9
[ "Apache-2.0" ]
null
null
null
PCMLIA-ADE-Pseu/src/MPI_localIni.cpp
Johnzhjw/evoIT2FRNN-GEP
5dbeea33e64c36cd43807cf3c8f9980a39198cd9
[ "Apache-2.0" ]
null
null
null
PCMLIA-ADE-Pseu/src/MPI_localIni.cpp
Johnzhjw/evoIT2FRNN-GEP
5dbeea33e64c36cd43807cf3c8f9980a39198cd9
[ "Apache-2.0" ]
null
null
null
#include "global.h" #include <math.h> #include <time.h> void localInitialization() { int color_pop = st_MPI_p.color_pop; int* nPop_all = st_MPI_p.nPop_all; int mpi_rank = st_MPI_p.mpi_rank; int mpi_size_subPop = st_MPI_p.mpi_size_subPop; int mpi_rank_subPop = st_MPI_p.mpi_rank_subPop; int nPop = st_global_p.nPop; int nObj = st_global_p.nObj; int nDim = st_global_p.nDim; int* each_size_subPop = st_MPI_p.each_size_subPop; int* recv_size_subPop = st_MPI_p.recv_size_subPop; int* disp_size_subPop = st_MPI_p.disp_size_subPop; int* nPop_mine = &st_global_p.nPop_mine; int* nPop_exchange = &st_global_p.nPop_exchange; int* n_weights_mine = &st_pop_comm_p.n_weights_mine; int* n_weights_left = &st_pop_comm_p.n_weights_left; int* n_weights_right = &st_pop_comm_p.n_weights_right; int* n_neighbor_left = &st_pop_comm_p.n_neighbor_left; int* n_neighbor_right = &st_pop_comm_p.n_neighbor_right; double* weights_mine = st_decomp_p.weights_mine; double* weights_all = st_decomp_p.weights_all; double* posFactor_mine = st_pop_comm_p.posFactor_mine; double* diver_var_store_all = st_grp_info_p.diver_var_store_all; double* weights_left = st_decomp_p.weights_left; double* weights_right = st_decomp_p.weights_right; double* posFactor_left = st_pop_comm_p.posFactor_left; double* posFactor_right = st_pop_comm_p.posFactor_right; // int i; int quo; int rem; quo = nPop_all[color_pop] / mpi_size_subPop; rem = nPop_all[color_pop] % mpi_size_subPop; for(i = 0; i < mpi_size_subPop; i++) { each_size_subPop[i] = quo; if(i < rem) each_size_subPop[i]++; recv_size_subPop[i] = each_size_subPop[i]; } disp_size_subPop[0] = 0; for(i = 1; i < mpi_size_subPop; i++) { disp_size_subPop[i] = disp_size_subPop[i - 1] + recv_size_subPop[i - 1]; } // (*nPop_mine) = each_size_subPop[mpi_rank_subPop]; int min_num; MPI_Allreduce(nPop_mine, &min_num, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if(min_num == 0) { if(0 == mpi_rank) printf("%s: There are too many CPUs, at least one rank has 0 individual, exiting...\n", AT); MPI_Abort(MPI_COMM_WORLD, MY_ERROR_MPI_TOOMANY); } (*nPop_exchange) = 0; (*n_weights_mine) = (*nPop_mine); if(mpi_rank_subPop) (*n_weights_left) = each_size_subPop[mpi_rank_subPop - 1]; else (*n_weights_left) = 0; if(mpi_rank_subPop < mpi_size_subPop - 1) (*n_weights_right) = each_size_subPop[mpi_rank_subPop + 1]; else (*n_weights_right) = 0; (*n_neighbor_left) = (*n_weights_left); (*n_neighbor_right) = (*n_weights_right); // load_weights();////////////////////////////////////////////////////////////////////////// // memcpy(weights_mine, &weights_all[disp_size_subPop[mpi_rank_subPop] * nObj], (*n_weights_mine) * nObj * sizeof(double)); memcpy(posFactor_mine, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop] * nDim], (*n_weights_mine) * nDim * sizeof(double)); if((*n_weights_left)) { memcpy(weights_left, &weights_all[disp_size_subPop[mpi_rank_subPop - 1] * nObj], (*n_weights_left) * nObj * sizeof(double)); memcpy(posFactor_left, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop - 1] * nDim], (*n_weights_left) * nDim * sizeof(double)); } if((*n_weights_right)) { memcpy(weights_right, &weights_all[disp_size_subPop[mpi_rank_subPop + 1] * nObj], (*n_weights_right) * nObj * sizeof(double)); memcpy(posFactor_right, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop + 1] * nDim], (*n_weights_right) * nDim * sizeof(double)); } // return; } void localInitialization_ND() { int color_pop = st_MPI_p.color_pop; int* nPop_all = st_MPI_p.nPop_all; int mpi_rank = st_MPI_p.mpi_rank; int mpi_size_subPop = st_MPI_p.mpi_size_subPop; int mpi_rank_subPop = st_MPI_p.mpi_rank_subPop; int* each_size_subPop = st_MPI_p.each_size_subPop; int* recv_size_subPop = st_MPI_p.recv_size_subPop; int* disp_size_subPop = st_MPI_p.disp_size_subPop; int* nPop_mine = &st_global_p.nPop_mine; // int i; int quo; int rem; quo = nPop_all[color_pop] / mpi_size_subPop; rem = nPop_all[color_pop] % mpi_size_subPop; for(i = 0; i < mpi_size_subPop; i++) { each_size_subPop[i] = quo; if(i < rem) each_size_subPop[i]++; recv_size_subPop[i] = each_size_subPop[i]; } disp_size_subPop[0] = 0; for(i = 1; i < mpi_size_subPop; i++) { disp_size_subPop[i] = disp_size_subPop[i - 1] + recv_size_subPop[i - 1]; } // (*nPop_mine) = each_size_subPop[mpi_rank_subPop]; int min_num; MPI_Allreduce(nPop_mine, &min_num, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if(min_num == 0) { if(0 == mpi_rank) printf("%s: There are too many CPUs, at least one rank has 0 individual, exiting...\n", AT); MPI_Abort(MPI_COMM_WORLD, MY_ERROR_MPI_TOOMANY); } return; }
40.141732
134
0.667517
Johnzhjw
db69cf0301c2eb940418a74f1332a35457e560fd
17,960
cc
C++
paddle/fluid/operators/detection/generate_mask_labels_op.cc
Thunderbrook/Paddle
4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5
[ "Apache-2.0" ]
1
2021-12-27T02:48:34.000Z
2021-12-27T02:48:34.000Z
paddle/fluid/operators/detection/generate_mask_labels_op.cc
Thunderbrook/Paddle
4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/detection/generate_mask_labels_op.cc
Thunderbrook/Paddle
4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <math.h> #include <algorithm> #include <string> #include <vector> #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/detection/bbox_util.h" #include "paddle/fluid/operators/detection/mask_util.h" #include "paddle/fluid/operators/gather.h" #include "paddle/fluid/operators/math/concat_and_split.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; const int kBoxDim = 4; template <typename T> void AppendMask(LoDTensor* out, int64_t offset, Tensor* to_add) { auto* out_data = out->data<T>(); auto* to_add_data = to_add->data<T>(); memcpy(out_data + offset, to_add_data, to_add->numel() * sizeof(T)); } class GenerateMaskLabelsOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("ImInfo"), "Input(ImInfo) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("GtClasses"), "Input(GtClasses) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("IsCrowd"), "Input(IsCrowd) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("GtSegms"), "Input(GtSegms) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("Rois"), "Input(Rois) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("LabelsInt32"), "Input(LabelsInt32) shouldn't be null."); PADDLE_ENFORCE( ctx->HasOutput("MaskRois"), "Output(MaskRois) of GenerateMaskLabelsOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("RoiHasMaskInt32"), "Output(RoiHasMaskInt32) of GenerateMaskLabelsOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("MaskInt32"), "Output(MaskInt32) of GenerateMaskLabelsOp should not be null"); auto im_info_dims = ctx->GetInputDim("ImInfo"); auto gt_segms_dims = ctx->GetInputDim("GtSegms"); PADDLE_ENFORCE_EQ(im_info_dims.size(), 2, "The rank of Input(ImInfo) must be 2."); PADDLE_ENFORCE_EQ(gt_segms_dims.size(), 2, "The rank of Input(GtSegms) must be 2."); PADDLE_ENFORCE_EQ(gt_segms_dims[1], 2, "The second dim of Input(GtSegms) must be 2."); int num_classes = ctx->Attrs().Get<int>("num_classes"); int resolution = ctx->Attrs().Get<int>("resolution"); ctx->SetOutputDim("MaskRois", {-1, 4}); ctx->SetOutputDim("RoiHasMaskInt32", {-1, 1}); ctx->SetOutputDim("MaskInt32", {-1, num_classes * resolution * resolution}); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Rois"); return framework::OpKernelType(data_type, platform::CPUPlace()); } }; /* * Expand masks from shape (#masks, M ** 2) to (#masks, #classes * M ** 2) * to encode class specific mask targets. */ template <typename T> static inline void ExpandMaskTarget(const platform::CPUDeviceContext& ctx, const Tensor& masks, const Tensor& mask_class_labels, const int resolution, const int num_classes, Tensor* mask_targets) { const uint8_t* masks_data = masks.data<uint8_t>(); int64_t num_mask = masks.dims()[0]; const int* mask_class_labels_data = mask_class_labels.data<int>(); const int M = resolution * resolution; const int mask_dim = M * num_classes; int* mask_targets_data = mask_targets->mutable_data<int>({num_mask, mask_dim}, ctx.GetPlace()); math::set_constant(ctx, mask_targets, -1); for (int64_t mask_id = 0; mask_id < num_mask; ++mask_id) { int cls = mask_class_labels_data[mask_id]; int start = M * cls; if (cls > 0) { for (int i = 0; i < M; ++i) { mask_targets_data[mask_id * mask_dim + start + i] = static_cast<int>(masks_data[mask_id * M + i]); } } } } template <typename T> std::vector<Tensor> SampleMaskForOneImage( const platform::CPUDeviceContext& ctx, const Tensor& im_info, const Tensor& gt_classes, const Tensor& is_crowd, const Tensor& gt_segms, const Tensor& rois, const Tensor& label_int32, const int num_classes, const int resolution, const framework::LoD& segm_length) { // Prepare the mask targets by associating one gt mask to each training roi // that has a fg (non-bg) class label. const int64_t gt_size = static_cast<int64_t>(gt_classes.dims()[0]); const int64_t roi_size = static_cast<int64_t>(rois.dims()[0]); const int* gt_classes_data = gt_classes.data<int>(); const int* is_crowd_data = is_crowd.data<int>(); const int* label_int32_data = label_int32.data<int>(); PADDLE_ENFORCE_EQ(roi_size, label_int32.dims()[0]); std::vector<int> mask_gt_inds, fg_inds; std::vector<std::vector<std::vector<T>>> gt_polys; auto polys_num = segm_length[1]; auto segm_lod_offset = framework::ConvertToOffsetBasedLoD(segm_length); auto lod1 = segm_lod_offset[1]; auto lod2 = segm_lod_offset[2]; const T* polys_data = gt_segms.data<T>(); for (int64_t i = 0; i < gt_size; ++i) { if ((gt_classes_data[i] > 0) && (is_crowd_data[i] == 0)) { mask_gt_inds.emplace_back(i); // slice fg segmentation polys int poly_num = polys_num[i]; std::vector<std::vector<T>> polys; int s_idx = lod1[i]; for (int j = 0; j < poly_num; ++j) { int s = lod2[s_idx + j]; int e = lod2[s_idx + j + 1]; PADDLE_ENFORCE_NE(s, e); std::vector<T> plts(polys_data + s * 2, polys_data + e * 2); polys.push_back(plts); } gt_polys.push_back(polys); } } for (int64_t i = 0; i < roi_size; ++i) { if (label_int32_data[i] > 0) { fg_inds.emplace_back(i); } } int gt_num = mask_gt_inds.size(); int fg_num = fg_inds.size(); Tensor boxes_from_polys; boxes_from_polys.mutable_data<T>({gt_num, 4}, platform::CPUPlace()); Poly2Boxes(gt_polys, boxes_from_polys.data<T>()); std::vector<int> roi_has_mask = std::vector<int>(fg_inds.begin(), fg_inds.end()); Tensor mask_class_labels; Tensor masks; Tensor rois_fg; auto im_scale = im_info.data<T>()[2]; if (fg_num > 0) { // Class labels for the foreground rois mask_class_labels.mutable_data<int>({fg_num, 1}, ctx.GetPlace()); Gather<int>(label_int32_data, 1, fg_inds.data(), fg_inds.size(), mask_class_labels.data<int>()); uint8_t* masks_data = masks.mutable_data<uint8_t>( {fg_num, resolution * resolution}, ctx.GetPlace()); // Find overlap between all foreground rois and the bounding boxes // enclosing each segmentation T* rois_fg_data = rois_fg.mutable_data<T>({fg_num, 4}, ctx.GetPlace()); Gather<T>(rois.data<T>(), 4, fg_inds.data(), fg_inds.size(), rois_fg.data<T>()); for (int k = 0; k < rois_fg.numel(); ++k) { rois_fg_data[k] = rois_fg_data[k] / im_scale; } Tensor overlaps_bbfg_bbpolys; overlaps_bbfg_bbpolys.mutable_data<T>({fg_num, gt_num}, ctx.GetPlace()); BboxOverlaps<T>(rois_fg, boxes_from_polys, &overlaps_bbfg_bbpolys); // Map from each fg rois to the index of the mask with highest overlap // (measured by bbox overlap) T* overlaps_bbfg_bbpolys_data = overlaps_bbfg_bbpolys.data<T>(); std::vector<int> fg_masks_inds; for (int64_t i = 0; i < fg_num; ++i) { const T* v = overlaps_bbfg_bbpolys_data + i * gt_num; T max_overlap = std::numeric_limits<T>::min(); int id = 0; for (int64_t j = 0; j < gt_num; ++j) { if (v[j] > max_overlap) { max_overlap = v[j]; id = j; } } fg_masks_inds.push_back(id); } // add fg targets for (int64_t i = 0; i < fg_num; ++i) { int fg_polys_ind = fg_masks_inds[i]; T* roi_fg = rois_fg_data + i * 4; uint8_t* mask = masks_data + i * resolution * resolution; Polys2MaskWrtBox(gt_polys[fg_polys_ind], roi_fg, resolution, mask); } } else { // The network cannot handle empty blobs, so we must provide a mask // We simply take the first bg roi, given it an all -1's mask (ignore // label), and label it with class zero (bg). int bg_num = 1; T* rois_fg_data = rois_fg.mutable_data<T>({bg_num, 4}, ctx.GetPlace()); const T* rois_data = rois.data<T>(); std::vector<int> bg_inds; for (int64_t i = 0; i < roi_size; ++i) { if (label_int32_data[i] == 0) { bg_inds.emplace_back(i); rois_fg_data[0] = rois_data[0] / im_scale; rois_fg_data[1] = rois_data[1] / im_scale; rois_fg_data[2] = rois_data[2] / im_scale; rois_fg_data[3] = rois_data[3] / im_scale; break; } } masks.mutable_data<uint8_t>({bg_num, resolution * resolution}, ctx.GetPlace()); math::set_constant(ctx, &masks, -1); int* mask_class_labels_data = mask_class_labels.mutable_data<int>({bg_num, 1}, ctx.GetPlace()); mask_class_labels_data[0] = 0; roi_has_mask = std::vector<int>(bg_inds.begin(), bg_inds.end()); } Tensor masks_expand; ExpandMaskTarget<T>(ctx, masks, mask_class_labels, resolution, num_classes, &masks_expand); T* rois_fg_data = rois_fg.data<T>(); for (int k = 0; k < rois_fg.numel(); ++k) { rois_fg_data[k] = rois_fg_data[k] * im_scale; } Tensor roi_has_mask_t; int roi_has_mask_size = roi_has_mask.size(); int* roi_has_mask_data = roi_has_mask_t.mutable_data<int>({roi_has_mask_size, 1}, ctx.GetPlace()); std::copy(roi_has_mask.begin(), roi_has_mask.end(), roi_has_mask_data); std::vector<Tensor> res; res.emplace_back(rois_fg); res.emplace_back(roi_has_mask_t); res.emplace_back(masks_expand); return res; } template <typename T> class GenerateMaskLabelsKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* im_info = ctx.Input<LoDTensor>("ImInfo"); auto* gt_classes = ctx.Input<LoDTensor>("GtClasses"); auto* is_crowd = ctx.Input<LoDTensor>("IsCrowd"); auto* gt_segms = ctx.Input<LoDTensor>("GtSegms"); auto* rois = ctx.Input<LoDTensor>("Rois"); auto* label_int32 = ctx.Input<LoDTensor>("LabelsInt32"); auto* mask_rois = ctx.Output<LoDTensor>("MaskRois"); auto* roi_has_mask_int32 = ctx.Output<LoDTensor>("RoiHasMaskInt32"); auto* mask_int32 = ctx.Output<LoDTensor>("MaskInt32"); int num_classes = ctx.Attr<int>("num_classes"); int resolution = ctx.Attr<int>("resolution"); PADDLE_ENFORCE_EQ(gt_classes->lod().size(), 1UL, "GenerateMaskLabelsOp gt_classes needs 1 level of LoD"); PADDLE_ENFORCE_EQ(is_crowd->lod().size(), 1UL, "GenerateMaskLabelsOp is_crowd needs 1 level of LoD"); PADDLE_ENFORCE_EQ(rois->lod().size(), 1UL, "GenerateMaskLabelsOp rois needs 1 level of LoD"); PADDLE_ENFORCE_EQ(label_int32->lod().size(), 1UL, "GenerateMaskLabelsOp label_int32 needs 1 level of LoD"); PADDLE_ENFORCE_EQ(gt_segms->lod().size(), 3UL); int64_t n = static_cast<int64_t>(gt_classes->lod().back().size() - 1); PADDLE_ENFORCE_EQ(gt_segms->lod()[0].size() - 1, n); int mask_dim = num_classes * resolution * resolution; int roi_num = rois->lod().back()[n]; mask_rois->mutable_data<T>({roi_num, kBoxDim}, ctx.GetPlace()); roi_has_mask_int32->mutable_data<int>({roi_num, 1}, ctx.GetPlace()); mask_int32->mutable_data<int>({roi_num, mask_dim}, ctx.GetPlace()); framework::LoD lod; std::vector<size_t> lod0(1, 0); int64_t num_mask = 0; auto& dev_ctx = ctx.device_context<platform::CPUDeviceContext>(); auto gt_classes_lod = gt_classes->lod().back(); auto is_crowd_lod = is_crowd->lod().back(); auto rois_lod = rois->lod().back(); auto label_int32_lod = label_int32->lod().back(); auto gt_segms_lod = gt_segms->lod(); for (int i = 0; i < n; ++i) { if (rois_lod[i] == rois_lod[i + 1]) { lod0.emplace_back(num_mask); continue; } Tensor im_info_slice = im_info->Slice(i, i + 1); Tensor gt_classes_slice = gt_classes->Slice(gt_classes_lod[i], gt_classes_lod[i + 1]); Tensor is_crowd_slice = is_crowd->Slice(is_crowd_lod[i], is_crowd_lod[i + 1]); Tensor label_int32_slice = label_int32->Slice(label_int32_lod[i], label_int32_lod[i + 1]); Tensor rois_slice = rois->Slice(rois_lod[i], rois_lod[i + 1]); auto sub_lod_and_offset = framework::GetSubLoDAndAbsoluteOffset(gt_segms_lod, i, i + 1, 0); auto lod_length = sub_lod_and_offset.first; size_t s = sub_lod_and_offset.second.first; size_t e = sub_lod_and_offset.second.second; Tensor gt_segms_slice = gt_segms->Slice(s, e); std::vector<Tensor> tensor_output = SampleMaskForOneImage<T>( dev_ctx, im_info_slice, gt_classes_slice, is_crowd_slice, gt_segms_slice, rois_slice, label_int32_slice, num_classes, resolution, lod_length); Tensor sampled_mask_rois = tensor_output[0]; Tensor sampled_roi_has_mask_int32 = tensor_output[1]; Tensor sampled_mask_int32 = tensor_output[2]; AppendMask<T>(mask_rois, kBoxDim * num_mask, &sampled_mask_rois); AppendMask<int>(roi_has_mask_int32, num_mask, &sampled_roi_has_mask_int32); AppendMask<int>(mask_int32, mask_dim * num_mask, &sampled_mask_int32); num_mask += sampled_mask_rois.dims()[0]; lod0.emplace_back(num_mask); } lod.emplace_back(lod0); mask_rois->set_lod(lod); roi_has_mask_int32->set_lod(lod); mask_int32->set_lod(lod); mask_rois->Resize({num_mask, kBoxDim}); roi_has_mask_int32->Resize({num_mask, 1}); mask_int32->Resize({num_mask, mask_dim}); } }; class GenerateMaskLabelsOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("ImInfo", "(Tensor), This input is a 2D Tensor with shape [B, 3]. " "B is the number of input images, " "each element consists of im_height, im_width, im_scale."); AddInput("GtClasses", "(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. " "M is the number of groundtruth, " "each element is a class label of groundtruth."); AddInput( "IsCrowd", "(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. " "M is the number of groundtruth, " "each element is a flag indicates whether a groundtruth is crowd."); AddInput( "GtSegms", "(LoDTensor), This input is a 2D LoDTensor with shape [S, 2], it's LoD " "level is 3. The LoD[0] represents the gt objects number of each " "instance. LoD[1] represents the segmentation counts of each objects. " "LoD[2] represents the polygons number of each segmentation. S the " "total number of polygons coordinate points. Each element is (x, y) " "coordinate points."); AddInput( "Rois", "(LoDTensor), This input is a 2D LoDTensor with shape [R, 4]. " "R is the number of rois which is the output of " "generate_proposal_labels, " "each element is a bounding box with (xmin, ymin, xmax, ymax) format."); AddInput("LabelsInt32", "(LoDTensor), This intput is a 2D LoDTensor with shape [R, 1], " "each element repersents a class label of a roi"); AddOutput( "MaskRois", "(LoDTensor), This output is a 2D LoDTensor with shape [P, 4]. " "P is the number of mask, " "each element is a bounding box with [xmin, ymin, xmax, ymax] format."); AddOutput("RoiHasMaskInt32", "(LoDTensor), This output is a 2D LoDTensor with shape [P, 1], " "each element repersents the output mask rois index with regard " "to input rois"); AddOutput("MaskInt32", "(LoDTensor), This output is a 4D LoDTensor with shape [P, Q], " "Q equal to num_classes * resolution * resolution"); AddAttr<int>("num_classes", "Class number."); AddAttr<int>("resolution", "Resolution of mask."); AddComment(R"DOC( This operator can be, for given the RoIs and corresponding labels, to sample foreground RoIs. This mask branch also has a :math: `K \\times M^{2}` dimensional output targets for each foreground RoI, which encodes K binary masks of resolution M x M, one for each of the K classes. This mask targets are used to compute loss of mask branch. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR( generate_mask_labels, ops::GenerateMaskLabelsOp, ops::GenerateMaskLabelsOpMaker, paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>); REGISTER_OP_CPU_KERNEL(generate_mask_labels, ops::GenerateMaskLabelsKernel<float>);
40.45045
80
0.656069
Thunderbrook
db6bb91b83fd89ae8b6602365f75524a668fea88
2,036
cc
C++
input.cc
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
input.cc
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
input.cc
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
/* git-junction * Copyright (c) 2016-2017 by Pauli Saksa * * Licensed under The MIT License, see file LICENSE.txt in this source tree. */ #include "input.hh" #include "exception.hh" #include "terminal_input.hh" #include "utils.hh" #include <iostream> #include <sstream> #include <unistd.h> // bool accept_field_functor::accept_size(std::string::size_type size, std::string::size_type min, std::string::size_type max) { if (size < min) { std::cout << "too short, " << min << '-' << max << " characters\n"; return false; } if (size > max) { std::cout << "too long, " << min << '-' << max << " characters\n"; return false; } return true; } accept_field_functor::~accept_field_functor() { } // ********************************************************* bool accept_yes_or_no::operator() (std::string &input) const { if (input.size() < 2 || input.size() > 3) { return false; } lowercase(input); return input == "yes" || input == "no"; } // ********************************************************* static std::string read_line(const std::string &prompt, bool hide) { terminal_input term_input{hide}; std::cout << prompt << std::flush; std::ostringstream oss; char inp; while (true) { const int i =read(STDIN_FILENO, &inp, 1); if (i != 1) { std::cout << '\n'; throw stdin_exception{}; } if (inp == '\n' || inp == '\r') break; if (inp >= 0 && inp < 32) continue; oss << inp; } return oss.str(); } // ********************************************************* std::string read_field(const std::string prompt, bool hide, const accept_field_functor &accept) { while (true) { std::string input =read_line(prompt, hide); if (accept(input)) // accept() may modify input return input; } }
20.989691
95
0.48723
psaksa
db6db73822024f7d160709380af99ee169922697
432
hpp
C++
Source/Decoder.hpp
Myles-Trevino/Resonance
47ff7c51caa8fc15862818f56a232c3e71dd7e0a
[ "Apache-2.0" ]
1
2020-09-07T13:03:34.000Z
2020-09-07T13:03:34.000Z
Source/Decoder.hpp
Myles-Trevino/Resonance
47ff7c51caa8fc15862818f56a232c3e71dd7e0a
[ "Apache-2.0" ]
null
null
null
Source/Decoder.hpp
Myles-Trevino/Resonance
47ff7c51caa8fc15862818f56a232c3e71dd7e0a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Myles Trevino Licensed under the Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ #pragma once #include <string> #include <vector> namespace LV::Decoder { void load_track_information(const std::string& file); void initialize_resampler_and_decoder(); void load_samples(); void destroy(); // Getters. const std::vector<float>& get_data(); const int get_sample_rate(); }
14.896552
54
0.729167
Myles-Trevino
db700b60ae0b4350c16bb9b355414a221e20e5b3
4,337
hpp
C++
src/webots/nodes/WbElevationGrid.hpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
2
2022-01-12T09:39:31.000Z
2022-01-15T06:27:57.000Z
src/webots/nodes/WbElevationGrid.hpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
null
null
null
src/webots/nodes/WbElevationGrid.hpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
null
null
null
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef WB_ELEVATION_GRID_HPP #define WB_ELEVATION_GRID_HPP #include "WbGeometry.hpp" #include "WbMFDouble.hpp" #include "WbSFDouble.hpp" #include "WbSFInt.hpp" #include "WbSFNode.hpp" class WbVector3; typedef struct dxHeightfieldData *dHeightfieldDataID; class WbElevationGrid : public WbGeometry { Q_OBJECT public: // constructors and destructor explicit WbElevationGrid(WbTokenizer *tokenizer = NULL); WbElevationGrid(const WbElevationGrid &other); explicit WbElevationGrid(const WbNode &other); virtual ~WbElevationGrid(); // field accessors // getters double xSpacing() const { return mXSpacing->value(); } double zSpacing() const { return mZSpacing->value(); } int xDimension() const { return mXDimension->value(); } int zDimension() const { return mZDimension->value(); } int height(int index) const { return mHeight->item(index); } double heightRange() const { return mMaxHeight - mMinHeight; } // setters void setXspacing(double x) { mXSpacing->setValue(x); } void setZspacing(double z) { mZSpacing->setValue(z); } void setHeightScaleFactor(double ratio) { mHeight->multiplyAllItems(ratio); } // reimplemented public functions int nodeType() const override { return WB_NODE_ELEVATION_GRID; } void preFinalize() override; void postFinalize() override; dGeomID createOdeGeom(dSpaceID space) override; void createWrenObjects() override; void createResizeManipulator() override; bool isAValidBoundingObject(bool checkOde = false, bool warning = true) const override; bool isSuitableForInsertionInBoundingObject(bool warning = false) const override; void rescale(const WbVector3 &scale) override; // ray tracing void recomputeBoundingSphere() const override; bool pickUVCoordinate(WbVector2 &uv, const WbRay &ray, int textureCoordSet = 0) const override; double computeDistance(const WbRay &ray) const override; // friction WbVector3 computeFrictionDirection(const WbVector3 &normal) const override; // resize manipulator void setResizeManipulatorDimensions() override; signals: void validElevationGridInserted(); protected: bool areSizeFieldsVisibleAndNotRegenerator() const override; void exportNodeFields(WbVrmlWriter &writer) const override; private: WbElevationGrid &operator=(const WbElevationGrid &); // non copyable WbNode *clone() const override { return new WbElevationGrid(*this); } void init(); // user accessible fields WbMFDouble *mHeight; WbSFInt *mXDimension; WbSFDouble *mXSpacing; WbSFInt *mZDimension; WbSFDouble *mZSpacing; WbSFDouble *mThickness; // other variables double mMinHeight; // min value in "height" field double mMaxHeight; // max value in "height" field dHeightfieldDataID mHeightfieldData; double *mData; void checkHeight(); double width() const { return mXSpacing->value() * (mXDimension->value() - 1); } double depth() const { return mZSpacing->value() * (mZDimension->value() - 1); } double height() const { return mMaxHeight - mMinHeight; } bool sanitizeFields(); // WREN void buildWrenMesh(); void updateScale(); // ODE void applyToOdeData(bool correctSolidMass = true) override; bool setOdeHeightfieldData(); double scaledWidth() const; double scaledDepth() const; double heightScaleFactor() const { return fabs(absoluteScale().y()); } // ray tracing double computeLocalCollisionPoint(const WbRay &ray, WbVector3 &localCollisionPoint) const; void computeMinMax(const WbVector3 &point, WbVector3 &min, WbVector3 &max) const; private slots: void updateHeight(); void updateXDimension(); void updateXSpacing(); void updateZDimension(); void updateZSpacing(); void updateThickness(); void updateLineScale(); }; #endif
33.10687
97
0.748905
Justin-Fisher
db70c1001508c517af633b42da7527881f544186
209
cpp
C++
main.cpp
fubieslc/flube
e3e9f08b00a767ae80981dd25dd40aff07a431ae
[ "libtiff", "BSD-3-Clause" ]
null
null
null
main.cpp
fubieslc/flube
e3e9f08b00a767ae80981dd25dd40aff07a431ae
[ "libtiff", "BSD-3-Clause" ]
null
null
null
main.cpp
fubieslc/flube
e3e9f08b00a767ae80981dd25dd40aff07a431ae
[ "libtiff", "BSD-3-Clause" ]
null
null
null
// main.cpp // #include "Core.hpp" int main(int argc, char** argv) { if (Core.Init()) { Core.Quit(); return -1; } else { Core.MainLoop(); Core.Quit(); return 0; } return 0; }
11.611111
34
0.507177
fubieslc
db70c1b7ba113a0a5825d1662a8e66c0962f40b0
49,361
cpp
C++
Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Casting/numeric_cast.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Serialization/IdUtils.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Settings/SettingsRegistry.h> #include <AzCore/std/parallel/scoped_lock.h> #include <AzCore/std/smart_ptr/make_shared.h> #include <AzFramework/Components/TransformComponent.h> #include <AzFramework/Entity/GameEntityContextBus.h> #include <AzFramework/Spawnable/Spawnable.h> #include <AzFramework/Spawnable/SpawnableEntitiesManager.h> namespace AzFramework { template<typename T> void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request) { request.m_ticket = &GetTicketPayload<Ticket>(ticket); Queue& queue = priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); request.m_requestId = GetTicketPayload<Ticket>(ticket).m_nextRequestId++; queue.m_pendingRequest.push(AZStd::move(request)); } } SpawnableEntitiesManager::SpawnableEntitiesManager() { AZ::ComponentApplicationBus::BroadcastResult(m_defaultSerializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); AZ_Assert( m_defaultSerializeContext, "Failed to retrieve serialization context during construction of the Spawnable Entities Manager."); if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { AZ::u64 value = aznumeric_caster(m_highPriorityThreshold); settingsRegistry->Get(value, "/O3DE/AzFramework/Spawnables/HighPriorityThreshold"); m_highPriorityThreshold = aznumeric_cast<SpawnablePriority>(AZStd::clamp(value, 0llu, 255llu)); } } SpawnableEntitiesManager::~SpawnableEntitiesManager() { AZ_Assert(m_totalTickets == 0, "Shutting down the Spawnable Entities Manager while there are still active Spawnable Tickets."); } void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); SpawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::SpawnEntities( EntitySpawnTicket& ticket, AZStd::vector<uint32_t> entityIndices, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); SpawnEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityIndices = AZStd::move(entityIndices); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); queueEntry.m_referencePreviouslySpawnedEntities = optionalArgs.m_referencePreviouslySpawnedEntities; QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::DespawnEntity(AZ::EntityId entityId, EntitySpawnTicket& ticket, DespawnEntityOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnEntity hasn't been initialized."); DespawnEntityCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityId = entityId; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::RetrieveTicket( EntitySpawnTicket::Id ticketId, RetrieveEntitySpawnTicketCallback callback, RetrieveTicketOptionalArgs optionalArgs) { if (ticketId == 0) { AZ_Assert(false, "Ticket id provided to RetrieveEntitySpawnTicket is invalid."); return; } RetrieveTicketCommand queueEntry; queueEntry.m_ticketId = ticketId; queueEntry.m_callback = AZStd::move(callback); Queue& queue = optionalArgs.m_priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); queue.m_pendingRequest.push(AZStd::move(queueEntry)); } } void SpawnableEntitiesManager::ReloadSpawnable( EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable, ReloadSpawnableOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); ReloadSpawnableCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_spawnable = AZStd::move(spawnable); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::UpdateEntityAliasTypes( EntitySpawnTicket& ticket, AZStd::vector<EntityAliasTypeChange> updatedAliases, UpdateEntityAliasTypesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); UpdateEntityAliasTypesCommand queueEntry; queueEntry.m_entityAliases = AZStd::move(updatedAliases); queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ListEntities( EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ListIndicesAndEntities( EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListIndicesEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ClaimEntities( EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ClaimEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized."); ClaimEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs) { AZ_Assert(completionCallback, "Barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized."); BarrierCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::LoadBarrier( EntitySpawnTicket& ticket, BarrierCallback completionCallback, LoadBarrierOptionalArgs optionalArgs) { AZ_Assert(completionCallback, "Load barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to LoadBarrier hasn't been initialized."); LoadBarrierCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_checkAliasSpawnables = optionalArgs.m_checkAliasSpawnables; QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } auto SpawnableEntitiesManager::ProcessQueue(CommandQueuePriority priority) -> CommandQueueStatus { CommandQueueStatus result = CommandQueueStatus::NoCommandsLeft; if ((priority & CommandQueuePriority::High) == CommandQueuePriority::High) { if (ProcessQueue(m_highPriorityQueue) == CommandQueueStatus::HasCommandsLeft) { result = CommandQueueStatus::HasCommandsLeft; } } if ((priority & CommandQueuePriority::Regular) == CommandQueuePriority::Regular) { if (ProcessQueue(m_regularPriorityQueue) == CommandQueueStatus::HasCommandsLeft) { result = CommandQueueStatus::HasCommandsLeft; } } return result; } auto SpawnableEntitiesManager::ProcessQueue(Queue& queue) -> CommandQueueStatus { // Process delayed requests first. // Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete. size_t delayedSize = queue.m_delayed.size(); for (size_t i = 0; i < delayedSize; ++i) { Requests& request = queue.m_delayed.front(); CommandResult result = AZStd::visit( [this](auto&& args) -> CommandResult { return ProcessRequest(args); }, request); if (result == CommandResult::Requeue) { queue.m_delayed.emplace_back(AZStd::move(request)); } queue.m_delayed.pop_front(); } // Process newly added requests. while (true) { AZStd::queue<Requests> pendingRequestQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); queue.m_pendingRequest.swap(pendingRequestQueue); } if (!pendingRequestQueue.empty()) { while (!pendingRequestQueue.empty()) { Requests& request = pendingRequestQueue.front(); CommandResult result = AZStd::visit( [this](auto&& args) -> CommandResult { return ProcessRequest(args); }, request); if (result == CommandResult::Requeue) { queue.m_delayed.emplace_back(AZStd::move(request)); } pendingRequestQueue.pop(); } } else { break; } }; return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft; } void* SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) { static AZStd::atomic_uint32_t idCounter { 1 }; auto result = aznew Ticket(); result->m_spawnable = AZStd::move(spawnable); result->m_ticketId = idCounter++; m_totalTickets++; m_ticketsPendingRegistration++; AZ_Assert( m_ticketsPendingRegistration <= m_totalTickets, "There are less total entity spawn tickets than there are tickets pending registration in the SpawnableEntitiesManager."); RegisterTicketCommand queueEntry; queueEntry.m_ticket = result; { AZStd::scoped_lock queueLock(m_highPriorityQueue.m_pendingRequestMutex); queueEntry.m_requestId = result->m_nextRequestId++; m_highPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } return result; } void SpawnableEntitiesManager::IncrementTicketReference(void* ticket) { reinterpret_cast<Ticket*>(ticket)->m_referenceCount++; } void SpawnableEntitiesManager::DecrementTicketReference(void* ticket) { auto ticketInstance = reinterpret_cast<Ticket*>(ticket); if (ticketInstance->m_referenceCount-- == 1) { DestroyTicketCommand queueEntry; queueEntry.m_ticket = ticketInstance; { AZStd::scoped_lock queueLock(m_regularPriorityQueue.m_pendingRequestMutex); queueEntry.m_requestId = ticketInstance->m_nextRequestId++; m_regularPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } } } EntitySpawnTicket::Id SpawnableEntitiesManager::GetTicketId(void* ticket) { return reinterpret_cast<Ticket*>(ticket)->m_ticketId; } const AZ::Data::Asset<Spawnable>& SpawnableEntitiesManager::GetSpawnableOnTicket(void* ticket) { return reinterpret_cast<Ticket*>(ticket)->m_spawnable; } AZ::Entity* SpawnableEntitiesManager::CloneSingleEntity(const AZ::Entity& entityPrototype, EntityIdMap& prototypeToCloneMap, AZ::SerializeContext& serializeContext) { // If the same ID gets remapped more than once, preserve the original remapping instead of overwriting it. constexpr bool allowDuplicateIds = false; return AZ::IdUtils::Remapper<AZ::EntityId, allowDuplicateIds>::CloneObjectAndGenerateNewIdsAndFixRefs( &entityPrototype, prototypeToCloneMap, &serializeContext); } AZ::Entity* SpawnableEntitiesManager::CloneSingleAliasedEntity( const AZ::Entity& entityPrototype, const Spawnable::EntityAlias& alias, EntityIdMap& prototypeToCloneMap, AZ::Entity* previouslySpawnedEntity, AZ::SerializeContext& serializeContext) { AZ::Entity* clone = nullptr; switch (alias.m_aliasType) { case Spawnable::EntityAliasType::Original: // Behave as the original version. clone = CloneSingleEntity(entityPrototype, prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Disable: // Do nothing. return nullptr; case Spawnable::EntityAliasType::Replace: clone = CloneSingleEntity(*(alias.m_spawnable->GetEntities()[alias.m_targetIndex]), prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Additional: // The asset handler will have sorted and inserted a Spawnable::EntityAliasType::Original, so the just // spawn the additional entity. clone = CloneSingleEntity(*(alias.m_spawnable->GetEntities()[alias.m_targetIndex]), prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Merge: AZ_Assert(previouslySpawnedEntity != nullptr, "Merging components but there's no entity to add to yet."); AppendComponents( *previouslySpawnedEntity, alias.m_spawnable->GetEntities()[alias.m_targetIndex]->GetComponents(), prototypeToCloneMap, serializeContext); return nullptr; default: AZ_Assert(false, "Unsupported spawnable entity alias type: %i", alias.m_aliasType); return nullptr; } } void SpawnableEntitiesManager::AppendComponents( AZ::Entity& target, const AZ::Entity::ComponentArrayType& componentPrototypes, EntityIdMap& prototypeToCloneMap, AZ::SerializeContext& serializeContext) { // Only components are added and entities are looked up so no duplicate entity ids should be encountered. constexpr bool allowDuplicateIds = false; for (const AZ::Component* component : componentPrototypes) { AZ::Component* clone = AZ::IdUtils::Remapper<AZ::EntityId, allowDuplicateIds>::CloneObjectAndGenerateNewIdsAndFixRefs( component, prototypeToCloneMap, &serializeContext); AZ_Assert(clone, "Unable to clone component for entity '%s' (%zu).", target.GetName().c_str(), target.GetId()); [[maybe_unused]] bool result = target.AddComponent(clone); AZ_Assert(result, "Unable to add cloned component to entity '%s' (%zu).", target.GetName().c_str(), target.GetId()); } } void SpawnableEntitiesManager::InitializeEntityIdMappings( const Spawnable::EntityList& entities, EntityIdMap& idMap, AZStd::unordered_set<AZ::EntityId>& previouslySpawned) { // Make sure we don't have any previous data lingering around. idMap.clear(); previouslySpawned.clear(); idMap.reserve(entities.size()); previouslySpawned.reserve(entities.size()); for (auto& entity : entities) { idMap.emplace(entity->GetId(), AZ::Entity::MakeId()); } } void SpawnableEntitiesManager::RefreshEntityIdMapping( const AZ::EntityId& entityId, EntityIdMap& idMap, AZStd::unordered_set<AZ::EntityId>& previouslySpawned) { if (previouslySpawned.contains(entityId)) { // This entity has already been spawned at least once before, so we need to generate a new id for it and // preserve the new id to fix up any future entity references to this entity. idMap[entityId] = AZ::Entity::MakeId(); } else { // This entity hasn't been spawned yet, so use the first id we've already generated for this entity and mark // it as spawned so we know not to reuse this id next time. previouslySpawned.emplace(entityId); } } auto SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasConstVisitor aliases = ticket.m_spawnable->TryGetAliasesConst(); aliases.IsValid() && aliases.AreAllSpawnablesReady()) { AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector<uint32_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices; // Keep track how many entities there were in the array initially size_t spawnedEntitiesInitialCount = spawnedEntities.size(); // These are 'prototype' entities we'll be cloning from const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities(); uint32_t entitiesToSpawnSize = aznumeric_caster(entitiesToSpawn.size()); // Reserve buffers spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize); spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); // Pre-generate the full set of entity-id-to-new-entity-id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // We clear out and regenerate the set of IDs on every SpawnAllEntities call, because presumably every entity reference // in every entity we're about to instantiate is intended to point to an entity in our newly-instantiated batch, regardless // of spawn order. If we didn't clear out the map, it would be possible for some entities here to have references to // previously-spawned entities from a previous SpawnEntities or SpawnAllEntities call. InitializeEntityIdMappings(entitiesToSpawn, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); auto aliasIt = aliases.begin(); auto aliasEnd = aliases.end(); if (aliasIt == aliasEnd) { for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(i); } } else { for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); if (aliasIt == aliasEnd || aliasIt->m_sourceIndex != i) { spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(i); } else { // The list of entities has already been sorted and optimized (See SpawnableEntitiesAliasList:Optimize) so can // be safely executed in order without risking an invalid state. AZ::Entity* previousEntity = nullptr; do { AZ::Entity* clone = CloneSingleAliasedEntity( *entitiesToSpawn[i], *aliasIt, ticket.m_entityIdReferenceMap, previousEntity, *request.m_serializeContext); previousEntity = clone; if (clone) { spawnedEntities.emplace_back(clone); spawnedEntityIndices.push_back(i); } ++aliasIt; } while (aliasIt != aliasEnd && aliasIt->m_sourceIndex == i); } } } // There were no initial entities then the ticket now holds exactly all entities. If there were already entities then // a new set are not added so it no longer holds exactly the number of entities. ticket.m_loadAll = spawnedEntitiesInitialCount == 0; auto newEntitiesBegin = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; auto newEntitiesEnd = ticket.m_spawnedEntities.end(); // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView(newEntitiesBegin, newEntitiesEnd)); } // Add to the game context, now the entities are active for (auto it = newEntitiesBegin; it != newEntitiesEnd; ++it) { AZ::Entity* clone = (*it); clone->SetEntitySpawnTicketId(request.m_ticketId); GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, clone); } // Let other systems know about newly spawned entities for any post-processing after adding to the scene/game context. if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView(newEntitiesBegin, newEntitiesEnd)); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasConstVisitor aliases = ticket.m_spawnable->TryGetAliasesConst(); aliases.IsValid() && aliases.AreAllSpawnablesReady()) { AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector<uint32_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices; AZ_Assert( spawnedEntities.size() == spawnedEntityIndices.size(), "The indices for the spawned entities has gone out of sync with the entities."); // Keep track of how many entities there were in the array initially size_t spawnedEntitiesInitialCount = spawnedEntities.size(); // These are 'prototype' entities we'll be cloning from const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities(); size_t entitiesToSpawnSize = request.m_entityIndices.size(); if (ticket.m_entityIdReferenceMap.empty() || !request.m_referencePreviouslySpawnedEntities) { // This map keeps track of ids from prototype (spawnable) to clone (instance) allowing patch ups of fields referring // to entityIds outside of a given entity. // We pre-generate the full set of entity id to new entity id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // By default, we only initialize this map once because it needs to persist across multiple SpawnEntities calls, so // that reference fixups work even when the entity being referenced is spawned in a different SpawnEntities // (or SpawnAllEntities) call. // However, the caller can also choose to reset the map by passing in "m_referencePreviouslySpawnedEntities = false". InitializeEntityIdMappings(entitiesToSpawn, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); } spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize); spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); auto aliasBegin = aliases.begin(); auto aliasEnd = aliases.end(); if (aliasBegin == aliasEnd) { for (uint32_t index : request.m_entityIndices) { if (index < entitiesToSpawn.size()) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); spawnedEntities.push_back( CloneSingleEntity(*entitiesToSpawn[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(index); } } } else { for (uint32_t index : request.m_entityIndices) { if (index < entitiesToSpawn.size()) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); auto aliasIt = AZStd::lower_bound( aliasBegin, aliasEnd, index, [](const Spawnable::EntityAlias& lhs, uint32_t rhs) { return lhs.m_sourceIndex < rhs; }); if (aliasIt == aliasEnd || aliasIt->m_sourceIndex != index) { spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(index); } else { // The list of entities has already been sorted and optimized (See SpawnableEntitiesAliasList:Optimize) so // can be safely executed in order without risking an invalid state. AZ::Entity* previousEntity = nullptr; do { AZ::Entity* clone = CloneSingleAliasedEntity( *entitiesToSpawn[index], *aliasIt, ticket.m_entityIdReferenceMap, previousEntity, *request.m_serializeContext); previousEntity = clone; if (clone) { spawnedEntities.emplace_back(clone); spawnedEntityIndices.push_back(index); } ++aliasIt; } while (aliasIt != aliasEnd && aliasIt->m_sourceIndex == index); } } } } ticket.m_loadAll = false; // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { request.m_preInsertionCallback( request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } // Add to the game context, now the entities are active for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it) { AZ::Entity* clone = (*it); clone->SetEntitySpawnTicketId(request.m_ticketId); GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it); } if (request.m_completionCallback) { request.m_completionCallback( request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { for (AZ::Entity* entity : ticket.m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } ticket.m_spawnedEntities.clear(); ticket.m_spawnedEntityIndices.clear(); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(DespawnEntityCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { AZStd::vector<AZ::Entity*>& spawnedEntities = request.m_ticket->m_spawnedEntities; for (auto entityIterator = spawnedEntities.begin(); entityIterator != spawnedEntities.end(); ++entityIterator) { if (*entityIterator != nullptr && (*entityIterator)->GetId() == request.m_entityId) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. (*entityIterator)->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, (*entityIterator)->GetId()); AZStd::iter_swap(entityIterator, spawnedEntities.rbegin()); spawnedEntities.pop_back(); break; } } if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; AZ_Assert(ticket.m_spawnable.GetId() == request.m_spawnable.GetId(), "Spawnable is being reloaded, but the provided spawnable has a different asset id. " "This will likely result in unexpected entities being created."); if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { // Delete the original entities. for (AZ::Entity* entity : ticket.m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } // Rebuild the list of entities. ticket.m_spawnedEntities.clear(); const Spawnable::EntityList& entities = request.m_spawnable->GetEntities(); // Pre-generate the full set of entity id to new entity id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // This map is intentionally cleared out and regenerated here to ensure that we're starting fresh with mappings that // match the new set of prototype entities getting spawned. InitializeEntityIdMappings(entities, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); if (ticket.m_loadAll) { // The new spawnable may have a different number of entities and since the intent of the user was // to spawn every entity, simply start over. ticket.m_spawnedEntityIndices.clear(); size_t entitiesToSpawnSize = entities.size(); for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping(entities[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); AZ::Entity* clone = CloneSingleEntity(*entities[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); ticket.m_spawnedEntities.push_back(clone); ticket.m_spawnedEntityIndices.push_back(i); } } else { size_t entitiesSize = entities.size(); for (uint32_t index : ticket.m_spawnedEntityIndices) { // It's possible for the new spawnable to have a different number of entities, so guard against this. // It's also possible that the entities have moved within the spawnable to a new index. This can't be // detected and will result in the incorrect entities being spawned. if (index < entitiesSize) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping(entities[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); AZ::Entity* clone = CloneSingleEntity(*entities[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); ticket.m_spawnedEntities.push_back(clone); } } } ticket.m_spawnable = AZStd::move(request.m_spawnable); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(UpdateEntityAliasTypesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasVisitor aliases = ticket.m_spawnable->TryGetAliases(); aliases.IsValid()) { for (EntityAliasTypeChange& replacement : request.m_entityAliases) { aliases.UpdateAliasType(replacement.m_aliasIndex, replacement.m_newAliasType); } aliases.Optimize(); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { request.m_listCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { AZ_Assert( ticket.m_spawnedEntities.size() == ticket.m_spawnedEntityIndices.size(), "Entities and indices on spawnable ticket have gone out of sync."); request.m_listCallback(request.m_ticketId, SpawnableConstIndexEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntityIndices.begin(), ticket.m_spawnedEntities.size())); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { request.m_listCallback(request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); ticket.m_spawnedEntities.clear(); ticket.m_spawnedEntityIndices.clear(); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(LoadBarrierCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (request.m_checkAliasSpawnables) { if (Spawnable::EntityAliasConstVisitor visitor = ticket.m_spawnable->TryGetAliasesConst(); !visitor.IsValid() || !visitor.AreAllSpawnablesReady()) { return CommandResult::Requeue; } } request.m_completionCallback(request.m_ticketId); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(RetrieveTicketCommand& request) -> CommandResult { auto entitySpawnTicketIterator = m_entitySpawnTicketMap.find(request.m_ticketId); if (entitySpawnTicketIterator == m_entitySpawnTicketMap.end()) { if (m_ticketsPendingRegistration > 0) { // There are still tickets pending registration, which may hold the reference, so delay this request // until all tickets are registered and it's known for sure if the ticket doesn't exist anymore. return CommandResult::Requeue; } else { AZ_Assert(false, "The EntitySpawnTicket corresponding to id '%lu' cannot be found", request.m_ticketId); return CommandResult::Executed; } } // About to make a copy so increase the reference count. entitySpawnTicketIterator->second->m_referenceCount++; request.m_callback(InternalToExternalTicket(entitySpawnTicketIterator->second, this)); return CommandResult::Executed; } auto SpawnableEntitiesManager::ProcessRequest(RegisterTicketCommand& request) -> CommandResult { if (request.m_requestId == request.m_ticket->m_currentRequestId) { m_entitySpawnTicketMap.insert_or_assign(request.m_ticket->m_ticketId, request.m_ticket); request.m_ticket->m_currentRequestId++; AZ_Assert( m_ticketsPendingRegistration > 0, "Attempting to decrement the number of entity spawn tickets pending registration while there are no registrations pending " "in the SpawnableEntitiesManager."); m_ticketsPendingRegistration--; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request) -> CommandResult { if (request.m_requestId == request.m_ticket->m_currentRequestId) { for (AZ::Entity* entity : request.m_ticket->m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } m_entitySpawnTicketMap.erase(request.m_ticket->m_ticketId); delete request.m_ticket; AZ_Assert( m_totalTickets > 0, "Attempting to decrement the total number of entity spawn tickets while are zero tickets in the SpawnableEntitiesManager."); m_totalTickets--; return CommandResult::Executed; } else { return CommandResult::Requeue; } } } // namespace AzFramework
47.190249
140
0.614676
BreakerOfThings
db70f6231304eca566a5b0200e9a8fb443ab0e8d
6,148
cpp
C++
skyline-continuous/src/src/main.cpp
alex-kulikov-git/skyline-computation
e2fc8328f712a2ec0bfcad797a79cf9cbda524a8
[ "MIT" ]
null
null
null
skyline-continuous/src/src/main.cpp
alex-kulikov-git/skyline-computation
e2fc8328f712a2ec0bfcad797a79cf9cbda524a8
[ "MIT" ]
null
null
null
skyline-continuous/src/src/main.cpp
alex-kulikov-git/skyline-computation
e2fc8328f712a2ec0bfcad797a79cf9cbda524a8
[ "MIT" ]
null
null
null
/* * main.cpp * Created on: July 5, 2018 * Author: Oleksii Kulikov */ #include <iostream> #include <chrono> #include "bnl.hpp" #include "output.hpp" #include "generator.hpp" #include "old_bnl.hpp" #include "old_dnc.hpp" #include "dnc.hpp" #include "nnl.hpp" #include "parallel_dnc.hpp" static std::size_t n = 0, dimension = 0; void init(){ std::cout << "Number of tuples: \nn = "; std::cin >> n; std::cout << "Number of dimensions: \ndimensions = "; std::cin >> dimension; } // @param cp gives the variation of the algorithm ( 0: getNext | 1: consume/produce | 2: parallel consume/produce ) double test_algorithm(Output &output, int cp){ std::chrono::_V2::system_clock::time_point start = std::chrono::high_resolution_clock::now(); switch(cp){ case 0: output.getTuples(); break; case 1: output.getTuplesCP(); break; case 2: output.getTuplesParallelCP(); break; default: break; } std::chrono::_V2::system_clock::time_point finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; output.print(); std::cout << "Elapsed time: " << elapsed.count() << "s\n\n"; return elapsed.count(); } bool check_results(const std::vector<std::vector<std::vector<double>>> &results){ static bool output = true; // check if sizes are equal for(auto r:results){ if(results[0].size() != r.size()){ std::cout << "Result sizes do not match.\n"; output = false; } } // check if results match for(std::size_t i = 1; i < results.size(); i++){ for(std::size_t j = 0; j < results[0].size(); j++){ if(std::find(results[i].begin(), results[i].end(), results[0][j]) == results[i].end()) { std::cout << "Tuple[" << j << "] in result 0 does not exist in result " << i << ".\n"; output = false; } } } return output; } int main() { init(); BNL *bnl_pointer; Output *output_pointer; // BNL iterator model Generator g(bnl_pointer, n, dimension); BNL bnl_im(output_pointer, &g); Output o1(&bnl_im); g.set_parent(&bnl_im); bnl_im.set_parent(&o1); std::cout << "Computing Skyline with iterator model BNL...\n"; double elapsed_1 = test_algorithm(o1, 0); // BNL produce/consume BNL bnl_pc(output_pointer, &g); Output o2(&bnl_pc); g.set_parent(&bnl_pc); bnl_pc.set_parent(&o2); std::cout << "Computing Skyline with produce/consume BNL...\n"; double elapsed_2 = test_algorithm(o2, 1); // NNL produce/consume NNL nnl_pc(output_pointer, &g); Output o3(&nnl_pc); g.set_parent(&nnl_pc); nnl_pc.set_parent(&o3); std::cout << "Computing Skyline with produce/consume NNL...\n"; double elapsed_3 = test_algorithm(o3, 1); // NNL produce/consume parallelized NNL nnl_parallel_pc(output_pointer, &g); Output o4(&nnl_parallel_pc); g.set_parent(&nnl_parallel_pc); nnl_parallel_pc.set_parent(&o4); std::cout << "Computing Skyline with produce/consume parallelized NNL...\n"; double elapsed_4 = test_algorithm(o4, 2); // DNC produce/consume DNC dnc(output_pointer, &g); Output o5(&dnc); g.set_parent(&dnc); dnc.set_parent(&o5); std::cout << "Computing Skyline with produce/consume DNC...\n"; double elapsed_5 = test_algorithm(o5, 1); // DNC produce/consume parallelized Parallel_DNC parallel_dnc(output_pointer, &g); Output o6(&parallel_dnc); g.set_parent(&parallel_dnc); parallel_dnc.set_parent(&o6); std::cout << "Computing Skyline with parallel produce/consume DNC...\n"; double elapsed_6 = test_algorithm(o6, 1); // OLD VERSIONS FOR TESTING // Old version of BNL // OldBNL old_bnl; // auto start = std::chrono::high_resolution_clock::now(); // std::cout << "Computing Skyline with normal BNL...\n"; // std::vector<std::vector<double>> result_bnl = old_bnl.computeSkyline(g.getTuples(), n); // auto finish = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> elapsed_7 = finish - start; // std::cout << "Resulting Skyline: \n"; // for(std::vector<std::vector<double>>::size_type i = 0; i < result_bnl.size(); i++){ // std::cout << "Tuple[" << i << "] is ("; // for(std::vector<double>::size_type j = 0; j < result_bnl[i].size(); j++){ // std::cout << result_bnl[i][j] << ' '; // } // std::cout << ")\n"; // } // std::cout << "\nElapsed time: " << elapsed_7.count() << "s\n\n"; // Old version of DNC // OldDNC old_dnc; // start = std::chrono::high_resolution_clock::now(); // std::cout << "Computing Skyline with normal DNC...\n"; // std::vector<std::vector<double>> result_old_dnc = old_dnc.computeSkyline(g.getTuples(), dimension); // finish = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> elapsed_8 = finish - start; // std::cout << "Resulting Skyline: \n"; // for(std::vector<std::vector<double>>::size_type i = 0; i < result_old_dnc.size(); i++){ // std::cout << "Tuple[" << i << "] is ("; // for(std::vector<double>::size_type j = 0; j < result_old_dnc[i].size(); j++){ // std::cout << result_old_dnc[i][j] << ' '; // } // std::cout << ")\n"; // } // std::cout << "\nElapsed time: " << elapsed_8.count() << "s\n\n"; // Total std::cout << "Input was: n = " << n << " dimension = " << dimension << "\n\n"; std::cout << "Results are: "; std::vector<std::vector<std::vector<double>>> to_check; to_check.push_back(o1.getStorage()); to_check.push_back(o2.getStorage()); to_check.push_back(o3.getStorage()); to_check.push_back(o4.getStorage()); to_check.push_back(o5.getStorage()); to_check.push_back(o6.getStorage()); // to_check.push_back(result_bnl); // to_check.push_back(result_old_dnc); if(check_results(to_check)) std::cout << "OK\n"; else std::cout << "NOT OK\n"; std::cout << "\nExecution time\n"; std::cout << "Iterator Model BNL: " << elapsed_1 << "s\n"; std::cout << "Produce/Consume BNL " << elapsed_2 << "s\n"; std::cout << "Produce/Consume NNL: " << elapsed_3 << "s\n"; std::cout << "Produce/Consume NNL Parallelized: " << elapsed_4 << "s\n"; std::cout << "Produce/Consume DNC: " << elapsed_5 << "s\n"; std::cout << "Produce/Consume DNC Parallelized: " << elapsed_6 << "s\n"; // std::cout << "Normal BNL: " << elapsed_7.count() << "s\n"; // std::cout << "Normal DNC: " << elapsed_8.count() << "s\n"; return 0; }
31.690722
115
0.652082
alex-kulikov-git
db71160728a089fda4b16b0ff3b5aeedbf75c233
28,682
cpp
C++
src/XESCore/TensorRoads.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/XESCore/TensorRoads.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/XESCore/TensorRoads.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2007, Laminar Research. * * 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 "TensorRoads.h" #include "MapDefs.h" #include "../RenderFarmUI/RF_DEMGraphics.h" #include "DEMDefs.h" #include "MapAlgs.h" #include "MapOverlay.h" #include "MapTopology.h" #include "PolyRasterUtils.h" #include "TensorUtils.h" #include "MathUtils.h" #include "ParamDefs.h" #include "GISTool_Globals.h" #include "PerfUtils.h" #include "MapCreate.h" #include "XUtils.h" #define ADVANCE_RATIO 0.0005 #define PROFILE_PERFORMANCE 1 #if PROFILE_PERFORMANCE #define TIMER(x) StElapsedTime __PerfTimer##x(#x); #else #define TIMER(x) #endif // SEt this to 1 to see the road restriction DEM - can explain why no roads showed up in a location. #define SHOW_ROAD_RESTRICT 0 // Make roads EVEN if origin code says not to. Useful for testing maybe. #define IGNORE_ORIGIN_CODES 0 // Show roads as debug mesh lines #define SHOW_GENERATED_ROADS 0 // Ignore urban density - useful for debugging #define IGNORE_DENSITY 1 /* Back before we had OSM, TensorRoads generated the "fake" road grids for urban areas where we lacked true vector data. This came from an academic paper. Here are the major ideas: - A "tensor field is a "flow field" - that is, a field of 2-d vector directions. - The idea was two-step: make a flow field that loosel corresponds to how we want the road grid to "flow", then turn the tensor field into roads. TENSOR FIELDS A tensor field is a field of 3-d rotations - its "flow" is bent by the rotations. What's cool about tensors (as opposed to a normal 2-d field of vectors indicating direction, or a 2-d field of angles) is that tensor fields are affine transforms and thus we can add them together and scale them. In other words, the same kinds of "blending" that would make an image look good produces VERY reasonable and sane results for tensor fields. Furthermore, tensor fields can be defined functionally - thus we can do a "composition of functions" (with the functions weighted. In fact, that is exactly what we do: we can build a tensor out of: - The terrain gradient, which will make the road grid follow the terrain. - Linear or circular pre-defined functions, which may have attenuation. - We can build linear gradients that scale off known edges to enforce the grid along highways. With the right blending gradients, we get a reasonably sane tensor map that seems to reflect 'local stuff'. TENSOR 2 ROADS The way we convert our tensor field is pretty easy. We create "seed" points along known highways (seed roads) and at those seed points we make a small step either along or normal to the flow. We then drop a seed for our cross-street and keep going. The result will be a sort of emergent grid that bends around the natural "flow" of the tensor field. If our tensor field is aesthetically pleasing (in otherwords, fly) then the road grid won't look that bad. There are some heuristics in this seeding to try to weed out and generally sanatize the emerging edges, as well as to keep the process fast. For example, we use a raster mask to avoid over-adding roads. (If the algorithm is allowed to run forever, it will eventually fill in an infinite number of infinitely thin lines, for certain tensors.) */ /************************************************************************************************************************************************ * ************************************************************************************************************************************************/ inline bool RoadsForThisFace(Face_handle f) { return !f->data().IsWater() && f->data().mTerrainType != terrain_Airport #if !IGNORE_ORIGIN_CODES && f->data().mParams.count(af_OriginCode) && f->data().mParams[af_OriginCode] == 2.0 #endif ; } bool CrossCheck(const Segment2& s1, const Segment2& s2, Point2& p) { if(s1.p1 == s2.p1 || s1.p1 == s2.p2 || s1.p2 == s2.p1 || s1.p2 == s2.p2) return false; if(!s1.could_intersect(s2)) return false; if(s1.p1.y() == s2.p1.y()) { DebugAssert(s1.p1.x() != s2.p2.x()); if (s1.p1.x() < s2.p1.x()) { if (s1.intersect(s2,p) && p != s1.p1 && p != s1.p2) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y); return true; } else return false; } else { if (s2.intersect(s1,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y); return true; } else return false; } } else { if (s1.p1.y() < s2.p1.y()) { if (s1.intersect(s2,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y); return true; } else return false; } else { if (s2.intersect(s1,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y); return true; } else return false; } } } Halfedge_handle InsertOneEdge(const Point_2& p1, const Point_2& p2, Pmwx& io_map, Locator& io_locator) { DebugAssert(p1 != p2); Vertex_handle v1, v2; Face_handle f; CGAL::Object obj1 = io_locator.locate(p1); CGAL::Object obj2 = io_locator.locate(p2); bool has_v1 = CGAL::assign(v1, obj1); bool has_v2 = CGAL::assign(v2, obj2); Curve_2 s(Segment_2(p1,p2)); if(has_v1 && has_v2) return io_map.insert_at_vertices(s, v1,v2); else if (has_v1) return io_map.insert_from_left_vertex(s, v1); else if (has_v2) return io_map.insert_from_right_vertex(s, v2); else if(CGAL::assign(f,obj1)) return io_map.insert_in_face_interior(s,f); else { //return CGAL::insert_curve(io_map,s); DebugAssert(!"Not disjoint!!"); return Halfedge_handle(); } } /* void SetRoadProps(Halfedge_handle e) { if (!e->data().mDominant) e = e->twin(); e->data().mSegments.push_back(GISNetworkSegment_t()); e->data().mSegments.back().mFeatType = road_LocalUnsep; } */ inline bool LessEdgesThan(Face_handle f, int c) { if(f->is_unbounded()) return false; Pmwx::Ccb_halfedge_circulator circ,stop; circ = stop = f->outer_ccb(); do { if(c-- <= 0) return false; ++circ; } while(circ != stop); for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h) { circ = stop = *h; do { if(c-- <= 0) return false; ++circ; } while(circ != stop); } return true; } void BulkZapRoads(const DEMGeo& inUrbanDensity, Pmwx& io_map) { printf("BEFORE ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2); for(Pmwx::Edge_iterator e = io_map.edges_begin(); e != io_map.edges_end(); ) { if((e->source()->degree() > 2 && e->target()->degree() > 2 && // If we have a real intersection on both sides AND e->face() != e->twin()->face() && // We divide two DIFFERENT faces (so we don't make an island) AND LessEdgesThan(e->face(), 6) && // The faces aren't too complex LessEdgesThan(e->twin()->face(), 6)) || (e->source()->degree() == 1 || e->target()->degree() == 1) // Or if we're an antenna ) { Point_2 mp(CGAL::midpoint(e->source()->point(),e->target()->point())); double d = inUrbanDensity.get(inUrbanDensity.lon_to_x(CGAL::to_double(mp.x())),inUrbanDensity.lat_to_y(CGAL::to_double(mp.y()))); if(e->source()->degree() == 1 || e->target()->degree() == 1) d = min(d,0.5); // always think of nuking antennas #if IGNORE_DENSITY d =1.0; #endif if(!RollDice(d)) { Halfedge_handle k = e; ++e; io_map.remove_edge(k); } else ++e; } else ++e; } printf("AFTER ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2); } void BulkInsertRoads(vector<Segment2> roads, Pmwx& io_map) { GIS_halfedge_data hed; hed.mSegments.push_back(GISNetworkSegment_t()); hed.mSegments.back().mFeatType = road_Local; vector<Segment_2> road_vec(roads.size()); vector<GIS_halfedge_data> data_vec(roads.size(),hed); for(int n = 0; n < roads.size(); ++n) road_vec[n] = Segment_2(ben2cgal<Point_2>(roads[n].p1),ben2cgal<Point_2>(roads[n].p2)); Map_CreateWithLineData(io_map, road_vec, data_vec); } int ThinLine(list<Point2>& pts, double max_dist_move, double max_dist_seg) { max_dist_move *= max_dist_move; max_dist_seg *= max_dist_seg; int t=0; while(1) { list<Point2>::iterator best_dead = pts.end(); double d_sq = 0.0f; for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i) { if(i != pts.begin()) { list<Point2>::iterator p(i), n(i); --p; ++n; if(n != pts.end()) { Segment2 span(*p, *n); if(span.squared_length() < max_dist_seg) { Point2 pp(span.projection(*i)); double my_dist = Segment2(pp, *i).squared_length(); if(my_dist < max_dist_move && my_dist > d_sq) { best_dead = i; d_sq = my_dist; } } } } } if(best_dead == pts.end()) break; pts.erase(best_dead); ++t; } return t; } /************************************************************************************************************************************************ * ************************************************************************************************************************************************/ RoadPrefs_t gRoadPrefs = { 10.0, 50000.0, 0.8, 1.0 }; struct TensorSeed { Point2 p; bool major; int x; int y; }; typedef list<TensorSeed> SeedQueue; struct Tensor_info { const DEMGeo * elev; const DEMGeo * grdx; const DEMGeo * grdy; const DEMGeo * uden; const DEMGeo * urad; const DEMGeo * usqr; Bbox2 bounds; }; inline int dem_get(const DEMGeo& d, int x, int y) { float e[9]; e[0] = d.get(x-1,y-1); e[1] = d.get(x ,y-1); e[2] = d.get(x+1,y-1); e[3] = d.get(x-1,y ); e[4] = d.get(x ,y ); e[5] = d.get(x+1,y ); e[6] = d.get(x-1,y+1); e[7] = d.get(x ,y+1); e[8] = d.get(x+1,y+1); if(e[4] == DEM_NO_DATA) return DEM_NO_DATA; int f = 0; bool h = false; for(int n = 0; n < 9; ++n) if(e[n] != DEM_NO_DATA) { h = true; f |= (int) e[n]; } return h ? f : DEM_NO_DATA; } static Vector2 Tensor_Func(const Point2& p, void * ref) { Tensor_info * i = (Tensor_info *) ref; double lon = interp(0,i->bounds.p1.x(),1,i->bounds.p2.x(),p.x()); double lat = interp(0,i->bounds.p1.y(),1,i->bounds.p2.y(),p.y()); double xe = i->elev->lon_to_x(lon); double ye = i->elev->lat_to_y(lat); double xr = i->urad->lon_to_x(lon); double yr = i->urad->lat_to_y(lat); double xu = i->usqr->lon_to_x(lon); double yu = i->usqr->lat_to_y(lat); double xg = i->grdx->lon_to_x(lon); double yg = i->grdx->lat_to_y(lat); double sq_w = 0.0f; double ir_w = 1.0f; float sqv = i->usqr->get(xu,yu); if (sqv == 1.0) sq_w = 1.f, ir_w = 0.0f; if (sqv == 2.0) sq_w = 0.f, ir_w = 1.0f; Vector2 basis = (Gradient2Tensor(Vector2(i->elev->gradient_x_bilinear(xe,ye),i->elev->gradient_y_bilinear(xe,ye))) * gRoadPrefs.elevation_weight); if(ir_w > 0.0f) basis += (Gradient2Tensor(Vector2(i->urad->gradient_x_bilinear(xr,yr),i->urad->gradient_y_bilinear(xr,yr))) * gRoadPrefs.radial_weight * ir_w); if (sq_w > 0.0f) basis += Vector2(i->grdx->get(xg,yg),i->grdy->get(xg,yg)); return basis; } bool CheckSeed( const TensorSeed& s, DEMGeo& d) { int old = dem_get(d,s.x,s.y); if(old==DEM_NO_DATA) return false; int mask = s.major ? 1 : 2; if ((old & mask) == 0) { return true; } return false; } void QueueSeed( const Point2& p, bool major, DEMGeo& dem, SeedQueue& q) { TensorSeed s; s.p = p; s.major = major; s.x = dem.lon_to_x(p.x()); s.y = dem.lat_to_y(p.y()); int old = dem_get(dem,s.x,s.y); if(old==DEM_NO_DATA)return; int mask = s.major ? 5 : 6; if ((old & mask) == 0) { old |= 4; dem(s.x,s.y) = old; q.push_back(s); } } bool CheckStats(const Point2& p, const Point2& p_old, const DEMGeo& elev, const DEMGeo& slope, const DEMGeo& density, float amp) { // return true; float d = density.get(density.lon_to_x(p.x()),density.lat_to_y(p.y())); float s = slope.get(slope.lon_to_x(p.x()),slope.lat_to_y(p.y())); if(d == DEM_NO_DATA) return false; d += amp; if (!RollDice(d)) return false; // if (!RollDice((d*gRoadPrefs.density_amp))) return false; float ss = fabs(elev.value_linear(p.x(),p.y())-elev.value_linear(p_old.x(),p_old.y())); float rr = pythag(elev.x_dist_to_m(elev.lon_to_x(p.x())-elev.lon_to_x(p_old.x())), elev.y_dist_to_m(elev.lat_to_y(p.y())-elev.lat_to_y(p_old.y()))); if(rr==0.0) return true; if(RollDice(ss / rr)*gRoadPrefs.slope_amp)return false; // if(RollDice(s * gRoadPrefs.slope_amp)) return false; return true; } bool CheckAndRegister( const Point2& p, DEMGeo& dem, int& ox, int& oy, int& ctr, bool major) { int x = intlim(dem.lon_to_x(p.x()),0,dem.mWidth -1); int y = intlim(dem.lat_to_y(p.y()),0,dem.mHeight-1); if(x == ox && y == oy) return (ctr-- > 0); ox =x; oy =y; ctr = 10; int old = dem.get(x,y); if(old==DEM_NO_DATA)return false; int mask = major ? 1 : 2; if ((old & mask) == 0) { old |= mask; dem(x,y) = old; return true; } return false; } void TensorForFace( const DEMGeo& inElevation, const DEMGeo& inUrbanDensity, const DEMGeo& inUrbanRadial, const DEMGeo& inUrbanSquare, const DEMGeo& inGridX, const DEMGeo& inGridY, Tensor_info& t) { t.elev = &inElevation; t.urad = &inUrbanRadial; t.usqr = &inUrbanSquare; t.uden = &inUrbanDensity; t.grdx = &inGridX; t.grdy = &inGridY; t.bounds.p1.x_ = inElevation.mWest ; t.bounds.p1.y_ = inElevation.mSouth; t.bounds.p2.x_ = inElevation.mEast ; t.bounds.p2.y_ = inElevation.mNorth; } void RasterEdge( Halfedge_handle e, DEMGeo& dem, Vector2 (* tensorFunc)(const Point2& p, void * ref), void * tensorRef) { int x1 = intlim(dem.lon_to_x(CGAL::to_double(e->source()->point().x())),0,dem.mWidth-1); int x2 = intlim(dem.lon_to_x(CGAL::to_double(e->target()->point().x())),0,dem.mWidth-1); int y1 = intlim(dem.lat_to_y(CGAL::to_double(e->source()->point().y())),0,dem.mHeight-1); int y2 = intlim(dem.lat_to_y(CGAL::to_double(e->target()->point().y())),0,dem.mHeight-1); Vector2 road_dir(cgal2ben(e->source()->point()),cgal2ben(e->target()->point())); road_dir.normalize(); if(std::abs(x2-x1) > std::abs(y2-y1)) { // "Horizontal line" if(x2 < x1) { swap(x1,x2); swap(y1,y2); } for(int x = x1; x <= x2; ++x) { int y = intlim(interp(x1,y1,x2,y2,x),0,dem.mHeight-1); Vector2 e(Tensor2Eigen(tensorFunc( Point2(interp(0,0,dem.mWidth -1,1,x), interp(0,0,dem.mHeight-1,1,y)),tensorRef))); double align_major = fabs(road_dir.dot(e)); e = e.perpendicular_ccw(); double align_minor = fabs(road_dir.dot(e)); int old = dem.get(x,y); if(align_major > 0.7) old |= 1; if(align_minor > 0.7) old |= 2; dem(x,y)=old; } } else { // "Vertical line" if(y2 < y1) { swap(x1,x2); swap(y1,y2); } for(int y = y1; y < y2; ++y) { int x = intlim(interp(y1,x1,y2,x2,y),0,dem.mWidth-1); Vector2 e(Tensor2Eigen(tensorFunc( Point2(interp(0,0,dem.mWidth -1,1,x), interp(0,0,dem.mHeight-1,1,y)),tensorRef))); double align_major = fabs(road_dir.dot(e)); e = e.perpendicular_ccw(); double align_minor = fabs(road_dir.dot(e)); int old = dem.get(x,y); if(align_major > 0.8) old |= 1; if(align_minor > 0.8) old |= 2; dem(x,y)=old; } } } void BuildRoadsForFace( Pmwx& ioMap, const DEMGeo& inElevation, const DEMGeo& inSlope, const DEMGeo& inUrbanDensity, const DEMGeo& inUrbanRadial, const DEMGeo& inUrbanSquare, Face_handle inFace, ProgressFunc inProg, ImageInfo * ioTensorImage, double outTensorBounds[4]) { Pmwx::Face_iterator f; int rx1, rx2, x, y; Tensor_info t; // gMeshLines.clear(); // gMeshPoints.clear(); DEMGeo road_restrict(inElevation.mWidth,inElevation.mHeight); DEMGeo grid_x(inElevation.mWidth,inElevation.mHeight); DEMGeo grid_y(inElevation.mWidth,inElevation.mHeight); road_restrict.copy_geo_from(inElevation); grid_x.copy_geo_from(inElevation); grid_y.copy_geo_from(inElevation); /********************************************************************************************************************************** * INITIALIZE THE ROAD RESTRICTION GRID USING WATER AND OTHER NON-PASSABLES! **********************************************************************************************************************************/ // Best to zap out a lot here since more possiblep points means more time in the alg. { TIMER(burn_water) set<Face_handle> no_road_faces; set<Halfedge_handle> bounds; PolyRasterizer<double> raster; for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f) if (!f->is_unbounded()) if(!RoadsForThisFace(f)) no_road_faces.insert(f); FindEdgesForFaceSet<Pmwx>(no_road_faces, bounds); y = SetupRasterizerForDEM(bounds, road_restrict, raster); raster.StartScanline(y); while (!raster.DoneScan()) { while (raster.GetRange(rx1, rx2)) { rx1 = intlim(rx1,0,road_restrict.mWidth-1); rx2 = intlim(rx2,0,road_restrict.mWidth-1); for (x = rx1; x < rx2; ++x) { road_restrict(x,y)=3.0; } } ++y; if (y >= road_restrict.mHeight) break; raster.AdvanceScanline(y); } { DEMGeo temp(road_restrict); for(y = 0; y < temp.mHeight; ++y) for(x = 0; x < temp.mWidth ; ++x) { if(temp.get_radial(x,y,1,0.0) != 0.0) road_restrict(x,y) = 3.0; } } } /********************************************************************************************************************************** * BURN EACH VECTOR INTO THE RESTRICTION GRID TOO **********************************************************************************************************************************/ { TIMER(burn_roads) TensorForFace( inElevation, inUrbanDensity, inUrbanRadial, inUrbanSquare, grid_x, grid_y, t); for(Pmwx::Edge_iterator e = ioMap.edges_begin(); e != ioMap.edges_end(); ++e) RasterEdge(e, road_restrict, Tensor_Func, &t); } #if DEV // gDem[dem_Wizard] = road_restrict; #endif /********************************************************************************************************************************** * BUILD GRID TENSOR FIELD **********************************************************************************************************************************/ // Running a tensor func that accesses every polygon vertex in its evaluator would be unacceptably slow. So we simply rasterize // each polygon's interior using its own internal tensor func, which simplifies the cost of building this. This lowers the accuracy // of the grid tensor field, but we don't care that much anyway. { TIMER(calc_linear_tensors) // int tcalcs = 0; for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f) if (!f->is_unbounded()) if(RoadsForThisFace(f)) { // First build a polygon with tensor weights for the face we're working on. vector<Point2> poly; vector<Vector2> tensors; PolyRasterizer<double> raster; Pmwx::Ccb_halfedge_circulator circ = f->outer_ccb(); Pmwx::Ccb_halfedge_circulator start = circ; Bbox2 bounds(cgal2ben(circ->source()->point())); do { poly.push_back(cgal2ben(circ->target()->point())); bounds += cgal2ben(circ->target()->point()); Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point())); Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point())); prev.normalize(); next.normalize(); Vector2 v(prev+next); v.normalize(); tensors.push_back(/*Eigen2Tensor*/(v)); ++circ; } while (circ != start); for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h) { Pmwx::Ccb_halfedge_circulator circ(*h); Pmwx::Ccb_halfedge_circulator start = circ; do { poly.push_back(cgal2ben(circ->target()->point())); Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point())); Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point())); prev.normalize(); next.normalize(); Vector2 v(prev+next); v.normalize(); tensors.push_back(/*Eigen2Tensor*/(v)); ++circ; } while(circ != start); } // Now rasterize into the polygon... double sz = (bounds.p2.y() - bounds.p1.y()) * (bounds.p2.x() - bounds.p1.x()); y = SetupRasterizerForDEM(f, road_restrict, raster); raster.StartScanline(y); while (!raster.DoneScan()) { while (raster.GetRange(rx1, rx2)) { rx1 = intlim(rx1,0,road_restrict.mWidth-1); rx2 = intlim(rx2,0,road_restrict.mWidth-1); for (x = rx1; x < rx2; ++x) if(road_restrict.get(x,y) != 3.0) { float sq = inUrbanSquare.get( inUrbanSquare.lon_to_x(grid_x.x_to_lon(x)), inUrbanSquare.lat_to_y(grid_x.y_to_lat(y))); if(sq == 1.0) { Vector2 t(grid_x.get(x,y),grid_y.get(x,y)); for (int n = 0; n < poly.size(); ++n) { // ++tcalcs; t += (Linear_Tensor(poly[n],tensors[n], 4.0 / sz, Point2(road_restrict.x_to_lon(x),road_restrict.y_to_lat(y)))); } grid_x(x,y) = t.dx; grid_y(x,y) = t.dy; } } } ++y; if (y >= road_restrict.mHeight) break; raster.AdvanceScanline(y); } } // printf("Total tensor calcs for road grid: %d\n",tcalcs); } /********************************************************************************************************************************** * SEED THE QUEUE! **********************************************************************************************************************************/ SeedQueue seedQ; { TIMER(build_seedQ) for(Pmwx::Vertex_iterator v = ioMap.vertices_begin(); v != ioMap.vertices_end(); ++v) { bool has_road = false; Pmwx::Halfedge_around_vertex_circulator circ(v->incident_halfedges()); Pmwx::Halfedge_around_vertex_circulator stop(circ); do { if (!circ->data().mSegments.empty() || !circ->twin()->data().mSegments.empty()) { has_road = true; break; } ++circ; } while (circ != stop); if(has_road) { QueueSeed(cgal2ben(v->point()),false,road_restrict,seedQ); } } printf("Queued %llu seeds origially.\n", (unsigned long long)seedQ.size()); } /********************************************************************************************************************************** * RUN THROUGH THE QUEUE, BUILDING ROADS **********************************************************************************************************************************/ vector<Segment2> roads; int ctr=0; { TIMER(eval_seed_Q) while(!seedQ.empty()) { ++ctr; if(CheckSeed(seedQ.front(),road_restrict)) { list<Point2> pts; Point2 fp(seedQ.front().p); Point2 bp(fp); pts.push_back(fp); bool front_alive = true; bool back_alive = true; bool major = seedQ.front().major; int fx(seedQ.front().x); int fy(seedQ.front().y); int fc=10,bc=10; int bx = fx, by = fy; Vector2 fe(0.0,0.0); Vector2 be(0.0,0.0); do { if (front_alive) { Vector2 e = Tensor2Eigen(Tensor_Func( Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,fp.x()), interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,fp.y())),&t)); if (!seedQ.front().major) e = e.perpendicular_ccw(); if(e.dot(fe) < 0) e = -e; fe = e; e *= ADVANCE_RATIO; fp += e; front_alive = CheckAndRegister(fp,road_restrict,fx, fy, fc, major); if(front_alive) front_alive = CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp); if(front_alive) { pts.push_front(fp); if (CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, 0.0f)) QueueSeed(fp,!major,road_restrict,seedQ); } } if (back_alive) { Vector2 e = -Tensor2Eigen(Tensor_Func( Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,bp.x()), interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,bp.y())),&t)); if (!seedQ.front().major) e = e.perpendicular_ccw(); if (e.dot(be) < 0) e = -e; be = e; e *= ADVANCE_RATIO; bp+= e; back_alive = CheckAndRegister(bp,road_restrict,bx, by, bc, major); if(back_alive) back_alive = CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp); if(back_alive) { pts.push_back(bp); if(CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, 0.0f)) QueueSeed(bp,!major,road_restrict,seedQ); } } } while (front_alive || back_alive); Point3 c(1,1,0); if(!major)c.y = 0; int k = ThinLine(pts, 10.0 * MTR_TO_NM * NM_TO_DEG_LAT, 500 * MTR_TO_NM * NM_TO_DEG_LAT); // printf("Killed %d points, kept %d points.\n", k, pts.size()); for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i) { // gMeshPoints.push_back(pair<Point2,Point3>(*i,c)); if(i != pts.begin()) { list<Point2>::iterator j(i); --j; // gMeshLines.push_back(pair<Point2,Point3>(*j,c)); // gMeshLines.push_back(pair<Point2,Point3>(*i,c)); // can't do this - makes a point cloud of roads - TOTALLY gross. // if(RollDice(max(inUrbanDensity.value_linear(j->x,j->y),inUrbanDensity.value_linear(i->x,i->y)))) roads.push_back(Segment2(*j,*i)); } } } seedQ.pop_front(); // if((ctr%1000)==0) // printf("Q contains: %d, pts: %d\n", seedQ.size(), gMeshPoints.size()); } } { TIMER(build_real_roads) Pmwx sub; sub.unbounded_face()->data().mTerrainType = terrain_Natural; BulkInsertRoads(roads, sub); BulkZapRoads(inUrbanDensity, sub); DebugAssert(sub.is_valid()); // TopoIntegrateMaps(&ioMap, &sub); // for(Pmwx::Face_iterator sf = sub.faces-begin(); sf != sub.faces_end(); ++sf) // sf->mTerrainType = terrain_Natural; DebugAssert(ioMap.is_valid()); DebugAssert(sub.is_valid()); #if SHOW_GENERATED_ROADS for(Pmwx::Edge_iterator eit = sub.edges_begin(); eit != sub.edges_end(); ++eit) debug_mesh_line(cgal2ben(eit->source()->point()),cgal2ben(eit->target()->point()),1,0,0, 0,1,0); #endif if(!sub.is_empty()) MergeMaps_legacy(ioMap, sub, false, NULL, true, inProg); } /********************************************************************************************************************************** * DEBUG OUTPUT **********************************************************************************************************************************/ #if OPENGL_MAP if(inFace != Face_handle() && ioTensorImage) { Pmwx::Ccb_halfedge_circulator circ = inFace->outer_ccb(); Pmwx::Ccb_halfedge_circulator start = circ; t.bounds = Bbox2(cgal2ben(circ->source()->point())); do { t.bounds += cgal2ben(circ->source()->point()); ++circ; } while (circ != start); TensorDDA(*ioTensorImage,Tensor_Func,&t); outTensorBounds[0] = t.bounds.p1.x(); outTensorBounds[1] = t.bounds.p1.y(); outTensorBounds[2] = t.bounds.p2.x(); outTensorBounds[3] = t.bounds.p2.y(); } #endif #if SHOW_ROAD_RESTRICT gDem[dem_Wizard] = road_restrict; #endif }
30.643162
148
0.593369
rromanchuk
db718f3da616444ed16544aa1dc149a4b7c3f991
3,174
cpp
C++
src/infra/ToValue.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
578
2019-05-04T09:09:42.000Z
2022-03-27T23:02:21.000Z
src/infra/ToValue.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
14
2019-05-11T14:34:56.000Z
2021-02-02T07:06:46.000Z
src/infra/ToValue.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
42
2019-05-11T16:04:19.000Z
2022-01-24T02:21:43.000Z
// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifdef TWO_MODULES module; #include <infra/Cpp20.h> module TWO(infra); #else #include <cstdlib> #include <infra/ToValue.h> #endif namespace two { #ifndef USE_STL template <> void to_value(const string& str, bool& val) { val = atoi(str.c_str()) != 0; } //str == "true" ? true : false; } template <> void to_value(const string& str, char& val) { val = char(atoi(str.c_str())); } template <> void to_value(const string& str, schar& val) { val = schar(atoi(str.c_str())); } template <> void to_value(const string& str, short& val) { val = short(atoi(str.c_str())); } template <> void to_value(const string& str, int& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, long& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, llong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, uchar& val) { val = uchar(atoi(str.c_str())); } template <> void to_value(const string& str, ushort& val) { val = ushort(atoi(str.c_str())); } template <> void to_value(const string& str, uint& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, ulong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, ullong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, float& val) { val = float(atof(str.c_str())); } template <> void to_value(const string& str, double& val) { val = atof(str.c_str()); } //sscanf(str.c_str(), "%lf", &val); } template <> void to_value(const string& str, ldouble& val) { val = atof(str.c_str()); } #else template <> void to_value(const string& str, bool& val) { val = std::stoi(str) != 0; } //str == "true" ? true : false; } template <> void to_value(const string& str, char& val) { val = char(std::stoi(str)); } template <> void to_value(const string& str, schar& val) { val = schar(std::stoi(str)); } template <> void to_value(const string& str, short& val) { val = short(std::stoi(str)); } template <> void to_value(const string& str, int& val) { val = std::stoi(str); } template <> void to_value(const string& str, long& val) { val = std::stoi(str); } template <> void to_value(const string& str, llong& val) { val = std::stoi(str); } template <> void to_value(const string& str, uchar& val) { val = uchar(std::stoi(str)); } template <> void to_value(const string& str, ushort& val) { val = ushort(std::stoi(str)); } template <> void to_value(const string& str, uint& val) { val = std::stoi(str); } template <> void to_value(const string& str, ulong& val) { val = std::stoi(str); } template <> void to_value(const string& str, ullong& val) { val = std::stoi(str); } template <> void to_value(const string& str, float& val) { val = std::stof(str); } template <> void to_value(const string& str, double& val) { val = std::stod(str); } template <> void to_value(const string& str, ldouble& val) { val = std::stod(str); } #endif }
63.48
125
0.660996
murataka
db72e8a58c56991009ed2558b84cd8ff6b326bfc
7,778
hpp
C++
neutrino/math/inc/matrix_functions.hpp
alexiynew/nih_framework
a65335586331daa0ece892f98265bd1d2f8f579f
[ "MIT" ]
1
2017-07-14T04:51:54.000Z
2017-07-14T04:51:54.000Z
neutrino/math/inc/matrix_functions.hpp
alexiynew/nih_framework
a65335586331daa0ece892f98265bd1d2f8f579f
[ "MIT" ]
32
2017-02-02T14:49:41.000Z
2019-06-25T19:38:27.000Z
neutrino/math/inc/matrix_functions.hpp
alexiynew/nih_framework
a65335586331daa0ece892f98265bd1d2f8f579f
[ "MIT" ]
null
null
null
#ifndef FRAMEWORK_MATH_DETAILS #error You should include math/math.hpp instead of matrix_functions.hpp #endif #ifndef FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP #define FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP #include <math/inc/matrix_functions_details.hpp> #include <math/inc/matrix_type.hpp> namespace framework::math { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @addtogroup math_matrix_functions /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name transpose /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the transpose of a Matrix. /// /// @param value Specifies the Matrix of which to take the transpose. /// /// @return The transpose of the Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<R, C, T> transpose(const Matrix<C, R, T>& value) { return matrix_functions_details::transpose(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name component_wise_multiplication /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Perform a component-wise multiplication of two matrices. /// /// @param lhs Specifies the first Matrix multiplicand. /// @param rhs Specifies the second Matrix multiplicand. /// /// @return The component-wise multiplication of two matrices. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> component_wise_multiplication(const Matrix<C, R, T>& lhs, const Matrix<C, R, T>& rhs) { Matrix<C, R, T> temp{lhs}; for (std::size_t i = 0; i < C; ++i) { temp[i] *= rhs[i]; } return temp; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name outer_product /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the outer product of a pair of vectors. /// /// @param lhs Specifies the parameter to be treated as a column vector. /// @param rhs Specifies the parameter to be treated as a row vector. /// /// @return The outer product of a pair of vectors. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> outer_product(const Vector<R, T>& lhs, const Vector<C, T>& rhs) { return matrix_functions_details::outer_product(lhs, rhs); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name determinant /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the determinant of a Matrix. /// /// @param value Specifies the Matrix of which to take the determinant. /// /// @return The determinant of the Matrix. template <std::size_t C, std::size_t R, typename T> inline T determinant(const Matrix<C, R, T>& value) { return matrix_functions_details::determinant(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name inverse /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse of a Matrix. /// /// The values in the returned Matrix are undefined if Matrix is singular or /// poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The inverse of a Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> inverse(const Matrix<C, R, T>& value) { return matrix_functions_details::inverse(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name affine_inverse /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse of a affine Matrix. /// /// The values in the returned Matrix are undefined if Matrix contains not /// affine transformations, or Matrix is singular or /// poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The inverse of a Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> affine_inverse(const Matrix<C, R, T>& value) { return matrix_functions_details::affine_inverse(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name inverse_transpose /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse-transpose of a Matrix. /// /// The values in the returned Matrix are undefined if Matrix is singular /// or poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The Matrix which is equivalent to `transpose(inverse(Matrix))`. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> inverse_transpose(const Matrix<C, R, T>& value) { return matrix_functions_details::inverse_transpose(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace framework::math #endif
44.193182
120
0.349061
alexiynew
db75eea6d83a17d1dffcf99b091a27f2dca24799
41,541
cpp
C++
tests/hardware_ietf-hardware.cpp
CESNET/velia
f0b7075f94014c5506bc43e6905f789c77d834b6
[ "Apache-2.0" ]
6
2021-02-26T13:01:56.000Z
2022-02-22T07:07:24.000Z
tests/hardware_ietf-hardware.cpp
CESNET/velia
f0b7075f94014c5506bc43e6905f789c77d834b6
[ "Apache-2.0" ]
3
2020-11-05T21:20:46.000Z
2021-06-04T18:32:46.000Z
tests/hardware_ietf-hardware.cpp
CESNET/velia
f0b7075f94014c5506bc43e6905f789c77d834b6
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "trompeloeil_doctest.h" #include <fstream> #include <future> #include <iterator> #include "fs-helpers/utils.h" #include "ietf-hardware/FspYhPsu.h" #include "ietf-hardware/IETFHardware.h" #include "ietf-hardware/sysrepo/Sysrepo.h" #include "mock/ietf_hardware.h" #include "pretty_printers.h" #include "test_log_setup.h" #include "test_sysrepo_helpers.h" #include "tests/configure.cmake.h" using namespace std::literals; TEST_CASE("HardwareState") { TEST_INIT_LOGS; static const auto modulePrefix = "/ietf-hardware:hardware"s; trompeloeil::sequence seq1; auto ietfHardware = std::make_shared<velia::ietf_hardware::IETFHardware>(); auto fans = std::make_shared<FakeHWMon>(); auto sysfsTempCpu = std::make_shared<FakeHWMon>(); auto sysfsTempFront = std::make_shared<FakeHWMon>(); auto sysfsTempMII0 = std::make_shared<FakeHWMon>(); auto sysfsTempMII1 = std::make_shared<FakeHWMon>(); auto sysfsVoltageAc = std::make_shared<FakeHWMon>(); auto sysfsVoltageDc = std::make_shared<FakeHWMon>(); auto sysfsPower = std::make_shared<FakeHWMon>(); auto sysfsCurrent = std::make_shared<FakeHWMon>(); auto emmc = std::make_shared<FakeEMMC>(); std::map<std::string, std::string> attributesEMMC; std::map<std::string, int64_t> attributesHWMon; // initialize all mocks attributesEMMC = { // FIXME passing initializer_list to macro is hell {"date"s, "02/2017"s}, {"serial"s, "0x00a8808d"s}, {"name"s, "8GME4R"s}, }; FAKE_EMMC(emmc, attributesEMMC); REQUIRE_CALL(*fans, attribute("fan1_input"s)).RETURN( 253); REQUIRE_CALL(*fans, attribute("fan2_input"s)).RETURN( 0); REQUIRE_CALL(*fans, attribute("fan3_input"s)).RETURN( 1280); REQUIRE_CALL(*fans, attribute("fan4_input"s)).RETURN( 666); REQUIRE_CALL(*sysfsTempFront, attribute("temp1_input")).RETURN(30800); REQUIRE_CALL(*sysfsTempCpu, attribute("temp1_input")).RETURN(41800); REQUIRE_CALL(*sysfsTempMII0, attribute("temp1_input")).RETURN(39000); REQUIRE_CALL(*sysfsTempMII1, attribute("temp1_input")).RETURN(36000); REQUIRE_CALL(*sysfsVoltageAc, attribute("in1_input")).RETURN(220000); REQUIRE_CALL(*sysfsVoltageDc, attribute("in1_input")).RETURN(12000); REQUIRE_CALL(*sysfsPower, attribute("power1_input")).RETURN(14000000); REQUIRE_CALL(*sysfsCurrent, attribute("curr1_input")).RETURN(200); attributesEMMC = {{"life_time"s, "40"s}}; FAKE_EMMC(emmc, attributesEMMC); using velia::ietf_hardware::data_reader::SensorType; using velia::ietf_hardware::data_reader::StaticData; using velia::ietf_hardware::data_reader::Fans; using velia::ietf_hardware::data_reader::SysfsValue; using velia::ietf_hardware::data_reader::EMMC; // register components into hw state ietfHardware->registerDataReader(StaticData("ne", std::nullopt, {{"class", "iana-hardware:chassis"}, {"mfg-name", "CESNET"s}})); ietfHardware->registerDataReader(StaticData("ne:ctrl", "ne", {{"class", "iana-hardware:module"}})); ietfHardware->registerDataReader(Fans("ne:fans", "ne", fans, 4)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-front", "ne:ctrl", sysfsTempFront, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-cpu", "ne:ctrl", sysfsTempCpu, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-internal-0", "ne:ctrl", sysfsTempMII0, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-internal-1", "ne:ctrl", sysfsTempMII1, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::VoltageAC>("ne:ctrl:voltage-in", "ne:ctrl", sysfsVoltageAc, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::VoltageDC>("ne:ctrl:voltage-out", "ne:ctrl", sysfsVoltageDc, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Power>("ne:ctrl:power", "ne:ctrl", sysfsPower, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Current>("ne:ctrl:current", "ne:ctrl", sysfsCurrent, 1)); ietfHardware->registerDataReader(EMMC("ne:ctrl:emmc", "ne:ctrl", emmc)); SECTION("Test HardwareState without sysrepo") { std::map<std::string, std::string> expected = { {"/ietf-hardware:hardware/component[name='ne']/class", "iana-hardware:chassis"}, {"/ietf-hardware:hardware/component[name='ne']/mfg-name", "CESNET"}, {"/ietf-hardware:hardware/component[name='ne:fans']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:fans']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/parent", "ne:fans:fan1"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value", "253"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/parent", "ne:fans:fan2"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/parent", "ne:fans:fan3"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value", "1280"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/parent", "ne:fans:fan4"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value", "666"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:ctrl']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:ctrl']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value", "41800"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value", "30800"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value", "39000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value", "36000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value", "14000000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value", "220000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-type", "volts-AC"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value", "12000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value", "200"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/serial-num", "0x00a8808d"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/mfg-date", "2017-02-01T00:00:00Z"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/model-name", "8GME4R"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/parent", "ne:ctrl:emmc"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value", "40"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-type", "other"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/units-display", "percent"}, }; // exclude last-change node auto result = ietfHardware->process(); result.erase(modulePrefix + "/last-change"); REQUIRE(result == expected); } SECTION("Test IETF Hardware from sysrepo's view") { TEST_SYSREPO_INIT_LOGS; TEST_SYSREPO_INIT; TEST_SYSREPO_INIT_CLIENT; auto ietfHardwareSysrepo = std::make_shared<velia::ietf_hardware::sysrepo::Sysrepo>(srSubs, ietfHardware); SECTION("test last-change") { // at least check that there is some timestamp REQUIRE(dataFromSysrepo(client, modulePrefix, SR_DS_OPERATIONAL).count("/last-change") > 0); } SECTION("test components") { std::map<std::string, std::string> expected = { {"[name='ne']/name", "ne"}, {"[name='ne']/class", "iana-hardware:chassis"}, {"[name='ne']/mfg-name", "CESNET"}, {"[name='ne']/sensor-data", ""}, {"[name='ne:fans']/class", "iana-hardware:module"}, {"[name='ne:fans']/name", "ne:fans"}, {"[name='ne:fans']/parent", "ne"}, {"[name='ne:fans']/sensor-data", ""}, {"[name='ne:fans:fan1']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan1']/name", "ne:fans:fan1"}, {"[name='ne:fans:fan1']/parent", "ne:fans"}, {"[name='ne:fans:fan1']/sensor-data", ""}, {"[name='ne:fans:fan1:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan1:rpm']/name", "ne:fans:fan1:rpm"}, {"[name='ne:fans:fan1:rpm']/parent", "ne:fans:fan1"}, {"[name='ne:fans:fan1:rpm']/sensor-data", ""}, {"[name='ne:fans:fan1:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value", "253"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan2']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan2']/name", "ne:fans:fan2"}, {"[name='ne:fans:fan2']/parent", "ne:fans"}, {"[name='ne:fans:fan2']/sensor-data", ""}, {"[name='ne:fans:fan2:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan2:rpm']/name", "ne:fans:fan2:rpm"}, {"[name='ne:fans:fan2:rpm']/parent", "ne:fans:fan2"}, {"[name='ne:fans:fan2:rpm']/sensor-data", ""}, {"[name='ne:fans:fan2:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value", "0"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan3']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan3']/name", "ne:fans:fan3"}, {"[name='ne:fans:fan3']/parent", "ne:fans"}, {"[name='ne:fans:fan3']/sensor-data", ""}, {"[name='ne:fans:fan3:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan3:rpm']/name", "ne:fans:fan3:rpm"}, {"[name='ne:fans:fan3:rpm']/parent", "ne:fans:fan3"}, {"[name='ne:fans:fan3:rpm']/sensor-data", ""}, {"[name='ne:fans:fan3:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value", "1280"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan4']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan4']/name", "ne:fans:fan4"}, {"[name='ne:fans:fan4']/parent", "ne:fans"}, {"[name='ne:fans:fan4']/sensor-data", ""}, {"[name='ne:fans:fan4:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan4:rpm']/name", "ne:fans:fan4:rpm"}, {"[name='ne:fans:fan4:rpm']/parent", "ne:fans:fan4"}, {"[name='ne:fans:fan4:rpm']/sensor-data", ""}, {"[name='ne:fans:fan4:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value", "666"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:ctrl']/name", "ne:ctrl"}, {"[name='ne:ctrl']/parent", "ne"}, {"[name='ne:ctrl']/class", "iana-hardware:module"}, {"[name='ne:ctrl']/sensor-data", ""}, {"[name='ne:ctrl:temperature-cpu']/name", "ne:ctrl:temperature-cpu"}, {"[name='ne:ctrl:temperature-cpu']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-cpu']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data", ""}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value", "41800"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-front']/name", "ne:ctrl:temperature-front"}, {"[name='ne:ctrl:temperature-front']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-front']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-front']/sensor-data", ""}, {"[name='ne:ctrl:temperature-front']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value", "30800"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-internal-0']/name", "ne:ctrl:temperature-internal-0"}, {"[name='ne:ctrl:temperature-internal-0']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-internal-0']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data", ""}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value", "39000"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-internal-1']/name", "ne:ctrl:temperature-internal-1"}, {"[name='ne:ctrl:temperature-internal-1']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-internal-1']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data", ""}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value", "36000"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:power']/name", "ne:ctrl:power"}, {"[name='ne:ctrl:power']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:power']/parent", "ne:ctrl"}, {"[name='ne:ctrl:power']/sensor-data", ""}, {"[name='ne:ctrl:power']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:power']/sensor-data/value", "14000000"}, {"[name='ne:ctrl:power']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:power']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:power']/sensor-data/value-type", "watts"}, {"[name='ne:ctrl:voltage-in']/name", "ne:ctrl:voltage-in"}, {"[name='ne:ctrl:voltage-in']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:voltage-in']/parent", "ne:ctrl"}, {"[name='ne:ctrl:voltage-in']/sensor-data", ""}, {"[name='ne:ctrl:voltage-in']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value", "220000"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-type", "volts-AC"}, {"[name='ne:ctrl:voltage-out']/name", "ne:ctrl:voltage-out"}, {"[name='ne:ctrl:voltage-out']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:voltage-out']/parent", "ne:ctrl"}, {"[name='ne:ctrl:voltage-out']/sensor-data", ""}, {"[name='ne:ctrl:voltage-out']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value", "12000"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-type", "volts-DC"}, {"[name='ne:ctrl:current']/name", "ne:ctrl:current"}, {"[name='ne:ctrl:current']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:current']/parent", "ne:ctrl"}, {"[name='ne:ctrl:current']/sensor-data", ""}, {"[name='ne:ctrl:current']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:current']/sensor-data/value", "200"}, {"[name='ne:ctrl:current']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:current']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:current']/sensor-data/value-type", "amperes"}, {"[name='ne:ctrl:emmc']/name", "ne:ctrl:emmc"}, {"[name='ne:ctrl:emmc']/parent", "ne:ctrl"}, {"[name='ne:ctrl:emmc']/class", "iana-hardware:module"}, {"[name='ne:ctrl:emmc']/serial-num", "0x00a8808d"}, {"[name='ne:ctrl:emmc']/mfg-date", "2017-02-01T00:00:00Z"}, {"[name='ne:ctrl:emmc']/model-name", "8GME4R"}, {"[name='ne:ctrl:emmc']/sensor-data", ""}, {"[name='ne:ctrl:emmc:lifetime']/name", "ne:ctrl:emmc:lifetime"}, {"[name='ne:ctrl:emmc:lifetime']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:emmc:lifetime']/parent", "ne:ctrl:emmc"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data", ""}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value", "40"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-scale", "units"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-type", "other"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/units-display", "percent"}, }; REQUIRE(dataFromSysrepo(client, modulePrefix + "/component", SR_DS_OPERATIONAL) == expected); } SECTION("test leafnode query") { const auto xpath = modulePrefix + "/component[name='ne:ctrl:emmc:lifetime']/class"; client->session_switch_ds(SR_DS_OPERATIONAL); auto val = client->get_item(xpath.c_str()); client->session_switch_ds(SR_DS_RUNNING); REQUIRE(!!val); REQUIRE(val->data()->get_identityref() == "iana-hardware:sensor"s); } } } class FakeI2C : public velia::ietf_hardware::TransientI2C { public: FakeI2C(const std::string& fakeHwmonRoot) : TransientI2C({}, {}, {}) , m_fakeHwmonRoot(fakeHwmonRoot) { } MAKE_CONST_MOCK0(isPresent, bool(), override); MAKE_CONST_MOCK0(bind_mock, void()); MAKE_CONST_MOCK0(unbind_mock, void()); void removeHwmonFile(const std::string& name) const { std::filesystem::remove(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo)) / name); } void bind() const override { bind_mock(); removeDirectoryTreeIfExists(m_fakeHwmonRoot); std::filesystem::create_directory(m_fakeHwmonRoot); std::filesystem::create_directory(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo))); for (const auto& filename : {"name", "temp1_input", "temp2_input", "curr1_input", "curr2_input", "curr3_input", "in1_input", "in2_input", "in3_input", "power1_input", "power2_input", "fan1_input"} ) { std::ofstream ofs(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo)) / filename); // I don't really care about the values here, I just need the HWMon class to think that the files exist. ofs << 0 << "\n"; } } void unbind() const override { unbind_mock(); removeDirectoryTreeIfExists(m_fakeHwmonRoot); m_hwmonNo++; } private: std::filesystem::path m_fakeHwmonRoot; mutable std::atomic<int> m_hwmonNo = 1; }; TEST_CASE("FspYhPsu") { TEST_INIT_LOGS; std::atomic<int> counter = 0; const auto fakeHwmonRoot = CMAKE_CURRENT_BINARY_DIR + "/tests/psu"s; removeDirectoryTreeIfExists(fakeHwmonRoot); auto fakeI2c = std::make_shared<FakeI2C>(fakeHwmonRoot); trompeloeil::sequence seq1; std::shared_ptr<velia::ietf_hardware::FspYhPsu> psu; std::vector<std::unique_ptr<trompeloeil::expectation>> expectations; auto i2cPresence = [&counter] { switch (counter) { case 0: case 2: case 4: return false; case 1: case 3: return true; } REQUIRE(false); __builtin_unreachable(); }; ALLOW_CALL(*fakeI2c, isPresent()).LR_RETURN(i2cPresence()); REQUIRE_CALL(*fakeI2c, bind_mock()).LR_WITH(counter == 1).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, unbind_mock()).LR_WITH(counter == 2).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, bind_mock()).LR_WITH(counter == 3).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, unbind_mock()).LR_WITH(counter == 4).IN_SEQUENCE(seq1); psu = std::make_shared<velia::ietf_hardware::FspYhPsu>(fakeHwmonRoot, "psu", fakeI2c); for (auto i : {0, 1, 2, 3, 4}) { std::this_thread::sleep_for(std::chrono::seconds(4)); velia::ietf_hardware::DataTree expected; switch (i) { case 0: break; case 1: expected = { {"/ietf-hardware:hardware/component[name='ne:psu']/class", "iana-hardware:power-supply"}, {"/ietf-hardware:hardware/component[name='ne:psu']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1']/parent", "ne:psu:fan"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/parent", "ne:psu:fan:fan1"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-type", "volts-AC"}, }; break; case 2: break; case 3: // Here I simulate read failure by a file from the hwmon directory. This happens when the user wants data from // a PSU that's no longer there and the watcher thread didn't unbind it yet. fakeI2c->removeHwmonFile("temp1_input"); break; case 4: break; } REQUIRE(psu->readValues() == expected); counter++; } waitForCompletionAndBitMore(seq1); }
69.235
137
0.607255
CESNET
db7846efea4d150c6002f9cc48ba392637725477
591
hpp
C++
include/Engine.hpp
DavidCarlyn/simple_cpp_gui
ba7e58bb231734b38ebb329f9d4142442ce81c0b
[ "MIT" ]
null
null
null
include/Engine.hpp
DavidCarlyn/simple_cpp_gui
ba7e58bb231734b38ebb329f9d4142442ce81c0b
[ "MIT" ]
null
null
null
include/Engine.hpp
DavidCarlyn/simple_cpp_gui
ba7e58bb231734b38ebb329f9d4142442ce81c0b
[ "MIT" ]
null
null
null
#pragma once #include <SDL.h> #include <string> class Engine { public: Engine(); SDL_Window* createWindow(const int width, const int height, std::string name = "WINDOW NAME"); SDL_Surface* createSurface(SDL_Window* window); SDL_Surface* createImageSurface(SDL_Surface* surface, std::string path); SDL_Renderer* createRenderer(SDL_Window* window); void freeSurface(SDL_Surface* surface); void destroyWindow(SDL_Window* window); void destroyRenderer(SDL_Renderer* renderer); void close(); private: };
28.142857
102
0.663283
DavidCarlyn
db789037bfac80d89b06b52ad44a23ce54bf584f
2,312
cpp
C++
TerraForge3D/src/Generators/ClearMeshGenerator.cpp
MalikuMane/TerraForge3D
aa0c532cbafe42b7789bb610bae7495211196cd5
[ "MIT" ]
434
2021-11-03T06:03:07.000Z
2022-03-31T22:52:19.000Z
TerraForge3D/src/Generators/ClearMeshGenerator.cpp
MalikuMane/TerraForge3D
aa0c532cbafe42b7789bb610bae7495211196cd5
[ "MIT" ]
14
2021-11-03T12:11:30.000Z
2022-03-31T16:52:24.000Z
TerraForge3D/src/Generators/ClearMeshGenerator.cpp
MalikuMane/TerraForge3D
aa0c532cbafe42b7789bb610bae7495211196cd5
[ "MIT" ]
45
2021-11-04T07:34:21.000Z
2022-03-31T07:06:05.000Z
#include "Generators/ClearMeshGenerator.h" #include "Utils/Utils.h" #include "Data/ApplicationState.h" #include "Profiler.h" ClearMeshGenerator::ClearMeshGenerator(ApplicationState *as, ComputeKernel *kernels) { bool tmp = false; appState = as; } void ClearMeshGenerator::Generate(ComputeKernel *kernels) { START_PROFILER(); if(useGPU) { if (appState->mode == ApplicationMode::TERRAIN) { kernels->SetKernelArg("clear_mesh_terrain", 0, "mesh"); kernels->ExecuteKernel("clear_mesh_terrain", cl::NDRange(1), cl::NDRange(appState->models.coreTerrain->mesh->vertexCount)); } else if (appState->mode == ApplicationMode::CUSTOM_BASE) { kernels->SetKernelArg("clear_mesh_custom_base", 0, "mesh"); kernels->SetKernelArg("clear_mesh_custom_base", 1, "mesh_copy"); kernels->ExecuteKernel("clear_mesh_custom_base", cl::NDRange(1), cl::NDRange(appState->models.customBase->mesh->vertexCount)); } } else { if (appState->mode == ApplicationMode::TERRAIN) { Mesh *mes = appState->models.coreTerrain->mesh; int vc = mes->vertexCount; for(int i=0; i<vc; i++) { mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = mes->vert[i].position.y = 0.0f; mes->vert[i].extras1.x = 0.0f; mes->vert[i].extras1.y = 0.0f; mes->vert[i].extras1.z = 0.0f; } } else if (appState->mode == ApplicationMode::CUSTOM_BASE) { Mesh *mes = appState->models.customBase->mesh; Mesh *mesC = appState->models.customBaseCopy->mesh; int vc = mesC->vertexCount; for(int i=0; i<vc; i++) { mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = 0.0f; mes->vert[i].position = mesC->vert[i].position; mes->vert[i].extras1.x = 0.0f; mes->vert[i].extras1.y = 0.0f; mes->vert[i].extras1.z = 0.0f; } } } END_PROFILER(time); } nlohmann::json ClearMeshGenerator::Save() { nlohmann::json data; data["uiActive"] = uiActive; data["useGPU"] = useGPU; return data; } void ClearMeshGenerator::Load(nlohmann::json data) { uiActive = data["uiActive"]; useGPU = data["useGPU"]; } void ClearMeshGenerator::ShowSettings() { if(ImGui::Checkbox("Use GPU##CMG", &useGPU)) { } ImGui::Checkbox("Use GPU For Normals(Flat Shading)##CMG", &appState->states.useGPUForNormals); ImGui::Text("Time : %lf ms", time); }
25.406593
129
0.66955
MalikuMane
db7c6c9a207927d5cfeb3aa6a0fcff3ad8344de7
656
hpp
C++
src/hardware/audio/components/length_component.hpp
geaz/emu-gameboy
da8a3e6898a0075dcb4371eb772e31695300ae54
[ "MIT" ]
47
2019-10-12T14:23:47.000Z
2022-03-22T03:31:43.000Z
src/hardware/audio/components/length_component.hpp
geaz/emu-gameboy
da8a3e6898a0075dcb4371eb772e31695300ae54
[ "MIT" ]
null
null
null
src/hardware/audio/components/length_component.hpp
geaz/emu-gameboy
da8a3e6898a0075dcb4371eb772e31695300ae54
[ "MIT" ]
2
2021-09-20T20:47:21.000Z
2021-10-12T12:10:46.000Z
#pragma once #ifndef LENGTHCOMPONENT_H #define LENGTHCOMPONENT_H #include <cstdint> namespace GGB::Hardware::Audio { class LengthComponent { public: void setLength(uint16_t value, bool stopAfterLength) { length = length == 0 ? value : length; lengthStop = stopAfterLength; } bool tick() { length -= length != 0 ? 1 : 0; return !lengthStop || (length != 0 && lengthStop); } private: bool lengthStop = false; uint16_t length = 0; }; } #endif // LENGTHCOMPONENT_H
21.866667
66
0.509146
geaz
db7d4727215550b68a5cf3bf5f4bd8e2fc78e565
913
cpp
C++
Module/HelloWorld_Scratch/kmain.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
1
2021-05-09T01:24:05.000Z
2021-05-09T01:24:05.000Z
Module/HelloWorld_Scratch/kmain.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
null
null
null
Module/HelloWorld_Scratch/kmain.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
null
null
null
#include "kmain.h" _declspec(naked) void multiboot_entry(void) { __asm { align 4 multiboot_header: //멀티부트 헤더 사이즈 : 0X20 dd(MULTIBOOT_HEADER_MAGIC); magic number dd(MULTIBOOT_HEADER_FLAGS); flags dd(CHECKSUM); checksum dd(HEADER_ADRESS); //헤더 주소 KERNEL_LOAD_ADDRESS+ALIGN(0x100064) dd(KERNEL_LOAD_ADDRESS); //커널이 로드된 가상주소 공간 dd(00); //사용되지 않음 dd(00); //사용되지 않음 dd(HEADER_ADRESS + 0x20); //커널 시작 주소 : 멀티부트 헤더 주소 + 0x20, kernel_entry kernel_entry : mov esp, KERNEL_STACK; //스택 설정 push 0; //플래그 레지스터 초기화 popf //GRUB에 의해 담겨 있는 정보값을 스택에 푸쉬한다. push ebx; //멀티부트 구조체 포인터 push eax; //매직 넘버 //위의 두 파라메터와 함께 kmain 함수를 호출한다. call kmain; //C++ 메인 함수 호출 //루프를 돈다. kmain이 리턴되지 않으면 아래 코드는 수행되지 않는다. halt: jmp halt; } } void kmain(unsigned long magic, unsigned long addr) { SkyConsole::Initialize(); SkyConsole::Print("Hello World!!\n"); for (;;); }
20.288889
72
0.654984
arkiny
db7e905e90ad38d210c95b593c49ddc191b9176b
1,130
hpp
C++
src/app/Page.hpp
hilnius/cappella
555a920330e615793b238d72255274ca7c558467
[ "MIT" ]
null
null
null
src/app/Page.hpp
hilnius/cappella
555a920330e615793b238d72255274ca7c558467
[ "MIT" ]
null
null
null
src/app/Page.hpp
hilnius/cappella
555a920330e615793b238d72255274ca7c558467
[ "MIT" ]
null
null
null
#ifndef PAGE_H_INCLUDED #define PAGE_H_INCLUDED #include "common/Types.hpp" #include "core/SQLEntity.hpp" #include <iostream> class JSONSerializable; class Page: public SQLEntity, public JSONSerializable { public: Page(); virtual ~Page(); void setId(INTEGER<12> id) { p_id = id; } void setName(STRING<255> name) { p_name = name; } void setUserId(INTEGER<12> userId) { p_userId = userId; } void setPageViews(INTEGER<12> pageViews) { p_pageViews = pageViews; } INTEGER<12> getId() { return p_id; } STRING<255> getName() { return p_name; } INTEGER<12> getUserId() { return p_userId; } INTEGER<12> getPageViews() { return p_pageViews; } private: INTEGER<12> p_id; STRING<255> p_name; INTEGER<12> p_userId; INTEGER<12> p_pageViews; protected: virtual std::map<std::string, const JSONSerializable*> getSerializedData() const { std::map<std::string, const JSONSerializable*> result; result["id"] = &p_id; result["name"] = &p_name; result["pageViews"] = &p_pageViews; return result; } }; #endif // PAGE_H_INCLUDED
24.565217
84
0.655752
hilnius
db7eb204d7d422870d51397c17162f4b698f1606
1,652
cpp
C++
Leetcode/Practice/1568.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
4
2019-06-04T11:03:38.000Z
2020-06-19T23:37:32.000Z
Leetcode/Practice/1568.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
Leetcode/Practice/1568.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
class Solution { public: void dfs(vector<vector<int>>& grid, int i, int j) { int n = grid.size(), m = grid[0].size(); if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0) return ; grid[i][j] = 0; int d1[] = {0, 1, 0, -1}, d2[] = {1, 0, -1, 0}; for(int k = 0; k < 4; k++) dfs(grid, i + d1[k], j + d2[k]); return ; } bool isConn(vector<vector<int>> grid) { if(grid.size() == 0) return false; int n = grid.size(), m = grid[0].size(); int flag = false; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { if(flag == false) { dfs(grid, i, j); flag = true; } else return false; } } } if(flag == false) return false; return true; } int minDays(vector<vector<int>>& grid) { if(grid.size() == 0) return true; int n = grid.size(), m = grid[0].size(); if(isConn(grid) == false) return 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { grid[i][j] = 0; if(isConn(grid) == false) return 1; grid[i][j] = 1; } } } return 2; } };
27.533333
65
0.311743
coderanant
db80bb3c19ca4a344a2598d805c05ea1a3a017a9
1,418
cpp
C++
BOJ/18000~18999/18200~18299/18233.cpp
shinkeonkim/today-ps
f3e5e38c5215f19579bb0422f303a9c18c626afa
[ "Apache-2.0" ]
2
2020-01-29T06:54:41.000Z
2021-11-07T13:23:27.000Z
BOJ/18000~18999/18200~18299/18233.cpp
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
BOJ/18000~18999/18200~18299/18233.cpp
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int N,P,E; int X[22]; int Y[22]; int check[22]; int answer[22]; bool isAnswer = false; void result() { if(isAnswer) return; int cnt = 0,Sx = 0,Sy = 0; for(int x = 0; x<N; x++) { if(check[x] == 1) { cnt++; Sx +=X[x]; Sy +=Y[x]; } } if(cnt != P) return; if(Sx <= E && E <=Sy) { isAnswer = true; // for(int x = 0; x<N; x++) { // cout << check[x] << " "; // } int left = E; for(int x = 0; x<N; x++) { if(check[x] == 1) { answer[x] +=X[x]; left-=X[x]; } } for(int x = 0; x<N; x++) { if(check[x] == 1 && left>0) { int K = min(left,Y[x]-answer[x]); answer[x] += K; left -= K; } } for(int x = 0; x<N; x++) { cout << answer[x] << " "; } } } void DFS(int current) { if(current == N) { for(int t = 0; t<2; t++) { check[current] = t; result(); } return ; } for(int t = 0; t<2; t++) { check[current] = t; DFS(current+1); } } int main() { cin >> N >> P >> E; for(int i = 0; i < N; i++) { cin >> X[i] >> Y[i]; } DFS(0); if(!isAnswer) { cout<<-1; } }
18.415584
49
0.339915
shinkeonkim
db81c4cf62e3b2a56c029cfa172ed228c68c01f5
2,321
cpp
C++
Assignment 11/Booking.cpp
tomy0000000/YZU-Computer-Programming-II
ec3254bc545581fa91c1efd957cbcef1f76cae21
[ "MIT" ]
1
2020-09-20T12:29:01.000Z
2020-09-20T12:29:01.000Z
Assignment 11/Booking.cpp
tomy0000000/YZU-Computer-Programming-II
ec3254bc545581fa91c1efd957cbcef1f76cae21
[ "MIT" ]
null
null
null
Assignment 11/Booking.cpp
tomy0000000/YZU-Computer-Programming-II
ec3254bc545581fa91c1efd957cbcef1f76cae21
[ "MIT" ]
null
null
null
// // Booking.cpp // Hw 11 // Object Oriented Vieshow Cinemas Taipei QSquare system // // Created by Tomy Hsieh on 2018/6/3. // Copyright © 2018年 Tomy Hsieh. All rights reserved. // #include "Booking.h" #include "MovieDatabase.h" #include <iostream> using std::cout; using std::endl; Booking::Booking() {} string Booking::getEmail() { return string(email); } int Booking::getMovieCode() { return movieCode; } int Booking::getDateCode() { return dateCode; } int Booking::getSessionTimeCode() { return sessionTimeCode; } int Booking::getNumTickets(int ticketType) { return numTickets[ticketType]; } string Booking::getSeletedSeat(int number) { return seletedSeats[number]; } void Booking::setEmail(string theEmail) { unsigned long length = theEmail.size(); length = (length < 40 ? length : 39); for (int i = 0; i < length; i++) { email[i] = theEmail[i]; } email[length] = '\0'; } void Booking::setMovieCode(int theMovieCode) { movieCode = (theMovieCode > 0 ? theMovieCode : 0); } void Booking::setDateCode(int theDateCode) { dateCode = (theDateCode > 0 ? theDateCode : 0); } void Booking::setSessionTimeCode(int theSessionTimeCode) { sessionTimeCode = (theSessionTimeCode > 0 ? theSessionTimeCode : 0); } void Booking::setNumTickets(int theNumTickets[]) { for (int i = 0; i < 4; i++) { numTickets[i] = (theNumTickets[i] > 0 ? theNumTickets[i] : 0); } } void Booking::setSeletedSeats(string theSeletedSeats[], int numSeats) { for (int i = 0; i < numSeats; i++) { seletedSeats[i][0] = theSeletedSeats[i][0]; seletedSeats[i][1] = theSeletedSeats[i][1]; seletedSeats[i][2] = '\0'; } cout << endl; } void Booking::displayBooking(MovieDatabase &movieDatabase) { cout << "\t\t\t\tNo. of Tickets\t\tPrice\t\tSubtotal" << endl; int Num = 0, Price = 0, Sub = 0, Total = 0; char ticketType[4][15] = {"Adult\t\t\t", "Concession\t\t", "Disability\t\t", "Elderly\t\t\t"}; for (int i = 0; i < 4; i++) { if (numTickets[i] != 0) { Num = numTickets[i]; Price = movieDatabase.getMovie(movieCode).getPrice(i); Sub = Num * Price; Total += Sub; cout << ticketType[i] << Num << "\t\t\t\t\t" << Price << "\t\t\t" << Sub << endl; } } cout << endl << "Total Amount For Tickets: " << Total << endl; }
30.142857
78
0.63464
tomy0000000
db83eb4b7174151e3f6261ece34cce9b304a7c6c
6,385
cpp
C++
DataStructures/src/streams/DS_Stream.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
DataStructures/src/streams/DS_Stream.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
DataStructures/src/streams/DS_Stream.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
#include "CommonTypeDefines.h" #include "streams/DS_FileStream.h" #include "fileUtils/_fileExists.h" #include <algorithm> using std::min; namespace DataStructures { //------------------------------------------------------------------- Stream ------------------------------------------------------------------------ #if __WORDSIZE == 64 template <> size_t Stream::Write(const unsigned int &buffer) { if (mForce32bitCompatable) { __u32 val = buffer; return this->Write(&val, sizeof(__u32)); } else return this->Write(&buffer, sizeof(unsigned int)); } template <> size_t Stream::Write(const int &buffer) { if (mForce32bitCompatable) { __s32 val = buffer; return this->Write(&val, sizeof(__s32)); } else return this->Write(&buffer, sizeof(int)); } template <> size_t Stream::Write(const unsigned long &buffer) { if (mForce32bitCompatable) { __u32 val = buffer; return this->Write(&val, sizeof(__u32)); } else return this->Write(&buffer, sizeof(unsigned long)); } template <> size_t Stream::Write(const long &buffer) { if (mForce32bitCompatable) { __s32 val = buffer; return this->Write(&val, sizeof(__s32)); } else return this->Write(&buffer, sizeof(long)); } template <> bool Stream::Read(unsigned int &dst) { if (mForce32bitCompatable) { __u32 t; bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(unsigned int)) == sizeof(unsigned int); } template <> bool Stream::Read(int &dst) { if (mForce32bitCompatable) { __s32 t; bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(int)) == sizeof(int); } template <> bool Stream::Read(unsigned long &dst) { if (mForce32bitCompatable) { __u32 t; bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(unsigned long)) == sizeof(unsigned long); } template <> bool Stream::Read(long &dst) { if (mForce32bitCompatable) { __s32 t; bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(long)) == sizeof(long); } #endif size_t Stream::WriteString(const char *buffer, size_t maxsize) { if (!CanWrite()) return 0; __u16 size = min(strlen(buffer), maxsize + sizeof(__u16)); size_t actSize = this->Write(&size, sizeof(size)); actSize += this->Write(buffer, size); return actSize; } size_t Stream::ReadString(char *dst, size_t maxsize) { if (Eof() || !dst || !CanRead()) return 0; __u16 size; size_t readIn = this->Read(&size, sizeof(size)); readIn += this->Read(dst, min((size_t)size, maxsize)); dst[size] = 0; return readIn; } size_t Stream::CopyFrom(Stream *stream, size_t count) { const size_t _max_buffer_size = 0xf0000; size_t size = count; if (count == 0) { stream->Seek(0, SEEK_SET); size = stream->Length(); } size_t result = size; size_t bufferSize; if (size > _max_buffer_size) bufferSize = _max_buffer_size; else bufferSize = size; char *buffer = (char *)malloc(bufferSize); size_t n; while (size != 0) { if (size > bufferSize) n = bufferSize; else n = size; stream->Read(buffer, n); Write(buffer, n); size -= n; } free(buffer); return result; } bool Stream::SaveToStream(Stream *stream) { if (!stream) return false; __s64 oldPos = Position(); __s64 oldPos1 = stream->Position(); bool res = stream->CopyFrom(this, 0) == Length(); Seek(oldPos, SEEK_SET); stream->Seek(oldPos1, SEEK_SET); return res; } bool Stream::LoadFromStream(Stream *stream) { if (!stream) return false; __s64 oldPos = Position(); __s64 oldPos1 = stream->Position(); size_t size = stream->Length(); SetLength(size); Seek(0, SEEK_SET); bool res = CopyFrom(stream, 0) == size; Seek(oldPos, SEEK_SET); stream->Seek(oldPos1, SEEK_SET); return res; } bool Stream::SaveToFile(const char *fileName) { FileStream *stream = new FileStream(fileName, "wb+"); bool result = SaveToStream(stream); stream->Close(); delete stream; return result; } bool Stream::LoadFromFile(const char *fileName) { if (!_fileExists(fileName)) return false; FileStream *stream = new FileStream(fileName, "rb"); bool result = LoadFromStream(stream); stream->Close(); delete stream; return result; } __s64 Stream::Length() { __s64 oldPos = Seek(0, SEEK_CUR); __s64 length = Seek(0, SEEK_END); Seek(oldPos, SEEK_SET); return length; } __s64 Stream::Position() { return Seek(0, SEEK_CUR); } char *Stream::ReadLine(char *str, int num) { if (num <= 0) return NULL; char c = 0; size_t maxCharsToRead = num - 1; for (size_t i = 0; i < maxCharsToRead; ++i) { size_t result = Read(&c, 1); if (result != 1) { str[i] = '\0'; break; } if (c == '\n') { str[i] = c; str[i + 1] = '\0'; break; } else if(c == '\r') { str[i] = c; // next may be '\n' size_t pos = Position(); char nextChar = 0; if (Read(&nextChar, 1) != 1) { // no more characters str[i + 1] = '\0'; break; } if (nextChar == '\n') { if (i == maxCharsToRead - 1) { str[i + 1] = '\0'; break; } else { str[i + 1] = nextChar; str[i + 2] = '\0'; break; } } else { Seek(pos, SEEK_SET); str[i + 1] = '\0'; break; } } str[i] = c; } return str; // what if first read failed? } bool Stream::Eof() { return Position() >= Length(); } bool Stream::Rewind() { if (!CanSeek()) return 0; else return Seek(0, SEEK_SET) == 0; } std::string Stream::GetAsString() { char *buffer; __s64 fileLen = Length(); __s64 oldPosition = Position(); buffer = (char *)malloc(fileLen + 1); Seek(0, SEEK_SET); Read(buffer, fileLen); Seek(oldPosition, SEEK_SET); buffer[fileLen] = 0; std::string result(buffer); free(buffer); return result; } __u32 Stream::GetMemoryCost() { //this value is not very accurate because of class HexString's cache using return static_cast<__u32>(sizeof(*this) + strlen(mFileName)); } }
19.829193
150
0.595771
Kay01010101
db847d9c5e85f99ba268367fa06d0defaff85ee5
6,733
cpp
C++
cpp/src/Time.cpp
311labs/SRL
c3f0069270ada3784f2a81d9ec9e390e31e53a59
[ "MIT" ]
2
2018-12-21T01:55:23.000Z
2021-11-29T01:30:37.000Z
cpp/src/Time.cpp
311labs/SRL
c3f0069270ada3784f2a81d9ec9e390e31e53a59
[ "MIT" ]
null
null
null
cpp/src/Time.cpp
311labs/SRL
c3f0069270ada3784f2a81d9ec9e390e31e53a59
[ "MIT" ]
null
null
null
/********************************************************************************* * Copyright (C) 1999,2004 by srl, Inc. All Rights Reserved. * ********************************************************************************* * Authors: Ian C. Starnes, Dr. J. Shane Frasier, Shaun Grant ********************************************************************************* * This library 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. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * ********************************************************************************* * Last $Author: ians $ $Revision: 248 $ * Last Modified $Date: 2006-03-08 22:50:35 -0500 (Wed, 08 Mar 2006) $ *********************************************************************************/ #include "srl/Time.h" using namespace SRL; // Basic Time Logic Time::Time(bool local_time, bool empty) { if (!empty) update(local_time); } Time::Time(TimeValue &tval) { _update(tval.tv_sec, tval.tv_usec, tval.tv_zone); } Time::Time(float64 sec) : _time(sec) { } Time::Time(uint8 hour, uint8 minute, float32 second, uint8 tz) { _update(hour, minute, second, tz); } Time::Time(time_t ts) { _update(static_cast<int32>(ts), 0, 0); } Time::Time(tm *dt) { _time = dt->tm_hour*3600.0f + dt->tm_min*60.0f + dt->tm_sec; //_tz = dt->tm_tz; } // Time::Time(String &str_time) // { // // TODO: Add String Construtor support // } Time::Time(const Time &time) { *this = time; } uint8 Time::hour() const { return (uint8)((uint32)(_time / 3600))%24; } uint8 Time::minute() const { return (uint8)((int32)(_time / 60)%60); } float32 Time::second() const { register uint32 itime = (uint32)_time; float32 ms = _time - itime; return ((float32)(itime % 60))+ms; } void Time::addToHour(const int32 &hours) { _time += hours * 3600; } void Time::addToMinute(const int32 &minutes) { _time += minutes * 60; } void Time::update(bool local_time) { TimeValue tv; System::GetCurrentTime(tv); if (local_time) { #ifdef linux const time_t t = tv.tv_sec; tm *lt = localtime(&t); tv.tv_dst = lt->tm_isdst; #endif tv.tv_sec -= (tv.tv_zone*3600) - (tv.tv_dst ? 3600 : 0); } _update(tv.tv_sec, tv.tv_usec, tv.tv_zone); } void Time::update(TimeValue &tv) { _update(tv.tv_sec, tv.tv_usec, tv.tv_zone); } void Time::_update(int32 ts, uint32 micro_seconds, uint8 tz) { if (ts > 86400) { _time = ts % 86400; //_time = ts-((int32)(ts / 86400.0f)*(86400.0f)); } else { _time = (float64)ts; } _time += ((float64)micro_seconds/1000000.0); _tz = tz; } void Time::_update(uint8 hour, uint8 minute, float32 second, uint8 tz) { _time = hour*3600.0f + minute*60.0f + second; _tz = tz; } bool Time::isValid() const { if ((_time > 0) && (_time < 86400)) return true; return false; } // String Time::formatString(const char *str_format) const // { // char tmp[256]; // //tm dt; // //toTM(&dt); // //strftime(tmp, 255, str_format, dt); // return tmp; // } String Time::asString() const { return String::Format("%02d:%02d:%2.4f", hour(), minute(), second()); } time_t Time::toUnix() const { return (time_t)_time; } void Time::toTM(tm *dt) const { //memset (dt, 0x0, sizeof (struct tm)); dt->tm_hour = hour(); dt->tm_min = minute(); dt->tm_sec = (int32)second(); } int32 Time::rescale() { if ((_time > SECONDS_IN_DAY)||(_time < 0)) { // calculate how many days to change int32 new_days = (int32)(_time / SECONDS_IN_DAY); _time = _time - ((float32)(new_days * SECONDS_IN_DAY)); return new_days; } return 0; } Time& Time::operator=(const Time &d) { _time = d._time; return *this; } Time& Time::operator++() { ++_time; return *this; } Time& Time::operator--() { --_time; return *this; } Time& Time::operator+=(const Time& t) { _time += t.getTime(); return *this; } Time& Time::operator-=(const Time& t) { _time -= t.getTime(); return *this; } Time& Time::operator+=(const int32 seconds) { _time += seconds; return *this; } Time& Time::operator-=(const int32 seconds) { _time -= seconds; return *this; } Time SRL::operator+(const Time& t1, const Time& t2) { return Time(t1.getTime()+t2.getTime()); } Time SRL::operator+(const Time& t1, const int32& seconds) { return Time(t1.getTime()+seconds); } Time SRL::operator+(const int32& seconds, const Time& t1) { return Time(seconds+t1.getTime()); } Time SRL::operator-(const Time& t1, const Time& t2) { return Time(t1.getTime()-t2.getTime()); } Time SRL::operator-(const Time& t1, const int32& seconds) { return Time(t1.getTime()-seconds); } Time SRL::operator-(const int32& seconds, const Time& t1) { return Time(seconds-t1.getTime()); } // COMPARISON OPERATIONS bool SRL::operator==(const Time& time1, const Time& time2) { // lets estimate if it is within milliseconds return time1.getTime() == time2.getTime(); } bool SRL::operator!=(const Time& time1, const Time& time2) { return time1.getTime() != time2.getTime(); } bool SRL::operator<(const Time& time1, const Time& time2) { return time1.getTime() < time2.getTime(); } bool SRL::operator<=(const Time& time1, const Time& time2) { return time1.getTime() <= time2.getTime(); } bool SRL::operator>(const Time& time1, const Time& time2) { return time1.getTime() > time2.getTime(); } bool SRL::operator>=(const Time& time1, const Time& time2) { return time1.getTime() >= time2.getTime(); }
22.901361
131
0.547898
311labs
db86fd0393e1a6ec76d97b9a5c98076e1fd12e83
47,102
hpp
C++
src/uavcan/equipment/ice/reciprocating/Status.hpp
bolderflight/dronecan
bf3382ebfad5107077c62ce220e102e1f3f7a67c
[ "MIT" ]
null
null
null
src/uavcan/equipment/ice/reciprocating/Status.hpp
bolderflight/dronecan
bf3382ebfad5107077c62ce220e102e1f3f7a67c
[ "MIT" ]
null
null
null
src/uavcan/equipment/ice/reciprocating/Status.hpp
bolderflight/dronecan
bf3382ebfad5107077c62ce220e102e1f3f7a67c
[ "MIT" ]
null
null
null
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /mnt/c/Users/BrianTaylor/Documents/Software/dronecan/dsdl/uavcan/equipment/ice/reciprocating/1120.Status.uavcan */ #ifndef UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED #define UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> #include <uavcan/equipment/ice/reciprocating/CylinderStatus.hpp> /******************************* Source text ********************************** # # Generic status message of a piston engine control system. # # All integer fields are required unless stated otherwise. # All floating point fields are optional unless stated otherwise; unknown/unapplicable fields should be set to NaN. # # # Abstract engine state. The flags defined below can provide further elaboration. # This is a required field. # uint2 state # # The engine is not running. This is the default state. # Next states: STARTING, FAULT # uint2 STATE_STOPPED = 0 # # The engine is starting. This is a transient state. # Next states: STOPPED, RUNNING, FAULT # uint2 STATE_STARTING = 1 # # The engine is running normally. # Some error flags may be set to indicate non-fatal issues, e.g. overheating. # Next states: STOPPED, FAULT # uint2 STATE_RUNNING = 2 # # The engine can no longer function. # The error flags may contain additional information about the nature of the fault. # Next states: STOPPED. # uint2 STATE_FAULT = 3 # # General status flags. # Note that not all flags are required. Those that aren't are prepended with a validity flag, which is, obviously, # always required; when the validity flag is set, it is assumed that the relevant flags are set correctly. # If the validity flag is cleared, then the state of the relevant flags should be ignored. # All unused bits must be cleared. # uint30 flags # # General error. This flag is required, and it can be used to indicate an error condition # that does not fit any of the other flags. # Note that the vendor may also report additional status information via the vendor specific status code # field of the NodeStatus message. # uint30 FLAG_GENERAL_ERROR = 1 # # Error of the crankshaft sensor. This flag is optional. # uint30 FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2 uint30 FLAG_CRANKSHAFT_SENSOR_ERROR = 4 # # Temperature levels. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_TEMPERATURE_SUPPORTED = 8 uint30 FLAG_TEMPERATURE_BELOW_NOMINAL = 16 # Under-temperature warning uint30 FLAG_TEMPERATURE_ABOVE_NOMINAL = 32 # Over-temperature warning uint30 FLAG_TEMPERATURE_OVERHEATING = 64 # Critical overheating uint30 FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128 # Exhaust gas over-temperature warning # # Fuel pressure. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_FUEL_PRESSURE_SUPPORTED = 256 uint30 FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512 # Under-pressure warning uint30 FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024 # Over-pressure warning # # Detonation warning. This flag is optional. # This warning is cleared immediately after broadcasting is done if detonation is no longer happening. # uint30 FLAG_DETONATION_SUPPORTED = 2048 uint30 FLAG_DETONATION_OBSERVED = 4096 # Detonation condition observed warning # # Misfire warning. This flag is optional. # This warning is cleared immediately after broadcasting is done if misfire is no longer happening. # uint30 FLAG_MISFIRE_SUPPORTED = 8192 uint30 FLAG_MISFIRE_OBSERVED = 16384 # Misfire condition observed warning # # Oil pressure. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_OIL_PRESSURE_SUPPORTED = 32768 uint30 FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536 # Under-pressure warning uint30 FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072 # Over-pressure warning # # Debris warning. This flag is optional. # uint30 FLAG_DEBRIS_SUPPORTED = 262144 uint30 FLAG_DEBRIS_DETECTED = 524288 # Detection of debris warning # # Reserved space # void16 # # Engine load estimate. # Unit: percent. # Range: [0, 127]. # uint7 engine_load_percent # # Engine speed. # Unit: revolutions per minute. # uint17 engine_speed_rpm # # Spark dwell time. # Unit: millisecond. # float16 spark_dwell_time_ms # # Atmospheric (barometric) pressure. # Unit: kilopascal. # float16 atmospheric_pressure_kpa # # Engine intake manifold pressure. # Unit: kilopascal. # float16 intake_manifold_pressure_kpa # # Engine intake manifold temperature. # Unit: kelvin. # float16 intake_manifold_temperature # # Engine coolant temperature. # Unit: kelvin. # float16 coolant_temperature # # Oil pressure. # Unit: kilopascal. # float16 oil_pressure # # Oil temperature. # Unit: kelvin. # float16 oil_temperature # # Fuel pressure. # Unit: kilopascal. # float16 fuel_pressure # # Instant fuel consumption estimate. # The estimated value should be low-pass filtered in order to prevent aliasing effects. # Unit: (centimeter^3)/minute. # float32 fuel_consumption_rate_cm3pm # # Estimate of the consumed fuel since the start of the engine. # This variable MUST be reset when the engine is stopped. # Unit: centimeter^3. # float32 estimated_consumed_fuel_volume_cm3 # # Throttle position. # Unit: percent. # uint7 throttle_position_percent # # The index of the publishing ECU. # uint6 ecu_index # # Spark plug activity report. # Can be used during pre-flight tests of the spark subsystem. # uint3 spark_plug_usage # uint3 SPARK_PLUG_SINGLE = 0 uint3 SPARK_PLUG_FIRST_ACTIVE = 1 uint3 SPARK_PLUG_SECOND_ACTIVE = 2 uint3 SPARK_PLUG_BOTH_ACTIVE = 3 # # Per-cylinder status information. # CylinderStatus[<=16] cylinder_status ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.equipment.ice.reciprocating.Status saturated uint2 state saturated uint30 flags void16 saturated uint7 engine_load_percent saturated uint17 engine_speed_rpm saturated float16 spark_dwell_time_ms saturated float16 atmospheric_pressure_kpa saturated float16 intake_manifold_pressure_kpa saturated float16 intake_manifold_temperature saturated float16 coolant_temperature saturated float16 oil_pressure saturated float16 oil_temperature saturated float16 fuel_pressure saturated float32 fuel_consumption_rate_cm3pm saturated float32 estimated_consumed_fuel_volume_cm3 saturated uint7 throttle_position_percent saturated uint6 ecu_index saturated uint3 spark_plug_usage uavcan.equipment.ice.reciprocating.CylinderStatus[<=16] cylinder_status ******************************************************************************/ #undef state #undef flags #undef _void_0 #undef engine_load_percent #undef engine_speed_rpm #undef spark_dwell_time_ms #undef atmospheric_pressure_kpa #undef intake_manifold_pressure_kpa #undef intake_manifold_temperature #undef coolant_temperature #undef oil_pressure #undef oil_temperature #undef fuel_pressure #undef fuel_consumption_rate_cm3pm #undef estimated_consumed_fuel_volume_cm3 #undef throttle_position_percent #undef ecu_index #undef spark_plug_usage #undef cylinder_status #undef STATE_STOPPED #undef STATE_STARTING #undef STATE_RUNNING #undef STATE_FAULT #undef FLAG_GENERAL_ERROR #undef FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED #undef FLAG_CRANKSHAFT_SENSOR_ERROR #undef FLAG_TEMPERATURE_SUPPORTED #undef FLAG_TEMPERATURE_BELOW_NOMINAL #undef FLAG_TEMPERATURE_ABOVE_NOMINAL #undef FLAG_TEMPERATURE_OVERHEATING #undef FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL #undef FLAG_FUEL_PRESSURE_SUPPORTED #undef FLAG_FUEL_PRESSURE_BELOW_NOMINAL #undef FLAG_FUEL_PRESSURE_ABOVE_NOMINAL #undef FLAG_DETONATION_SUPPORTED #undef FLAG_DETONATION_OBSERVED #undef FLAG_MISFIRE_SUPPORTED #undef FLAG_MISFIRE_OBSERVED #undef FLAG_OIL_PRESSURE_SUPPORTED #undef FLAG_OIL_PRESSURE_BELOW_NOMINAL #undef FLAG_OIL_PRESSURE_ABOVE_NOMINAL #undef FLAG_DEBRIS_SUPPORTED #undef FLAG_DEBRIS_DETECTED #undef SPARK_PLUG_SINGLE #undef SPARK_PLUG_FIRST_ACTIVE #undef SPARK_PLUG_SECOND_ACTIVE #undef SPARK_PLUG_BOTH_ACTIVE namespace uavcan { namespace equipment { namespace ice { namespace reciprocating { template <int _tmpl> struct UAVCAN_EXPORT Status_ { typedef const Status_<_tmpl>& ParameterType; typedef Status_<_tmpl>& ReferenceType; struct ConstantTypes { typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STOPPED; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STARTING; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_RUNNING; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_FAULT; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_GENERAL_ERROR; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_OVERHEATING; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_OBSERVED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_OBSERVED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_DETECTED; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SINGLE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_FIRST_ACTIVE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SECOND_ACTIVE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_BOTH_ACTIVE; }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > state; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > flags; typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > _void_0; typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_load_percent; typedef ::uavcan::IntegerSpec< 17, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_speed_rpm; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > spark_dwell_time_ms; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > atmospheric_pressure_kpa; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_pressure_kpa; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > coolant_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_pressure; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > fuel_pressure; typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > fuel_consumption_rate_cm3pm; typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > estimated_consumed_fuel_volume_cm3; typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > throttle_position_percent; typedef ::uavcan::IntegerSpec< 6, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ecu_index; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > spark_plug_usage; typedef ::uavcan::Array< ::uavcan::equipment::ice::reciprocating::CylinderStatus, ::uavcan::ArrayModeDynamic, 16 > cylinder_status; }; enum { MinBitLen = FieldTypes::state::MinBitLen + FieldTypes::flags::MinBitLen + FieldTypes::_void_0::MinBitLen + FieldTypes::engine_load_percent::MinBitLen + FieldTypes::engine_speed_rpm::MinBitLen + FieldTypes::spark_dwell_time_ms::MinBitLen + FieldTypes::atmospheric_pressure_kpa::MinBitLen + FieldTypes::intake_manifold_pressure_kpa::MinBitLen + FieldTypes::intake_manifold_temperature::MinBitLen + FieldTypes::coolant_temperature::MinBitLen + FieldTypes::oil_pressure::MinBitLen + FieldTypes::oil_temperature::MinBitLen + FieldTypes::fuel_pressure::MinBitLen + FieldTypes::fuel_consumption_rate_cm3pm::MinBitLen + FieldTypes::estimated_consumed_fuel_volume_cm3::MinBitLen + FieldTypes::throttle_position_percent::MinBitLen + FieldTypes::ecu_index::MinBitLen + FieldTypes::spark_plug_usage::MinBitLen + FieldTypes::cylinder_status::MinBitLen }; enum { MaxBitLen = FieldTypes::state::MaxBitLen + FieldTypes::flags::MaxBitLen + FieldTypes::_void_0::MaxBitLen + FieldTypes::engine_load_percent::MaxBitLen + FieldTypes::engine_speed_rpm::MaxBitLen + FieldTypes::spark_dwell_time_ms::MaxBitLen + FieldTypes::atmospheric_pressure_kpa::MaxBitLen + FieldTypes::intake_manifold_pressure_kpa::MaxBitLen + FieldTypes::intake_manifold_temperature::MaxBitLen + FieldTypes::coolant_temperature::MaxBitLen + FieldTypes::oil_pressure::MaxBitLen + FieldTypes::oil_temperature::MaxBitLen + FieldTypes::fuel_pressure::MaxBitLen + FieldTypes::fuel_consumption_rate_cm3pm::MaxBitLen + FieldTypes::estimated_consumed_fuel_volume_cm3::MaxBitLen + FieldTypes::throttle_position_percent::MaxBitLen + FieldTypes::ecu_index::MaxBitLen + FieldTypes::spark_plug_usage::MaxBitLen + FieldTypes::cylinder_status::MaxBitLen }; // Constants static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STOPPED >::Type STATE_STOPPED; // 0 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STARTING >::Type STATE_STARTING; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_RUNNING >::Type STATE_RUNNING; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_FAULT >::Type STATE_FAULT; // 3 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_GENERAL_ERROR >::Type FLAG_GENERAL_ERROR; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type FLAG_CRANKSHAFT_SENSOR_ERROR; // 4 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type FLAG_TEMPERATURE_SUPPORTED; // 8 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type FLAG_TEMPERATURE_BELOW_NOMINAL; // 16 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_ABOVE_NOMINAL; // 32 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type FLAG_TEMPERATURE_OVERHEATING; // 64 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL; // 128 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type FLAG_FUEL_PRESSURE_SUPPORTED; // 256 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type FLAG_FUEL_PRESSURE_BELOW_NOMINAL; // 512 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_FUEL_PRESSURE_ABOVE_NOMINAL; // 1024 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type FLAG_DETONATION_SUPPORTED; // 2048 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_OBSERVED >::Type FLAG_DETONATION_OBSERVED; // 4096 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type FLAG_MISFIRE_SUPPORTED; // 8192 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type FLAG_MISFIRE_OBSERVED; // 16384 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type FLAG_OIL_PRESSURE_SUPPORTED; // 32768 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type FLAG_OIL_PRESSURE_BELOW_NOMINAL; // 65536 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_OIL_PRESSURE_ABOVE_NOMINAL; // 131072 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type FLAG_DEBRIS_SUPPORTED; // 262144 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_DETECTED >::Type FLAG_DEBRIS_DETECTED; // 524288 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SINGLE >::Type SPARK_PLUG_SINGLE; // 0 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type SPARK_PLUG_FIRST_ACTIVE; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type SPARK_PLUG_SECOND_ACTIVE; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type SPARK_PLUG_BOTH_ACTIVE; // 3 // Fields typename ::uavcan::StorageType< typename FieldTypes::state >::Type state; typename ::uavcan::StorageType< typename FieldTypes::flags >::Type flags; typename ::uavcan::StorageType< typename FieldTypes::engine_load_percent >::Type engine_load_percent; typename ::uavcan::StorageType< typename FieldTypes::engine_speed_rpm >::Type engine_speed_rpm; typename ::uavcan::StorageType< typename FieldTypes::spark_dwell_time_ms >::Type spark_dwell_time_ms; typename ::uavcan::StorageType< typename FieldTypes::atmospheric_pressure_kpa >::Type atmospheric_pressure_kpa; typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_pressure_kpa >::Type intake_manifold_pressure_kpa; typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_temperature >::Type intake_manifold_temperature; typename ::uavcan::StorageType< typename FieldTypes::coolant_temperature >::Type coolant_temperature; typename ::uavcan::StorageType< typename FieldTypes::oil_pressure >::Type oil_pressure; typename ::uavcan::StorageType< typename FieldTypes::oil_temperature >::Type oil_temperature; typename ::uavcan::StorageType< typename FieldTypes::fuel_pressure >::Type fuel_pressure; typename ::uavcan::StorageType< typename FieldTypes::fuel_consumption_rate_cm3pm >::Type fuel_consumption_rate_cm3pm; typename ::uavcan::StorageType< typename FieldTypes::estimated_consumed_fuel_volume_cm3 >::Type estimated_consumed_fuel_volume_cm3; typename ::uavcan::StorageType< typename FieldTypes::throttle_position_percent >::Type throttle_position_percent; typename ::uavcan::StorageType< typename FieldTypes::ecu_index >::Type ecu_index; typename ::uavcan::StorageType< typename FieldTypes::spark_plug_usage >::Type spark_plug_usage; typename ::uavcan::StorageType< typename FieldTypes::cylinder_status >::Type cylinder_status; Status_() : state() , flags() , engine_load_percent() , engine_speed_rpm() , spark_dwell_time_ms() , atmospheric_pressure_kpa() , intake_manifold_pressure_kpa() , intake_manifold_temperature() , coolant_temperature() , oil_pressure() , oil_temperature() , fuel_pressure() , fuel_consumption_rate_cm3pm() , estimated_consumed_fuel_volume_cm3() , throttle_position_percent() , ecu_index() , spark_plug_usage() , cylinder_status() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<1565 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindMessage }; enum { DefaultDataTypeID = 1120 }; static const char* getDataTypeFullName() { return "uavcan.equipment.ice.reciprocating.Status"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); }; /* * Out of line struct method definitions */ template <int _tmpl> bool Status_<_tmpl>::operator==(ParameterType rhs) const { return state == rhs.state && flags == rhs.flags && engine_load_percent == rhs.engine_load_percent && engine_speed_rpm == rhs.engine_speed_rpm && spark_dwell_time_ms == rhs.spark_dwell_time_ms && atmospheric_pressure_kpa == rhs.atmospheric_pressure_kpa && intake_manifold_pressure_kpa == rhs.intake_manifold_pressure_kpa && intake_manifold_temperature == rhs.intake_manifold_temperature && coolant_temperature == rhs.coolant_temperature && oil_pressure == rhs.oil_pressure && oil_temperature == rhs.oil_temperature && fuel_pressure == rhs.fuel_pressure && fuel_consumption_rate_cm3pm == rhs.fuel_consumption_rate_cm3pm && estimated_consumed_fuel_volume_cm3 == rhs.estimated_consumed_fuel_volume_cm3 && throttle_position_percent == rhs.throttle_position_percent && ecu_index == rhs.ecu_index && spark_plug_usage == rhs.spark_plug_usage && cylinder_status == rhs.cylinder_status; } template <int _tmpl> bool Status_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(state, rhs.state) && ::uavcan::areClose(flags, rhs.flags) && ::uavcan::areClose(engine_load_percent, rhs.engine_load_percent) && ::uavcan::areClose(engine_speed_rpm, rhs.engine_speed_rpm) && ::uavcan::areClose(spark_dwell_time_ms, rhs.spark_dwell_time_ms) && ::uavcan::areClose(atmospheric_pressure_kpa, rhs.atmospheric_pressure_kpa) && ::uavcan::areClose(intake_manifold_pressure_kpa, rhs.intake_manifold_pressure_kpa) && ::uavcan::areClose(intake_manifold_temperature, rhs.intake_manifold_temperature) && ::uavcan::areClose(coolant_temperature, rhs.coolant_temperature) && ::uavcan::areClose(oil_pressure, rhs.oil_pressure) && ::uavcan::areClose(oil_temperature, rhs.oil_temperature) && ::uavcan::areClose(fuel_pressure, rhs.fuel_pressure) && ::uavcan::areClose(fuel_consumption_rate_cm3pm, rhs.fuel_consumption_rate_cm3pm) && ::uavcan::areClose(estimated_consumed_fuel_volume_cm3, rhs.estimated_consumed_fuel_volume_cm3) && ::uavcan::areClose(throttle_position_percent, rhs.throttle_position_percent) && ::uavcan::areClose(ecu_index, rhs.ecu_index) && ::uavcan::areClose(spark_plug_usage, rhs.spark_plug_usage) && ::uavcan::areClose(cylinder_status, rhs.cylinder_status); } template <int _tmpl> int Status_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0; int res = 1; res = FieldTypes::state::encode(self.state, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::encode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::_void_0::encode(_void_0, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_load_percent::encode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_speed_rpm::encode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_dwell_time_ms::encode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::atmospheric_pressure_kpa::encode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_pressure_kpa::encode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_temperature::encode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::coolant_temperature::encode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_pressure::encode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_temperature::encode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_pressure::encode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_consumption_rate_cm3pm::encode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::estimated_consumed_fuel_volume_cm3::encode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::throttle_position_percent::encode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::ecu_index::encode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_plug_usage::encode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::cylinder_status::encode(self.cylinder_status, codec, tao_mode); return res; } template <int _tmpl> int Status_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0; int res = 1; res = FieldTypes::state::decode(self.state, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::decode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::_void_0::decode(_void_0, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_load_percent::decode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_speed_rpm::decode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_dwell_time_ms::decode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::atmospheric_pressure_kpa::decode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_pressure_kpa::decode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_temperature::decode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::coolant_temperature::decode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_pressure::decode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_temperature::decode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_pressure::decode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_consumption_rate_cm3pm::decode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::estimated_consumed_fuel_volume_cm3::decode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::throttle_position_percent::decode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::ecu_index::decode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_plug_usage::decode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::cylinder_status::decode(self.cylinder_status, codec, tao_mode); return res; } /* * Out of line type method definitions */ template <int _tmpl> ::uavcan::DataTypeSignature Status_<_tmpl>::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0x5465C0CF37619F32ULL); FieldTypes::state::extendDataTypeSignature(signature); FieldTypes::flags::extendDataTypeSignature(signature); FieldTypes::_void_0::extendDataTypeSignature(signature); FieldTypes::engine_load_percent::extendDataTypeSignature(signature); FieldTypes::engine_speed_rpm::extendDataTypeSignature(signature); FieldTypes::spark_dwell_time_ms::extendDataTypeSignature(signature); FieldTypes::atmospheric_pressure_kpa::extendDataTypeSignature(signature); FieldTypes::intake_manifold_pressure_kpa::extendDataTypeSignature(signature); FieldTypes::intake_manifold_temperature::extendDataTypeSignature(signature); FieldTypes::coolant_temperature::extendDataTypeSignature(signature); FieldTypes::oil_pressure::extendDataTypeSignature(signature); FieldTypes::oil_temperature::extendDataTypeSignature(signature); FieldTypes::fuel_pressure::extendDataTypeSignature(signature); FieldTypes::fuel_consumption_rate_cm3pm::extendDataTypeSignature(signature); FieldTypes::estimated_consumed_fuel_volume_cm3::extendDataTypeSignature(signature); FieldTypes::throttle_position_percent::extendDataTypeSignature(signature); FieldTypes::ecu_index::extendDataTypeSignature(signature); FieldTypes::spark_plug_usage::extendDataTypeSignature(signature); FieldTypes::cylinder_status::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STOPPED >::Type Status_<_tmpl>::STATE_STOPPED = 0U; // 0 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STARTING >::Type Status_<_tmpl>::STATE_STARTING = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_RUNNING >::Type Status_<_tmpl>::STATE_RUNNING = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_FAULT >::Type Status_<_tmpl>::STATE_FAULT = 3U; // 3 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_GENERAL_ERROR >::Type Status_<_tmpl>::FLAG_GENERAL_ERROR = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR = 4U; // 4 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_TEMPERATURE_SUPPORTED = 8U; // 8 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_BELOW_NOMINAL = 16U; // 16 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_ABOVE_NOMINAL = 32U; // 32 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type Status_<_tmpl>::FLAG_TEMPERATURE_OVERHEATING = 64U; // 64 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128U; // 128 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_SUPPORTED = 256U; // 256 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512U; // 512 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024U; // 1024 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type Status_<_tmpl>::FLAG_DETONATION_SUPPORTED = 2048U; // 2048 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_OBSERVED >::Type Status_<_tmpl>::FLAG_DETONATION_OBSERVED = 4096U; // 4096 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type Status_<_tmpl>::FLAG_MISFIRE_SUPPORTED = 8192U; // 8192 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type Status_<_tmpl>::FLAG_MISFIRE_OBSERVED = 16384U; // 16384 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_SUPPORTED = 32768U; // 32768 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536U; // 65536 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072U; // 131072 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type Status_<_tmpl>::FLAG_DEBRIS_SUPPORTED = 262144U; // 262144 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_DETECTED >::Type Status_<_tmpl>::FLAG_DEBRIS_DETECTED = 524288U; // 524288 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SINGLE >::Type Status_<_tmpl>::SPARK_PLUG_SINGLE = 0U; // 0 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_FIRST_ACTIVE = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_SECOND_ACTIVE = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_BOTH_ACTIVE = 3U; // 3 /* * Final typedef */ typedef Status_<0> Status; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::equipment::ice::reciprocating::Status > _uavcan_gdtr_registrator_Status; } } // Namespace reciprocating } // Namespace ice } // Namespace equipment } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "state: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::state >::stream(s, obj.state, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "flags: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::flags >::stream(s, obj.flags, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "engine_load_percent: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_load_percent >::stream(s, obj.engine_load_percent, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "engine_speed_rpm: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_speed_rpm >::stream(s, obj.engine_speed_rpm, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "spark_dwell_time_ms: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_dwell_time_ms >::stream(s, obj.spark_dwell_time_ms, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "atmospheric_pressure_kpa: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::atmospheric_pressure_kpa >::stream(s, obj.atmospheric_pressure_kpa, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "intake_manifold_pressure_kpa: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_pressure_kpa >::stream(s, obj.intake_manifold_pressure_kpa, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "intake_manifold_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_temperature >::stream(s, obj.intake_manifold_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "coolant_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::coolant_temperature >::stream(s, obj.coolant_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "oil_pressure: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_pressure >::stream(s, obj.oil_pressure, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "oil_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_temperature >::stream(s, obj.oil_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "fuel_pressure: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_pressure >::stream(s, obj.fuel_pressure, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "fuel_consumption_rate_cm3pm: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_consumption_rate_cm3pm >::stream(s, obj.fuel_consumption_rate_cm3pm, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "estimated_consumed_fuel_volume_cm3: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::estimated_consumed_fuel_volume_cm3 >::stream(s, obj.estimated_consumed_fuel_volume_cm3, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "throttle_position_percent: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::throttle_position_percent >::stream(s, obj.throttle_position_percent, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "ecu_index: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::ecu_index >::stream(s, obj.ecu_index, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "spark_plug_usage: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_plug_usage >::stream(s, obj.spark_plug_usage, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "cylinder_status: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::cylinder_status >::stream(s, obj.cylinder_status, level + 1); } } namespace uavcan { namespace equipment { namespace ice { namespace reciprocating { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(s, obj, 0); return s; } } // Namespace reciprocating } // Namespace ice } // Namespace equipment } // Namespace uavcan #endif // UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED
41.980392
178
0.715999
bolderflight
db87898b216bae3122a2f3d54dd64e72f4558416
2,738
cpp
C++
Scripts/PlayerMovement/BombDropSkill.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
10
2019-02-25T11:36:23.000Z
2021-11-03T22:51:30.000Z
Scripts/PlayerMovement/BombDropSkill.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
146
2019-02-05T13:57:33.000Z
2019-11-07T16:21:31.000Z
Scripts/PlayerMovement/BombDropSkill.cpp
FractalPuppy/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
3
2019-11-17T20:49:12.000Z
2020-04-19T17:28:28.000Z
#include "BombDropSkill.h" #include "PlayerMovement.h" #include "Application.h" #include "ModuleNavigation.h" #include "ModuleTime.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ComponentBoxTrigger.h" #include "PlayerState.h" BombDropSkill::BombDropSkill(PlayerMovement* PM, const char* trigger, ComponentBoxTrigger* attackBox) : MeleeSkill(PM, trigger, attackBox) { } BombDropSkill::~BombDropSkill() { path.clear(); } void BombDropSkill::Start() { MeleeSkill::Start(); player->App->navigation->setPlayerBB(player->gameobject->bbox); if (player->App->navigation->NavigateTowardsCursor(player->gameobject->transform->position, path, math::float3(player->OutOfMeshCorrectionXZ, player->OutOfMeshCorrectionY, player->OutOfMeshCorrectionXZ), intersectionPoint, bombDropMaxDistance, PathFindType::NODODGE)) { pathIndex = 0; player->gameobject->transform->LookAt(intersectionPoint); if (bombDropFX) { bombDropFX->SetActive(true); } player->ResetCooldown(HUD_BUTTON_E); } //Create the hitbox boxSize = math::float3(250.f, 100.f, 250.f); //attackBoxTrigger.set // Set delay for hit hitDelay = 0.5f; } void BombDropSkill::UseSkill() { if (path.size() > 0 && timer > bombDropPreparationTime && timer < hitDelay) { math::float3 currentPosition = player->gameobject->transform->GetPosition(); while (pathIndex < path.size() && currentPosition.DistanceSq(path[pathIndex]) < MINIMUM_PATH_DISTANCE) { pathIndex++; } if (pathIndex < path.size()) { player->gameobject->transform->LookAt(path[pathIndex]); math::float3 direction = (path[pathIndex] - currentPosition).Normalized(); player->gameobject->transform->SetPosition(currentPosition + bombDropSpeed * direction * player->App->time->fullGameDeltaTime); } } if (player->attackBoxTrigger != nullptr && !player->attackBoxTrigger->enabled) { // Update hitbox boxPosition = player->transform->up * 100.f; //this front stuff isnt working well when rotating the chicken player->attackBoxTrigger->SetBoxPosition(boxPosition.x, boxPosition.y, boxPosition.z + 200.f); } } void BombDropSkill::CheckInput() { if (timer > player->currentState->duration) //CAN SWITCH? { if (player->IsUsingSkill()) { player->currentState = (PlayerState*)player->attack; } else if (player->IsMovingToAttack()) { if (player->ThirdStageBoss) { player->currentState = (PlayerState*)player->walkToHit3rdBoss; } else { player->currentState = (PlayerState*)player->walkToHit; } } else if (player->IsMovingToItem()) { player->currentState = (PlayerState*)player->walkToPickItem; } else if (player->IsMoving()) { player->currentState = (PlayerState*)player->walk; } } }
25.351852
130
0.716216
solidajenjo
db8a4a63e97545d5a94ba11d2f41fb79b03c5b80
14,657
cpp
C++
source/RDP/Views/SetupTargetApplicationView.cpp
jekstrand/GPUOpen-Tools-DevDriverTools
1f583cece41ac5c1b3e53b675bf0511e1fd81e54
[ "MIT" ]
null
null
null
source/RDP/Views/SetupTargetApplicationView.cpp
jekstrand/GPUOpen-Tools-DevDriverTools
1f583cece41ac5c1b3e53b675bf0511e1fd81e54
[ "MIT" ]
null
null
null
source/RDP/Views/SetupTargetApplicationView.cpp
jekstrand/GPUOpen-Tools-DevDriverTools
1f583cece41ac5c1b3e53b675bf0511e1fd81e54
[ "MIT" ]
1
2018-10-02T08:47:03.000Z
2018-10-02T08:47:03.000Z
//============================================================================= /// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief Implementation of the Setup Target Application panel interface. //============================================================================= #include <QStandardItemModel> #include <QFileDialog> #include <QFontMetrics> #include <QGridLayout> #include <QSpacerItem> #include "SetupTargetApplicationView.h" #include "ui_SetupTargetApplicationView.h" #include "../RDPDefinitions.h" #include "../Settings/RDPSettings.h" #include "../Util/RDPUtil.h" #include "../Models/SetupTargetApplicationModel.h" #include "../Models/DeveloperPanelModel.h" #include <QtUtil.h> //----------------------------------------------------------------------------- /// Explicit constructor /// \param pPanelModel The panel model. /// \param pParent The parent widget. //----------------------------------------------------------------------------- SetupTargetApplicationView::SetupTargetApplicationView(DeveloperPanelModel* pPanelModel, QWidget* pParent) : QWidget(pParent), ui(new Ui::SetupTargetApplicationView), m_pSetupTargetApplicationModel(nullptr), m_traceInProgress(false) { ui->setupUi(this); // Create a model for the table view. m_pSetupTargetApplicationModel = new SetupTargetApplicationModel(); Q_ASSERT(m_pSetupTargetApplicationModel != nullptr); QtCommon::QtUtil::ApplyStandardTableStyle(ui->TargetApplicationList); ui->TargetApplicationList->setModel(m_pSetupTargetApplicationModel->GetTableModel()); ui->TargetApplicationList->SetTargetApplicationModel(m_pSetupTargetApplicationModel); Q_ASSERT(pPanelModel); pPanelModel->SetTargetApplicationsModel(m_pSetupTargetApplicationModel); // Set up signals/slots. connect(ui->addToListButton, &QPushButton::clicked, this, &SetupTargetApplicationView::AddToList); connect(ui->targetExeLineEdit, &QLineEdit::returnPressed, this, &SetupTargetApplicationView::OnReturnPressedOnExecutableLine); connect(ui->removeFromListButton, &QPushButton::clicked, this, &SetupTargetApplicationView::RemoveFromList); connect(ui->targetExeBrowseButton, &QPushButton::clicked, this, &SetupTargetApplicationView::OnTargetExeBrowseButtonPressed); connect(ui->TargetApplicationList, &AppListTreeView::clicked, this, &SetupTargetApplicationView::OnApplicationSelected); connect(ui->targetExeLineEdit, &QLineEdit::textChanged, this, &SetupTargetApplicationView::OnTargetExeLineEditTextChanged); // Disable the remove from list button for now ui->removeFromListButton->setEnabled(false); // Disable the add to list button for now ui->addToListButton->setEnabled(false); // Enable sorting for target application list ui->TargetApplicationList->setSortingEnabled(true); ui->TargetApplicationList->sortByColumn(TARGET_APPLICATION_TABLE_COLUMN_EXECUTABLE_NAME, Qt::AscendingOrder); // Update the model. m_pSetupTargetApplicationModel->Update(); AdjustTableColumns(); } //----------------------------------------------------------------------------- /// Destructor //----------------------------------------------------------------------------- SetupTargetApplicationView::~SetupTargetApplicationView() { SAFE_DELETE(ui); SAFE_DELETE(m_pSetupTargetApplicationModel); } //----------------------------------------------------------------------------- /// Slot to handle what happens when the user clicks the 'Add to list' /// button /// \param clicked Whether the button is clicked //----------------------------------------------------------------------------- void SetupTargetApplicationView::AddToList(bool clicked) { Q_UNUSED(clicked); QString applicationFilepath = ui->targetExeLineEdit->text(); if (applicationFilepath.isEmpty()) { RDPUtil::ShowNotification(gs_PRODUCT_NAME_STRING, gs_NO_FILE_SPECIFIED_TEXT, NotificationWidget::Button::Ok); } else { // Remove any leading and trailing whitespace from the specified executable. applicationFilepath = applicationFilepath.trimmed(); AddExecutableToList(applicationFilepath); } } //----------------------------------------------------------------------------- /// Add the given executable filename to the Target Applications table. /// \param executableFilename The executable filename to add to the target list. /// \returns True if the new item was added to the list successfully, and false if it failed. //----------------------------------------------------------------------------- bool SetupTargetApplicationView::AddExecutableToList(const QString& executableFilename) { bool addedSuccessfully = m_pSetupTargetApplicationModel->AddApplication(executableFilename); if (addedSuccessfully == false) { RDPUtil::ShowNotification(gs_PRODUCT_NAME_STRING, gs_DUPLICATE_FILE_TEXT, NotificationWidget::Button::Ok); } else { // The executable was added successfully, so clear out the textbox. ui->targetExeLineEdit->setText(""); AdjustTableColumns(); // Select the last application added by the user. QModelIndex firstRow = ui->TargetApplicationList->model()->index(0, 0); ui->TargetApplicationList->setCurrentIndex(firstRow); // Enable the "Remove from list" button ui->removeFromListButton->setEnabled(true); } return addedSuccessfully; } //----------------------------------------------------------------------------- /// Handler invoked when the 'Remove from list' button is clicked. /// \param clicked Flag that indicates if the button is checked. //----------------------------------------------------------------------------- void SetupTargetApplicationView::RemoveFromList(bool clicked) { Q_UNUSED(clicked); QModelIndex selectedRowIndex = ui->TargetApplicationList->currentIndex(); if (selectedRowIndex.isValid()) { int selectedRow = selectedRowIndex.row(); int sourceModelRow = m_pSetupTargetApplicationModel->MapToSourceModelRow(ui->TargetApplicationList->currentIndex()); RDPSettings& rdpSettings = RDPSettings::Get(); // If a trace is currently being collected or this application is currently being profiled, disallow this operation. if (m_traceInProgress || (rdpSettings.isAllowTargetApplicationProfiling(sourceModelRow) && !GetSetupTargetApplicationModel()->ActivelyProfiledApplication().isEmpty()) ) { RDPUtil::ShowNotification(gs_DELETE_WHILE_PROFILING_TITLE, gs_DELETE_WHILE_PROFILING_MSG, NotificationWidget::Button::Ok); return; } // Pop up a confirmation dialog box NotificationWidget::Button resultButton = RDPUtil::ShowNotification(gs_DELETE_APPLICATION_TITLE, gs_DELETE_APPLICATION, NotificationWidget::Button::Yes | NotificationWidget::Button::No, NotificationWidget::Button::No); if (resultButton == NotificationWidget::Button::Yes) { // Get the name of the application being removed QString executableName; bool result = m_pSetupTargetApplicationModel->GetExecutableNameAtRow(sourceModelRow, executableName); m_pSetupTargetApplicationModel->RemoveApplication(selectedRow); AdjustTableColumns(); // Get the model QAbstractItemModel* pModel = m_pSetupTargetApplicationModel->GetTableModel(); // Get the data from the first row/column QString text = pModel->data(pModel->index(0, 0)).toString(); // If the table is empty, disable the "Remove from list" button if (text.isEmpty()) { ui->removeFromListButton->setEnabled(false); } // emit a signal to indicate that an app was removed if (result == true) { emit ApplicationRemovedFromList(executableName); } } } } //----------------------------------------------------------------------------- /// Handler invoked when the user presses the "Enter" key while the target executable textbox has focus. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnReturnPressedOnExecutableLine() { // Add whatever is in the textbox as the next target executable. AddToList(false); } //----------------------------------------------------------------------------- /// Target exe browse button pressed SLOT - Determines what to do when the /// browse button next to the target executable edit field is pressed. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTargetExeBrowseButtonPressed() { // Fill the dialog with the existing target executable directory. const QString& lastAppPath = RDPSettings::Get().GetLastTargetExecutableDirectory(); #ifdef WIN32 // Create file filters for the windows file dialog box QString fileNameFilter = "All files (*.*);;Exe files (*.exe)"; QString defaultFilter = "Exe files (*.exe)"; // Open a new file selection dialog so the user can choose a target executable. const QString& applicationFilepath = QFileDialog::getOpenFileName(this, gs_BROWSE_APPLICATION_FILEPATH_CAPTION_TEXT, lastAppPath, fileNameFilter, &defaultFilter); #else // Open a new file selection dialog so the user can choose a target executable. const QString& applicationFilepath = QFileDialog::getOpenFileName(this, gs_BROWSE_APPLICATION_FILEPATH_CAPTION_TEXT, lastAppPath); #endif // WIN32 // getOpenFileName returns a "null" QString if the user cancels the dialog. Only continue if they select something. if (!applicationFilepath.isNull()) { // Trim the full path to just the application filename to filter with. QFileInfo fileInfo(applicationFilepath); QString executableOnly(fileInfo.fileName()); // Keep the user's last directory to start at next time. RDPSettings::Get().SetLastTargetExecutableDirectory(applicationFilepath); ui->targetExeLineEdit->setText(executableOnly); AddToList(true); } } //----------------------------------------------------------------------------- /// Adjust the column widths of the target applications table //----------------------------------------------------------------------------- void SetupTargetApplicationView::AdjustTableColumns() { int numRows = m_pSetupTargetApplicationModel->GetTableModel()->rowCount(); QtCommon::QtUtil::AutoAdjustTableColumns(ui->TargetApplicationList, numRows, 10); } //----------------------------------------------------------------------------- /// Enable the "Remove from list" button when an exe is selected from the list /// \param index the model index of the clicked item //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnApplicationSelected(const QModelIndex& index) { Q_UNUSED(index); // A row was clicked on, so enable the "Remove from list" button ui->removeFromListButton->setEnabled(true); } //----------------------------------------------------------------------------- /// Enable/disable the "Add to list" button as necessary /// \param text The text enetered into the line edit //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTargetExeLineEditTextChanged(const QString& text) { // Enable/Disable the add to list button ui->addToListButton->setEnabled(!text.isEmpty()); } //----------------------------------------------------------------------------- /// Slot invoked when the RGPTraceModel either starts or finishes collecting an RGP trace. /// \param traceIsBeingCollected A flag that indicates the current state of RGP Trace collection. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTraceCollectionStatusUpdated(bool traceIsBeingCollected) { m_traceInProgress = traceIsBeingCollected; } //----------------------------------------------------------------------------- /// Return the model object pointer. /// \return SetupTargetApplicationModel pointer //----------------------------------------------------------------------------- SetupTargetApplicationModel* SetupTargetApplicationView::GetSetupTargetApplicationModel() { return m_pSetupTargetApplicationModel; } //----------------------------------------------------------------------------- /// Slot invoked when the user profiling checkbox click is not valid //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilingCheckboxClickError() { // Put up an error message RDPUtil::ShowNotification(gs_UNCHECK_PROFILE_WHILE_COLLECTING_TRACE_TITLE, gs_UNCHECK_PROFILE_WHILE_COLLECTING_TRACE_MSG, NotificationWidget::Button::Ok); } //----------------------------------------------------------------------------- /// Slot invoked when the user attempts to profile multiple instances of the same application /// \param profiledProcessInfo Process information for the latest application instance started. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilingMultipleTargetsWarning(const ProcessInfoModel& profiledProcessInfo) { // Put up an warning message QString message = QString(gs_MULTIPLE_TARGET_APPLICATION_INSTANCES_MSG).arg(profiledProcessInfo.GetProcessName().toStdString().c_str()).arg(profiledProcessInfo.GetProcessId()); RDPUtil::ShowNotification(gs_MULTIPLE_TARGET_APPLICATION_INSTANCES_TITLE, message, NotificationWidget::Button::Ok); } //----------------------------------------------------------------------------- /// Slot invoked when the user attempts to select another targe application for profiles while /// another application is already being profiled. /// \param processInfo Process information for the latest application instance started. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilerInUseWarning(const ProcessInfoModel& processInfo) { // Put up an warning message QString message = QString(gs_PROFILER_ALREADY_IN_USE_MSG).arg(processInfo.GetProcessName().toStdString().c_str()).arg(processInfo.GetProcessId()); RDPUtil::ShowNotification(gs_PROFILER_ALREADY_IN_USE_TITLE, message, NotificationWidget::Button::Ok); }
47.280645
188
0.620796
jekstrand
db92f30c47c05a64c20949fe9801d6e7ab4bc274
32,279
cc
C++
examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/types.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
2,494
2015-02-11T04:34:13.000Z
2022-03-31T14:21:47.000Z
examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/types.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/types.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
442
2015-02-12T13:45:46.000Z
2022-03-21T05:28:05.000Z
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/types.h" #include "src/ostreams.h" #include "src/types-inl.h" namespace v8 { namespace internal { // ----------------------------------------------------------------------------- // Range-related custom order on doubles. // We want -0 to be less than +0. static bool dle(double x, double y) { return x <= y && (x != 0 || IsMinusZero(x) || !IsMinusZero(y)); } static bool deq(double x, double y) { return dle(x, y) && dle(y, x); } // ----------------------------------------------------------------------------- // Glb and lub computation. // The largest bitset subsumed by this type. template<class Config> int TypeImpl<Config>::BitsetType::Glb(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); DCHECK(unioned->Wellformed()); return unioned->Get(0)->BitsetGlb(); // Other BitsetGlb's are kNone anyway. } else { return kNone; } } // The smallest bitset subsuming this type. template<class Config> int TypeImpl<Config>::BitsetType::Lub(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); int bitset = kNone; for (int i = 0; i < unioned->Length(); ++i) { bitset |= unioned->Get(i)->BitsetLub(); } return bitset; } else if (type->IsClass()) { // Little hack to avoid the need for a region for handlification here... return Config::is_class(type) ? Lub(*Config::as_class(type)) : type->AsClass()->Bound(NULL)->AsBitset(); } else if (type->IsConstant()) { return type->AsConstant()->Bound()->AsBitset(); } else if (type->IsRange()) { return type->AsRange()->Bound()->AsBitset(); } else if (type->IsContext()) { return type->AsContext()->Bound()->AsBitset(); } else if (type->IsArray()) { return type->AsArray()->Bound()->AsBitset(); } else if (type->IsFunction()) { return type->AsFunction()->Bound()->AsBitset(); } else { UNREACHABLE(); return kNone; } } // The smallest bitset subsuming this type, ignoring explicit bounds. template<class Config> int TypeImpl<Config>::BitsetType::InherentLub(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); int bitset = kNone; for (int i = 0; i < unioned->Length(); ++i) { bitset |= unioned->Get(i)->InherentBitsetLub(); } return bitset; } else if (type->IsClass()) { return Lub(*type->AsClass()->Map()); } else if (type->IsConstant()) { return Lub(*type->AsConstant()->Value()); } else if (type->IsRange()) { return Lub(type->AsRange()->Min(), type->AsRange()->Max()); } else if (type->IsContext()) { return kInternal & kTaggedPtr; } else if (type->IsArray()) { return kArray; } else if (type->IsFunction()) { return kFunction; } else { UNREACHABLE(); return kNone; } } template<class Config> int TypeImpl<Config>::BitsetType::Lub(i::Object* value) { DisallowHeapAllocation no_allocation; if (value->IsNumber()) { return Lub(value->Number()) & (value->IsSmi() ? kTaggedInt : kTaggedPtr); } return Lub(i::HeapObject::cast(value)->map()); } template<class Config> int TypeImpl<Config>::BitsetType::Lub(double value) { DisallowHeapAllocation no_allocation; if (i::IsMinusZero(value)) return kMinusZero; if (std::isnan(value)) return kNaN; if (IsUint32Double(value)) return Lub(FastD2UI(value)); if (IsInt32Double(value)) return Lub(FastD2I(value)); return kOtherNumber; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(double min, double max) { DisallowHeapAllocation no_allocation; DCHECK(dle(min, max)); if (deq(min, max)) return BitsetType::Lub(min); // Singleton range. int bitset = BitsetType::kNumber ^ SEMANTIC(BitsetType::kNaN); if (dle(0, min) || max < 0) bitset ^= SEMANTIC(BitsetType::kMinusZero); return bitset; // TODO(neis): Could refine this further by doing more checks on min/max. } template<class Config> int TypeImpl<Config>::BitsetType::Lub(int32_t value) { if (value >= 0x40000000) { return i::SmiValuesAre31Bits() ? kOtherUnsigned31 : kUnsignedSmall; } if (value >= 0) return kUnsignedSmall; if (value >= -0x40000000) return kOtherSignedSmall; return i::SmiValuesAre31Bits() ? kOtherSigned32 : kOtherSignedSmall; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(uint32_t value) { DisallowHeapAllocation no_allocation; if (value >= 0x80000000u) return kOtherUnsigned32; if (value >= 0x40000000u) { return i::SmiValuesAre31Bits() ? kOtherUnsigned31 : kUnsignedSmall; } return kUnsignedSmall; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(i::Map* map) { DisallowHeapAllocation no_allocation; switch (map->instance_type()) { case STRING_TYPE: case ASCII_STRING_TYPE: case CONS_STRING_TYPE: case CONS_ASCII_STRING_TYPE: case SLICED_STRING_TYPE: case SLICED_ASCII_STRING_TYPE: case EXTERNAL_STRING_TYPE: case EXTERNAL_ASCII_STRING_TYPE: case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE: case SHORT_EXTERNAL_STRING_TYPE: case SHORT_EXTERNAL_ASCII_STRING_TYPE: case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE: case INTERNALIZED_STRING_TYPE: case ASCII_INTERNALIZED_STRING_TYPE: case EXTERNAL_INTERNALIZED_STRING_TYPE: case EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE: case EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE: case SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE: case SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE: case SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE: return kString; case SYMBOL_TYPE: return kSymbol; case ODDBALL_TYPE: { Heap* heap = map->GetHeap(); if (map == heap->undefined_map()) return kUndefined; if (map == heap->null_map()) return kNull; if (map == heap->boolean_map()) return kBoolean; DCHECK(map == heap->the_hole_map() || map == heap->uninitialized_map() || map == heap->no_interceptor_result_sentinel_map() || map == heap->termination_exception_map() || map == heap->arguments_marker_map()); return kInternal & kTaggedPtr; } case HEAP_NUMBER_TYPE: return kNumber & kTaggedPtr; case JS_VALUE_TYPE: case JS_DATE_TYPE: case JS_OBJECT_TYPE: case JS_CONTEXT_EXTENSION_OBJECT_TYPE: case JS_GENERATOR_OBJECT_TYPE: case JS_MODULE_TYPE: case JS_GLOBAL_OBJECT_TYPE: case JS_BUILTINS_OBJECT_TYPE: case JS_GLOBAL_PROXY_TYPE: case JS_ARRAY_BUFFER_TYPE: case JS_TYPED_ARRAY_TYPE: case JS_DATA_VIEW_TYPE: case JS_SET_TYPE: case JS_MAP_TYPE: case JS_SET_ITERATOR_TYPE: case JS_MAP_ITERATOR_TYPE: case JS_WEAK_MAP_TYPE: case JS_WEAK_SET_TYPE: if (map->is_undetectable()) return kUndetectable; return kOtherObject; case JS_ARRAY_TYPE: return kArray; case JS_FUNCTION_TYPE: return kFunction; case JS_REGEXP_TYPE: return kRegExp; case JS_PROXY_TYPE: case JS_FUNCTION_PROXY_TYPE: return kProxy; case MAP_TYPE: // When compiling stub templates, the meta map is used as a place holder // for the actual map with which the template is later instantiated. // We treat it as a kind of type variable whose upper bound is Any. // TODO(rossberg): for caching of CompareNilIC stubs to work correctly, // we must exclude Undetectable here. This makes no sense, really, // because it means that the template isn't actually parametric. // Also, it doesn't apply elsewhere. 8-( // We ought to find a cleaner solution for compiling stubs parameterised // over type or class variables, esp ones with bounds... return kDetectable; case DECLARED_ACCESSOR_INFO_TYPE: case EXECUTABLE_ACCESSOR_INFO_TYPE: case SHARED_FUNCTION_INFO_TYPE: case ACCESSOR_PAIR_TYPE: case FIXED_ARRAY_TYPE: case FOREIGN_TYPE: case CODE_TYPE: return kInternal & kTaggedPtr; default: UNREACHABLE(); return kNone; } } // ----------------------------------------------------------------------------- // Predicates. // Check this <= that. template<class Config> bool TypeImpl<Config>::SlowIs(TypeImpl* that) { DisallowHeapAllocation no_allocation; // Fast path for bitsets. if (this->IsNone()) return true; if (that->IsBitset()) { return BitsetType::Is(BitsetType::Lub(this), that->AsBitset()); } if (that->IsClass()) { return this->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map() && ((Config::is_class(that) && Config::is_class(this)) || BitsetType::New(this->BitsetLub())->Is( BitsetType::New(that->BitsetLub()))); } if (that->IsConstant()) { return this->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value() && this->AsConstant()->Bound()->Is(that->AsConstant()->Bound()); } if (that->IsRange()) { return this->IsRange() && this->AsRange()->Bound()->Is(that->AsRange()->Bound()) && dle(that->AsRange()->Min(), this->AsRange()->Min()) && dle(this->AsRange()->Max(), that->AsRange()->Max()); } if (that->IsContext()) { return this->IsContext() && this->AsContext()->Outer()->Equals(that->AsContext()->Outer()); } if (that->IsArray()) { return this->IsArray() && this->AsArray()->Element()->Equals(that->AsArray()->Element()); } if (that->IsFunction()) { // We currently do not allow for any variance here, in order to keep // Union and Intersect operations simple. if (!this->IsFunction()) return false; FunctionType* this_fun = this->AsFunction(); FunctionType* that_fun = that->AsFunction(); if (this_fun->Arity() != that_fun->Arity() || !this_fun->Result()->Equals(that_fun->Result()) || !that_fun->Receiver()->Equals(this_fun->Receiver())) { return false; } for (int i = 0; i < this_fun->Arity(); ++i) { if (!that_fun->Parameter(i)->Equals(this_fun->Parameter(i))) return false; } return true; } // (T1 \/ ... \/ Tn) <= T <=> (T1 <= T) /\ ... /\ (Tn <= T) if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (!unioned->Get(i)->Is(that)) return false; } return true; } // T <= (T1 \/ ... \/ Tn) <=> (T <= T1) \/ ... \/ (T <= Tn) // (iff T is not a union) DCHECK(!this->IsUnion() && that->IsUnion()); UnionHandle unioned = handle(that->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (this->Is(unioned->Get(i))) return true; if (this->IsBitset()) break; // Fast fail, only first field is a bitset. } return false; } template<class Config> bool TypeImpl<Config>::NowIs(TypeImpl* that) { DisallowHeapAllocation no_allocation; // TODO(rossberg): this is incorrect for // Union(Constant(V), T)->NowIs(Class(M)) // but fuzzing does not cover that! if (this->IsConstant()) { i::Object* object = *this->AsConstant()->Value(); if (object->IsHeapObject()) { i::Map* map = i::HeapObject::cast(object)->map(); for (Iterator<i::Map> it = that->Classes(); !it.Done(); it.Advance()) { if (*it.Current() == map) return true; } } } return this->Is(that); } // Check if this contains only (currently) stable classes. template<class Config> bool TypeImpl<Config>::NowStable() { DisallowHeapAllocation no_allocation; for (Iterator<i::Map> it = this->Classes(); !it.Done(); it.Advance()) { if (!it.Current()->is_stable()) return false; } return true; } // Check this overlaps that. template<class Config> bool TypeImpl<Config>::Maybe(TypeImpl* that) { DisallowHeapAllocation no_allocation; // (T1 \/ ... \/ Tn) overlaps T <=> (T1 overlaps T) \/ ... \/ (Tn overlaps T) if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->Maybe(that)) return true; } return false; } // T overlaps (T1 \/ ... \/ Tn) <=> (T overlaps T1) \/ ... \/ (T overlaps Tn) if (that->IsUnion()) { UnionHandle unioned = handle(that->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (this->Maybe(unioned->Get(i))) return true; } return false; } DCHECK(!this->IsUnion() && !that->IsUnion()); if (this->IsBitset() || that->IsBitset()) { return BitsetType::IsInhabited(this->BitsetLub() & that->BitsetLub()); } if (this->IsClass()) { return that->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map(); } if (this->IsConstant()) { return that->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value(); } if (this->IsContext()) { return this->Equals(that); } if (this->IsArray()) { // There is no variance! return this->Equals(that); } if (this->IsFunction()) { // There is no variance! return this->Equals(that); } return false; } // Check if value is contained in (inhabits) type. template<class Config> bool TypeImpl<Config>::Contains(i::Object* value) { DisallowHeapAllocation no_allocation; if (this->IsRange()) { return value->IsNumber() && dle(this->AsRange()->Min(), value->Number()) && dle(value->Number(), this->AsRange()->Max()) && BitsetType::Is(BitsetType::Lub(value), this->BitsetLub()); } for (Iterator<i::Object> it = this->Constants(); !it.Done(); it.Advance()) { if (*it.Current() == value) return true; } return BitsetType::New(BitsetType::Lub(value))->Is(this); } template<class Config> bool TypeImpl<Config>::UnionType::Wellformed() { DCHECK(this->Length() >= 2); for (int i = 0; i < this->Length(); ++i) { DCHECK(!this->Get(i)->IsUnion()); if (i > 0) DCHECK(!this->Get(i)->IsBitset()); for (int j = 0; j < this->Length(); ++j) { if (i != j) DCHECK(!this->Get(i)->Is(this->Get(j))); } } return true; } // ----------------------------------------------------------------------------- // Union and intersection template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Rebound( int bitset, Region* region) { TypeHandle bound = BitsetType::New(bitset, region); if (this->IsClass()) { return ClassType::New(this->AsClass()->Map(), bound, region); } else if (this->IsConstant()) { return ConstantType::New(this->AsConstant()->Value(), bound, region); } else if (this->IsRange()) { return RangeType::New( this->AsRange()->Min(), this->AsRange()->Max(), bound, region); } else if (this->IsContext()) { return ContextType::New(this->AsContext()->Outer(), bound, region); } else if (this->IsArray()) { return ArrayType::New(this->AsArray()->Element(), bound, region); } else if (this->IsFunction()) { FunctionHandle function = Config::handle(this->AsFunction()); int arity = function->Arity(); FunctionHandle type = FunctionType::New( function->Result(), function->Receiver(), bound, arity, region); for (int i = 0; i < arity; ++i) { type->InitParameter(i, function->Parameter(i)); } return type; } UNREACHABLE(); return TypeHandle(); } template<class Config> int TypeImpl<Config>::BoundBy(TypeImpl* that) { DCHECK(!this->IsUnion()); if (that->IsUnion()) { UnionType* unioned = that->AsUnion(); int length = unioned->Length(); int bitset = BitsetType::kNone; for (int i = 0; i < length; ++i) { bitset |= BoundBy(unioned->Get(i)->unhandle()); } return bitset; } else if (that->IsClass() && this->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map()) { return that->BitsetLub(); } else if (that->IsConstant() && this->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value()) { return that->AsConstant()->Bound()->AsBitset(); } else if (that->IsContext() && this->IsContext() && this->Is(that)) { return that->AsContext()->Bound()->AsBitset(); } else if (that->IsArray() && this->IsArray() && this->Is(that)) { return that->AsArray()->Bound()->AsBitset(); } else if (that->IsFunction() && this->IsFunction() && this->Is(that)) { return that->AsFunction()->Bound()->AsBitset(); } return that->BitsetGlb(); } template<class Config> int TypeImpl<Config>::IndexInUnion( int bound, UnionHandle unioned, int current_size) { DCHECK(!this->IsUnion()); for (int i = 0; i < current_size; ++i) { TypeHandle that = unioned->Get(i); if (that->IsBitset()) { if (BitsetType::Is(bound, that->AsBitset())) return i; } else if (that->IsClass() && this->IsClass()) { if (*this->AsClass()->Map() == *that->AsClass()->Map()) return i; } else if (that->IsConstant() && this->IsConstant()) { if (*this->AsConstant()->Value() == *that->AsConstant()->Value()) return i; } else if (that->IsContext() && this->IsContext()) { if (this->Is(that)) return i; } else if (that->IsArray() && this->IsArray()) { if (this->Is(that)) return i; } else if (that->IsFunction() && this->IsFunction()) { if (this->Is(that)) return i; } } return -1; } // Get non-bitsets from type, bounded by upper. // Store at result starting at index. Returns updated index. template<class Config> int TypeImpl<Config>::ExtendUnion( UnionHandle result, int size, TypeHandle type, TypeHandle other, bool is_intersect, Region* region) { if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { TypeHandle type_i = unioned->Get(i); DCHECK(i == 0 || !(type_i->IsBitset() || type_i->Is(unioned->Get(0)))); if (!type_i->IsBitset()) { size = ExtendUnion(result, size, type_i, other, is_intersect, region); } } } else if (!type->IsBitset()) { DCHECK(type->IsClass() || type->IsConstant() || type->IsRange() || type->IsContext() || type->IsArray() || type->IsFunction()); int inherent_bound = type->InherentBitsetLub(); int old_bound = type->BitsetLub(); int other_bound = type->BoundBy(other->unhandle()) & inherent_bound; int new_bound = is_intersect ? (old_bound & other_bound) : (old_bound | other_bound); if (new_bound != BitsetType::kNone) { int i = type->IndexInUnion(new_bound, result, size); if (i == -1) { i = size++; } else if (result->Get(i)->IsBitset()) { return size; // Already fully subsumed. } else { int type_i_bound = result->Get(i)->BitsetLub(); new_bound |= type_i_bound; if (new_bound == type_i_bound) return size; } if (new_bound != old_bound) type = type->Rebound(new_bound, region); result->Set(i, type); } } return size; } // Union is O(1) on simple bitsets, but O(n*m) on structured unions. template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Union( TypeHandle type1, TypeHandle type2, Region* region) { // Fast case: bit sets. if (type1->IsBitset() && type2->IsBitset()) { return BitsetType::New(type1->AsBitset() | type2->AsBitset(), region); } // Fast case: top or bottom types. if (type1->IsAny() || type2->IsNone()) return type1; if (type2->IsAny() || type1->IsNone()) return type2; // Semi-fast case: Unioned objects are neither involved nor produced. if (!(type1->IsUnion() || type2->IsUnion())) { if (type1->Is(type2)) return type2; if (type2->Is(type1)) return type1; } // Slow case: may need to produce a Unioned object. int size = 0; if (!type1->IsBitset()) { size += (type1->IsUnion() ? type1->AsUnion()->Length() : 1); } if (!type2->IsBitset()) { size += (type2->IsUnion() ? type2->AsUnion()->Length() : 1); } int bitset = type1->BitsetGlb() | type2->BitsetGlb(); if (bitset != BitsetType::kNone) ++size; DCHECK(size >= 1); UnionHandle unioned = UnionType::New(size, region); size = 0; if (bitset != BitsetType::kNone) { unioned->Set(size++, BitsetType::New(bitset, region)); } size = ExtendUnion(unioned, size, type1, type2, false, region); size = ExtendUnion(unioned, size, type2, type1, false, region); if (size == 1) { return unioned->Get(0); } else { unioned->Shrink(size); DCHECK(unioned->Wellformed()); return unioned; } } // Intersection is O(1) on simple bitsets, but O(n*m) on structured unions. template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Intersect( TypeHandle type1, TypeHandle type2, Region* region) { // Fast case: bit sets. if (type1->IsBitset() && type2->IsBitset()) { return BitsetType::New(type1->AsBitset() & type2->AsBitset(), region); } // Fast case: top or bottom types. if (type1->IsNone() || type2->IsAny()) return type1; if (type2->IsNone() || type1->IsAny()) return type2; // Semi-fast case: Unioned objects are neither involved nor produced. if (!(type1->IsUnion() || type2->IsUnion())) { if (type1->Is(type2)) return type1; if (type2->Is(type1)) return type2; } // Slow case: may need to produce a Unioned object. int size = 0; if (!type1->IsBitset()) { size += (type1->IsUnion() ? type1->AsUnion()->Length() : 1); } if (!type2->IsBitset()) { size += (type2->IsUnion() ? type2->AsUnion()->Length() : 1); } int bitset = type1->BitsetGlb() & type2->BitsetGlb(); if (bitset != BitsetType::kNone) ++size; DCHECK(size >= 1); UnionHandle unioned = UnionType::New(size, region); size = 0; if (bitset != BitsetType::kNone) { unioned->Set(size++, BitsetType::New(bitset, region)); } size = ExtendUnion(unioned, size, type1, type2, true, region); size = ExtendUnion(unioned, size, type2, type1, true, region); if (size == 0) { return None(region); } else if (size == 1) { return unioned->Get(0); } else { unioned->Shrink(size); DCHECK(unioned->Wellformed()); return unioned; } } // ----------------------------------------------------------------------------- // Iteration. template<class Config> int TypeImpl<Config>::NumClasses() { DisallowHeapAllocation no_allocation; if (this->IsClass()) { return 1; } else if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); int result = 0; for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->IsClass()) ++result; } return result; } else { return 0; } } template<class Config> int TypeImpl<Config>::NumConstants() { DisallowHeapAllocation no_allocation; if (this->IsConstant()) { return 1; } else if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); int result = 0; for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->IsConstant()) ++result; } return result; } else { return 0; } } template<class Config> template<class T> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Iterator<T>::get_type() { DCHECK(!Done()); return type_->IsUnion() ? type_->AsUnion()->Get(index_) : type_; } // C++ cannot specialise nested templates, so we have to go through this // contortion with an auxiliary template to simulate it. template<class Config, class T> struct TypeImplIteratorAux { static bool matches(typename TypeImpl<Config>::TypeHandle type); static i::Handle<T> current(typename TypeImpl<Config>::TypeHandle type); }; template<class Config> struct TypeImplIteratorAux<Config, i::Map> { static bool matches(typename TypeImpl<Config>::TypeHandle type) { return type->IsClass(); } static i::Handle<i::Map> current(typename TypeImpl<Config>::TypeHandle type) { return type->AsClass()->Map(); } }; template<class Config> struct TypeImplIteratorAux<Config, i::Object> { static bool matches(typename TypeImpl<Config>::TypeHandle type) { return type->IsConstant(); } static i::Handle<i::Object> current( typename TypeImpl<Config>::TypeHandle type) { return type->AsConstant()->Value(); } }; template<class Config> template<class T> bool TypeImpl<Config>::Iterator<T>::matches(TypeHandle type) { return TypeImplIteratorAux<Config, T>::matches(type); } template<class Config> template<class T> i::Handle<T> TypeImpl<Config>::Iterator<T>::Current() { return TypeImplIteratorAux<Config, T>::current(get_type()); } template<class Config> template<class T> void TypeImpl<Config>::Iterator<T>::Advance() { DisallowHeapAllocation no_allocation; ++index_; if (type_->IsUnion()) { UnionHandle unioned = handle(type_->AsUnion()); for (; index_ < unioned->Length(); ++index_) { if (matches(unioned->Get(index_))) return; } } else if (index_ == 0 && matches(type_)) { return; } index_ = -1; } // ----------------------------------------------------------------------------- // Conversion between low-level representations. template<class Config> template<class OtherType> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Convert( typename OtherType::TypeHandle type, Region* region) { if (type->IsBitset()) { return BitsetType::New(type->AsBitset(), region); } else if (type->IsClass()) { TypeHandle bound = BitsetType::New(type->BitsetLub(), region); return ClassType::New(type->AsClass()->Map(), bound, region); } else if (type->IsConstant()) { TypeHandle bound = Convert<OtherType>(type->AsConstant()->Bound(), region); return ConstantType::New(type->AsConstant()->Value(), bound, region); } else if (type->IsRange()) { TypeHandle bound = Convert<OtherType>(type->AsRange()->Bound(), region); return RangeType::New( type->AsRange()->Min(), type->AsRange()->Max(), bound, region); } else if (type->IsContext()) { TypeHandle bound = Convert<OtherType>(type->AsContext()->Bound(), region); TypeHandle outer = Convert<OtherType>(type->AsContext()->Outer(), region); return ContextType::New(outer, bound, region); } else if (type->IsUnion()) { int length = type->AsUnion()->Length(); UnionHandle unioned = UnionType::New(length, region); for (int i = 0; i < length; ++i) { TypeHandle t = Convert<OtherType>(type->AsUnion()->Get(i), region); unioned->Set(i, t); } return unioned; } else if (type->IsArray()) { TypeHandle element = Convert<OtherType>(type->AsArray()->Element(), region); TypeHandle bound = Convert<OtherType>(type->AsArray()->Bound(), region); return ArrayType::New(element, bound, region); } else if (type->IsFunction()) { TypeHandle res = Convert<OtherType>(type->AsFunction()->Result(), region); TypeHandle rcv = Convert<OtherType>(type->AsFunction()->Receiver(), region); TypeHandle bound = Convert<OtherType>(type->AsFunction()->Bound(), region); FunctionHandle function = FunctionType::New( res, rcv, bound, type->AsFunction()->Arity(), region); for (int i = 0; i < function->Arity(); ++i) { TypeHandle param = Convert<OtherType>( type->AsFunction()->Parameter(i), region); function->InitParameter(i, param); } return function; } else { UNREACHABLE(); return None(region); } } // ----------------------------------------------------------------------------- // Printing. template<class Config> const char* TypeImpl<Config>::BitsetType::Name(int bitset) { switch (bitset) { case REPRESENTATION(kAny): return "Any"; #define RETURN_NAMED_REPRESENTATION_TYPE(type, value) \ case REPRESENTATION(k##type): return #type; REPRESENTATION_BITSET_TYPE_LIST(RETURN_NAMED_REPRESENTATION_TYPE) #undef RETURN_NAMED_REPRESENTATION_TYPE #define RETURN_NAMED_SEMANTIC_TYPE(type, value) \ case SEMANTIC(k##type): return #type; SEMANTIC_BITSET_TYPE_LIST(RETURN_NAMED_SEMANTIC_TYPE) #undef RETURN_NAMED_SEMANTIC_TYPE default: return NULL; } } template <class Config> void TypeImpl<Config>::BitsetType::Print(OStream& os, // NOLINT int bitset) { DisallowHeapAllocation no_allocation; const char* name = Name(bitset); if (name != NULL) { os << name; return; } static const int named_bitsets[] = { #define BITSET_CONSTANT(type, value) REPRESENTATION(k##type), REPRESENTATION_BITSET_TYPE_LIST(BITSET_CONSTANT) #undef BITSET_CONSTANT #define BITSET_CONSTANT(type, value) SEMANTIC(k##type), SEMANTIC_BITSET_TYPE_LIST(BITSET_CONSTANT) #undef BITSET_CONSTANT }; bool is_first = true; os << "("; for (int i(ARRAY_SIZE(named_bitsets) - 1); bitset != 0 && i >= 0; --i) { int subset = named_bitsets[i]; if ((bitset & subset) == subset) { if (!is_first) os << " | "; is_first = false; os << Name(subset); bitset -= subset; } } DCHECK(bitset == 0); os << ")"; } template <class Config> void TypeImpl<Config>::PrintTo(OStream& os, PrintDimension dim) { // NOLINT DisallowHeapAllocation no_allocation; if (dim != REPRESENTATION_DIM) { if (this->IsBitset()) { BitsetType::Print(os, SEMANTIC(this->AsBitset())); } else if (this->IsClass()) { os << "Class(" << static_cast<void*>(*this->AsClass()->Map()) << " < "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsConstant()) { os << "Constant(" << static_cast<void*>(*this->AsConstant()->Value()) << " : "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsRange()) { os << "Range(" << this->AsRange()->Min() << ".." << this->AsRange()->Max() << " : "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsContext()) { os << "Context("; this->AsContext()->Outer()->PrintTo(os, dim); os << ")"; } else if (this->IsUnion()) { os << "("; UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { TypeHandle type_i = unioned->Get(i); if (i > 0) os << " | "; type_i->PrintTo(os, dim); } os << ")"; } else if (this->IsArray()) { os << "Array("; AsArray()->Element()->PrintTo(os, dim); os << ")"; } else if (this->IsFunction()) { if (!this->AsFunction()->Receiver()->IsAny()) { this->AsFunction()->Receiver()->PrintTo(os, dim); os << "."; } os << "("; for (int i = 0; i < this->AsFunction()->Arity(); ++i) { if (i > 0) os << ", "; this->AsFunction()->Parameter(i)->PrintTo(os, dim); } os << ")->"; this->AsFunction()->Result()->PrintTo(os, dim); } else { UNREACHABLE(); } } if (dim == BOTH_DIMS) os << "/"; if (dim != SEMANTIC_DIM) { BitsetType::Print(os, REPRESENTATION(this->BitsetLub())); } } #ifdef DEBUG template <class Config> void TypeImpl<Config>::Print() { OFStream os(stdout); PrintTo(os); os << endl; } #endif // ----------------------------------------------------------------------------- // Instantiations. template class TypeImpl<ZoneTypeConfig>; template class TypeImpl<ZoneTypeConfig>::Iterator<i::Map>; template class TypeImpl<ZoneTypeConfig>::Iterator<i::Object>; template class TypeImpl<HeapTypeConfig>; template class TypeImpl<HeapTypeConfig>::Iterator<i::Map>; template class TypeImpl<HeapTypeConfig>::Iterator<i::Object>; template TypeImpl<ZoneTypeConfig>::TypeHandle TypeImpl<ZoneTypeConfig>::Convert<HeapType>( TypeImpl<HeapTypeConfig>::TypeHandle, TypeImpl<ZoneTypeConfig>::Region*); template TypeImpl<HeapTypeConfig>::TypeHandle TypeImpl<HeapTypeConfig>::Convert<Type>( TypeImpl<ZoneTypeConfig>::TypeHandle, TypeImpl<HeapTypeConfig>::Region*); } } // namespace v8::internal
32.671053
80
0.621457
madanagopaltcomcast
db9471268d8a19e81c2756bee36f02aab74bd2a0
1,391
cpp
C++
src/Engine/Thread.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
127
2018-12-09T18:40:02.000Z
2022-03-06T00:10:07.000Z
src/Engine/Thread.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
267
2019-02-26T22:16:48.000Z
2022-02-09T09:49:22.000Z
src/Engine/Thread.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
17
2019-02-26T20:45:34.000Z
2021-06-17T15:06:26.000Z
#include <squirrel.h> #include "engge/System/Locator.hpp" #include "engge/Engine/EntityManager.hpp" #include "engge/Engine/Thread.hpp" #include <utility> namespace ng { Thread::Thread(std::string name, bool isGlobal, HSQUIRRELVM v, HSQOBJECT thread_obj, HSQOBJECT env_obj, HSQOBJECT closureObj, std::vector<HSQOBJECT> args) : m_name(std::move(name)), m_v(v), m_threadObj(thread_obj), m_envObj(env_obj), m_closureObj(closureObj), m_args(std::move(args)), m_isGlobal(isGlobal) { sq_addref(m_v, &m_threadObj); sq_addref(m_v, &m_envObj); sq_addref(m_v, &m_closureObj); m_id = Locator<EntityManager>::get().getThreadId(); } Thread::~Thread() { sq_release(m_v, &m_threadObj); sq_release(m_v, &m_envObj); sq_release(m_v, &m_closureObj); } std::string Thread::getName() const { return m_name; } HSQUIRRELVM Thread::getThread() const { return m_threadObj._unVal.pThread; } bool Thread::call() { auto thread = getThread(); // call the closure in the thread SQInteger top = sq_gettop(thread); sq_pushobject(thread, m_closureObj); sq_pushobject(thread, m_envObj); for (auto arg : m_args) { sq_pushobject(thread, arg); } if (SQ_FAILED(sq_call(thread, 1 + m_args.size(), SQFalse, SQTrue))) { sq_settop(thread, top); return false; } return true; } } // namespace ng
26.75
133
0.672178
scemino
db957aeb96208737a0f832c61bb9b7c15ee33b44
11,669
cpp
C++
externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
1
2021-09-02T08:42:59.000Z
2021-09-02T08:42:59.000Z
externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
null
null
null
externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2017 Melown Technologies SE * * 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. */ #include "../camera.hpp" #include "../navigation.hpp" #include "../traverseNode.hpp" #include "../coordsManip.hpp" #include "../mapLayer.hpp" #include "../mapConfig.hpp" #include "../map.hpp" #include "../gpuResource.hpp" #include "../renderTasks.hpp" #include <optick.h> namespace vts { using vtslibs::vts::NodeInfo; namespace { double cross(const vec2 &a, const vec2 &b) { return a[0] * b[1] - a[1] * b[0]; } double sign(double a) { return a < 0 ? -1 : 1; } double lineSolver(const vec2 &p, const vec2 &a, const vec2 &b, double av, double bv) { vec2 v1 = b - a; if (dot(v1, v1) < 1e-4) return av; // degenerated into a point vec2 v2 = p - a; double l1 = length(v1); double l2 = length(v2); double u = l2 / l1 * sign(dot(v2, v1)); return interpolate(av, bv, u); } double triangleSolver(const vec2 &p, const vec2 &a, const vec2 &b, const vec2 &c, double av, double bv, double cv) { vec2 v0 = b - a; vec2 v1 = c - a; vec2 v2 = p - a; double d00 = dot(v0, v0); double d01 = dot(v0, v1); double d11 = dot(v1, v1); double d20 = dot(v2, v0); double d21 = dot(v2, v1); { // detect degenerated cases (lines) if (d00 < 1e-4) return lineSolver(p, a, c, av, cv); if (d11 < 1e-4) return lineSolver(p, a, b, av, bv); vec2 v3 = c - b; double d33 = dot(v3, v3); if (d33 < 1e-4) return lineSolver(p, a, b, av, bv); } double invDenom = 1.0 / (d00 * d11 - d01 * d01); double v = (d11 * d20 - d01 * d21) * invDenom; double w = (d00 * d21 - d01 * d20) * invDenom; double u = 1 - v - w; return u * av + v * bv + w * cv; } double bilinearInterpolation(double u, double v, double av, double bv, double cv, double dv) { assert(u >= 0 && u <= 1 && v >= 0 && v <= 1); double p = interpolate(av, bv, u); double q = interpolate(cv, dv, u); return interpolate(p, q, v); } double quadrilateralSolver(const vec2 &p, const vec2 &a, const vec2 &b, const vec2 &c, const vec2 &d, double av, double bv, double cv, double dv) { const vec2 e = b - a; const vec2 f = c - a; { // detect degenerated cases (triangles) vec2 q3 = b - d; vec2 q4 = c - d; if (dot(e, e) < 1e-4) return triangleSolver(p, a, c, d, av, cv, dv); if (dot(f, f) < 1e-4) return triangleSolver(p, a, b, d, av, bv, dv); if (dot(q3, q3) < 1e-4) return triangleSolver(p, a, b, c, av, bv, cv); if (dot(q4, q4) < 1e-4) return triangleSolver(p, a, b, c, av, bv, cv); } vec2 g = a - b + d - c; vec2 h = p - a; double k2 = cross(g, f); if (std::abs(k2) < 1e-7) { // rectangle double u = h[0] / e[0]; double v = h[1] / f[1]; if (v >= 0 && v <= 1 && u >= 0 && u <= 1) return bilinearInterpolation(u, v, av, bv, cv, dv); return nan1(); // the query is outside the quadrilateral } double k0 = cross(h, e); double k1 = cross(e, f) + cross(h, g); double w = k1 * k1 - 4 * k0 * k2; if (w < 0) return nan1(); // the quadrilateral has negative area w = sqrt(w); double v1 = (-k1 - w) / (2 * k2); double u1 = (h[0] - f[0] * v1) / (e[0] + g[0] * v1); double v2 = (-k1 + w) / (2 * k2); double u2 = (h[0] - f[0] * v2) / (e[0] + g[0] * v2); if (v1 >= 0 && v1 <= 1 && u1 >= 0 && u1 <= 1) return bilinearInterpolation(u1, v1, av, bv, cv, dv); if (v2 >= 0 && v2 <= 1 && u2 >= 0 && u2 <= 1) return bilinearInterpolation(u2, v2, av, bv, cv, dv); return nan1(); // the query is outside the quadrilateral } double altitudeInterpolation( const vec2 &query, const vec2 points[4], double values[4]) { return quadrilateralSolver(query, points[0], points[1], points[2], points[3], values[0], values[1], values[2], values[3] ); } TraverseNode *findTravSds(CameraImpl *camera, TraverseNode *where, const vec2 &pointSds, uint32 maxLod) { assert(where && where->meta); if (where->id.lod >= maxLod) return where; math::Point2 ublasSds = vecToUblas<math::Point2>(pointSds); for (auto &ci : where->childs) { // avoid computing new extents if we already have them if (ci.meta) { if (!math::inside(ci.meta->extents, ublasSds)) continue; } else { const Extents2 ce = subExtents( where->meta->extents, where->id, ci.id); if (!math::inside(ce, ublasSds)) continue; } if (!camera->travInit(&ci)) continue; return findTravSds(camera, &ci, pointSds, maxLod); } return where; } } // namespace bool CameraImpl::getSurfaceOverEllipsoid( double &result, const vec3 &navPos, double sampleSize, bool renderDebug) { OPTICK_EVENT(); assert(map->convertor); assert(!map->layers.empty()); //std::string s = map->layers.empty() ? "true" : "false"; //LOG(info3) << "map" << std::endl; //LOG(info3) << map << std::endl; //LOG(info3) << "map layers 0" << std::endl; //// LOG(info3) << map->layers << std::endl; //LOG(info3) << "map->layers.empty() : " << s; //LOG(info3) << map->layers[0] << std::endl; //LOG(info3) << "map layers 0 traverseRoot" << std::endl; //LOG(info3) << map->layers[0]->traverseRoot << std::endl; //LOG(info3) << "map end" << std::endl; //if (map->layers[0] == nullptr) { // return false; //} //---------------------------------------crash region -------------------------------------- TraverseNode *root = map->layers[0]->traverseRoot.get(); //------------------------------------------------------------------------------------------- if (!root || !root->meta) return false; if (sampleSize <= 0) sampleSize = getSurfaceAltitudeSamples(); // find surface division coordinates (and appropriate node info) vec2 sds; boost::optional<NodeInfo> info; uint32 index = 0; for (const auto &it : map->mapconfig->referenceFrame.division.nodes) { struct I { uint32 &i; I(uint32 &i) : i(i) {} ~I() { ++i; } } inc(index); if (it.second.partitioning.mode != vtslibs::registry::PartitioningMode::bisection) continue; const NodeInfo &ni = map->mapconfig->referenceDivisionNodeInfos[index]; try { sds = vec3to2(map->convertor->convert(navPos, Srs::Navigation, it.second.srs)); if (!ni.inside(vecToUblas<math::Point2>(sds))) continue; info = ni; break; } catch(const std::exception &) { // do nothing } } if (!info) return false; // desired lod uint32 desiredLod = std::max(0.0, -std::log2(sampleSize / info->extents().size())); // find corner positions vec2 points[4]; { NodeInfo i = *info; while (i.nodeId().lod < desiredLod) { for (auto j : vtslibs::vts::children(i.nodeId())) { NodeInfo k = i.child(j); if (!k.inside(vecToUblas<math::Point2>(sds))) continue; i = k; break; } } math::Extents2 ext = i.extents(); vec2 center = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5; vec2 size = vecFromUblas<vec2>(ext.ur - ext.ll); vec2 p = sds; if (sds(0) < center(0)) p(0) -= size(0); if (sds(1) < center(1)) p(1) -= size(1); points[0] = p; points[1] = p + vec2(size(0), 0); points[2] = p + vec2(0, size(1)); points[3] = p + size; // todo periodicity } // find the actual corners TraverseNode *travRoot = findTravById(root, info->nodeId()); if (!travRoot || !travRoot->meta) return false; double altitudes[4]; const TraverseNode *nodes[4]; for (int i = 0; i < 4; i++) { auto t = findTravSds(this, travRoot, points[i], desiredLod); if (!t) return false; if (!t->meta->surrogateNav) return false; const math::Extents2 &ext = t->meta->extents; points[i] = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5; altitudes[i] = *t->meta->surrogateNav; nodes[i] = t; } // interpolate double res = altitudeInterpolation(sds, points, altitudes); // debug visualization if (renderDebug) { RenderInfographicsTask task; task.mesh = map->getMesh("internal://data/meshes/sphere.obj"); task.mesh->priority = inf1(); if (*task.mesh) { float c = std::isnan(res) ? 0.0 : 1.0; task.color = vec4f(c, c, c, 0.7f); double scaleSum = 0; for (int i = 0; i < 4; i++) { const TraverseNode *t = nodes[i]; double scale = t->meta->extents.size() * 0.035; task.model = translationMatrix(*t->meta->surrogatePhys) * scaleMatrix(scale); draws.infographics.push_back(convert(task)); scaleSum += scale; } if (!std::isnan(res)) { vec3 p = navPos; p[2] = res; p = map->convertor->convert(p, Srs::Navigation, Srs::Physical); task.model = translationMatrix(p) * scaleMatrix(scaleSum / 4); task.color = vec4f(c, c, c, 1.f); draws.infographics.push_back(convert(task)); } } } // output if (std::isnan(res)) return false; result = res; return true; } double CameraImpl::getSurfaceAltitudeSamples() { double targetDistance = length(vec3(target - eye)); double viewExtent = targetDistance / (apiProj(1, 1) * 0.5); double result = viewExtent / options.samplesForAltitudeLodSelection; if (std::isnan(result)) return 10; return result; } } // namespace vts
31.034574
97
0.537921
HanochZhu
db9683b9927669a1c501318a673a228da87a6576
5,411
cpp
C++
src/internal/ResumeCache.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
src/internal/ResumeCache.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
src/internal/ResumeCache.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. #include "ResumeCache.h" #include <algorithm> #include "src/framing/Frame.h" #include "src/framing/FrameTransport.h" #include "src/statemachine/RSocketStateMachine.h" namespace { using rsocket::FrameType; bool shouldTrackFrame(const FrameType frameType) { switch (frameType) { case FrameType::REQUEST_CHANNEL: case FrameType::REQUEST_STREAM: case FrameType::REQUEST_RESPONSE: case FrameType::REQUEST_FNF: case FrameType::REQUEST_N: case FrameType::CANCEL: case FrameType::ERROR: case FrameType::PAYLOAD: return true; case FrameType::RESERVED: case FrameType::SETUP: case FrameType::LEASE: case FrameType::KEEPALIVE: case FrameType::METADATA_PUSH: case FrameType::RESUME: case FrameType::RESUME_OK: case FrameType::EXT: default: return false; } } } // anonymous namespace rsocket { ResumeCache::~ResumeCache() { clearFrames(position_); } void ResumeCache::trackReceivedFrame( const folly::IOBuf& serializedFrame, const FrameType frameType, const StreamId streamId) { onStreamOpen(streamId, frameType); if (shouldTrackFrame(frameType)) { VLOG(6) << "received frame " << frameType; // TODO(tmont): this could be expensive, find a better way to get length impliedPosition_ += serializedFrame.computeChainDataLength(); } } void ResumeCache::trackSentFrame( const folly::IOBuf& serializedFrame, const FrameType frameType, const folly::Optional<StreamId> streamIdPtr) { if (streamIdPtr) { const StreamId streamId = *streamIdPtr; onStreamOpen(streamId, frameType); } if (shouldTrackFrame(frameType)) { // TODO(tmont): this could be expensive, find a better way to get length auto frameDataLength = serializedFrame.computeChainDataLength(); // if the frame is too huge, we don't cache it if (frameDataLength > capacity_) { resetUpToPosition(position_); position_ += frameDataLength; DCHECK(size_ == 0); return; } addFrame(serializedFrame, frameDataLength); position_ += frameDataLength; } } void ResumeCache::resetUpToPosition(ResumePosition position) { if (position <= resetPosition_) { return; } if (position > position_) { position = position_; } clearFrames(position); resetPosition_ = position; DCHECK(frames_.empty() || frames_.front().first == resetPosition_); } bool ResumeCache::isPositionAvailable(ResumePosition position) const { return (position_ == position) || std::binary_search( frames_.begin(), frames_.end(), std::make_pair(position, std::unique_ptr<folly::IOBuf>()), [](decltype(frames_.back()) pairA, decltype(frames_.back()) pairB) { return pairA.first < pairB.first; }); } void ResumeCache::addFrame(const folly::IOBuf& frame, size_t frameDataLength) { size_ += frameDataLength; while (size_ > capacity_) { evictFrame(); } frames_.emplace_back(position_, frame.clone()); stats_->resumeBufferChanged(1, static_cast<int>(frameDataLength)); } void ResumeCache::evictFrame() { DCHECK(!frames_.empty()); auto position = frames_.size() > 1 ? std::next(frames_.begin())->first : position_; resetUpToPosition(position); } void ResumeCache::clearFrames(ResumePosition position) { if (frames_.empty()) { return; } DCHECK(position <= position_); DCHECK(position >= resetPosition_); auto end = std::lower_bound( frames_.begin(), frames_.end(), position, [](decltype(frames_.back()) pair, ResumePosition pos) { return pair.first < pos; }); DCHECK(end == frames_.end() || end->first >= resetPosition_); auto pos = end == frames_.end() ? position : end->first; stats_->resumeBufferChanged( -static_cast<int>(std::distance(frames_.begin(), end)), -static_cast<int>(pos - resetPosition_)); frames_.erase(frames_.begin(), end); size_ -= static_cast<decltype(size_)>(pos - resetPosition_); } void ResumeCache::sendFramesFromPosition( ResumePosition position, FrameTransport& frameTransport) const { DCHECK(isPositionAvailable(position)); if (position == position_) { // idle resumption return; } auto found = std::lower_bound( frames_.begin(), frames_.end(), position, [](decltype(frames_.back()) pair, ResumePosition pos) { return pair.first < pos; }); DCHECK(found != frames_.end()); DCHECK(found->first == position); while (found != frames_.end()) { frameTransport.outputFrameOrEnqueue(found->second->clone()); found++; } } void ResumeCache::onStreamClosed(StreamId streamId) { // This is crude. We could try to preserve the stream type in // RSocketStateMachine and pass it down explicitly here. activeRequestStreams_.erase(streamId); activeRequestChannels_.erase(streamId); activeRequestResponses_.erase(streamId); } void ResumeCache::onStreamOpen(StreamId streamId, FrameType frameType) { if (frameType == FrameType::REQUEST_STREAM) { activeRequestStreams_.insert(streamId); } else if (frameType == FrameType::REQUEST_CHANNEL) { activeRequestChannels_.insert(streamId); } else if (frameType == FrameType::REQUEST_RESPONSE) { activeRequestResponses_.insert(streamId); } } } // reactivesocket
27.190955
79
0.685825
benjchristensen
db9768afc836e12b07b38ecbbd7ab34cc3d2d96c
1,865
cpp
C++
evolve4src/src/evolve/evolveDoc.cpp
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
evolve4src/src/evolve/evolveDoc.cpp
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
evolve4src/src/evolve/evolveDoc.cpp
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
// evolveDoc.cpp : implementation of the CevolveDoc class // #include "stdafx.h" #include "evolve.h" #include "evolveDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CevolveDoc IMPLEMENT_DYNCREATE(CevolveDoc, CDocument) BEGIN_MESSAGE_MAP(CevolveDoc, CDocument) END_MESSAGE_MAP() // CevolveDoc construction/destruction CevolveDoc::CevolveDoc() { universe = NULL; } CevolveDoc::~CevolveDoc() { if( universe != NULL ) { Universe_Delete(universe); universe = NULL; } } BOOL CevolveDoc::OnNewDocument() { UNIVERSE *u; CevolveApp *app; char errbuf[1000]; NewUniverseOptions *nuo; if( ! CDocument::OnNewDocument() ) return FALSE; app = (CevolveApp *) AfxGetApp(); nuo = app->GetNewUniverseOptions(); u = CreateUniverse(nuo, errbuf); if( u == NULL ) { AfxMessageBox(errbuf, MB_OK, 0); return false; } SetModifiedFlag(true); universe = u; return true; } void CevolveDoc::Serialize(CArchive& ar) { // // do nothing as we have arn't using seriaize mechanism // return; } void CevolveDoc::DeleteContents() { if( universe != NULL ) { Universe_Delete(universe); universe = NULL; } } BOOL CevolveDoc::OnOpenDocument(LPCTSTR lpszPathName) { char errbuf[1000]; UNIVERSE *u; u = LoadUniverse(lpszPathName, errbuf); if( u == NULL ) { AfxMessageBox(errbuf, MB_OK, 0); universe = NULL; return false; } universe = u; return true; } BOOL CevolveDoc::OnSaveDocument(LPCTSTR lpszPathName) { int n; char errbuf[1000]; n = StoreUniverse(lpszPathName, universe, errbuf); if( n == 0 ) { AfxMessageBox(errbuf, MB_OK, 0); return false; } SetModifiedFlag(false); return true; } // CevolveDoc diagnostics #ifdef _DEBUG void CevolveDoc::AssertValid() const { CDocument::AssertValid(); } void CevolveDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CevolveDoc commands
14.236641
57
0.69866
ilyar
db9ca8666ef286a6ed1d50a8ef88bcbb61e3454f
17,155
cpp
C++
src/Mustl/MustlWebLink.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
9
2020-11-02T17:20:40.000Z
2021-12-25T15:35:36.000Z
src/Mustl/MustlWebLink.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
2
2020-06-27T23:14:13.000Z
2020-11-02T17:28:32.000Z
src/Mustl/MustlWebLink.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
1
2021-05-12T23:05:42.000Z
2021-05-12T23:05:42.000Z
//%Header { /***************************************************************************** * * File: src/Mustl/MustlWebLink.cpp * * Copyright: Andy Southgate 2002-2007, 2020 * * 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. * ****************************************************************************/ //%Header } ol7C6mm/6AFh/4txRC+jvA /* * $Id: MustlWebLink.cpp,v 1.30 2006/06/29 10:12:36 southa Exp $ * $Log: MustlWebLink.cpp,v $ * Revision 1.30 2006/06/29 10:12:36 southa * 64 bit compatibility fixes * * Revision 1.29 2006/06/01 15:39:55 southa * DrawArray verification and fixes * * Revision 1.28 2005/05/19 13:02:20 southa * Mac release work * * Revision 1.27 2004/09/26 21:07:16 southa * Mustl compilation fixes * * Revision 1.26 2004/01/02 21:13:16 southa * Source conditioning * * Revision 1.25 2004/01/01 21:15:46 southa * Created XCode project * * Revision 1.24 2003/10/06 22:23:45 southa * Game to GameMustl move * * Revision 1.23 2003/09/17 19:40:38 southa * Source conditioning upgrades * * Revision 1.22 2003/08/21 23:09:32 southa * Fixed file headers * * Revision 1.21 2003/01/20 10:45:31 southa * Singleton tidying * * Revision 1.20 2003/01/18 13:34:00 southa * Created MushcoreSingleton * * Revision 1.19 2003/01/17 13:30:41 southa * Source conditioning and build fixes * * Revision 1.18 2003/01/17 12:20:41 southa * Fixed auto_ptr duplication * * Revision 1.17 2003/01/16 15:58:02 southa * Mustl exception handling * * Revision 1.16 2003/01/16 12:03:55 southa * Platform and invalid socket fixes * * Revision 1.15 2003/01/14 20:46:12 southa * Post data handling * * Revision 1.14 2003/01/14 17:38:22 southa * Mustl web configuration * * Revision 1.13 2003/01/13 23:05:22 southa * Mustl test application * * Revision 1.12 2003/01/13 16:50:50 southa * win32 support * * Revision 1.11 2003/01/13 15:01:20 southa * Fix Mustl command line build * * Revision 1.10 2003/01/12 17:33:01 southa * Mushcore work * * Revision 1.9 2003/01/11 17:58:15 southa * Mustl fixes * * Revision 1.8 2003/01/09 14:57:08 southa * Created Mushcore * * Revision 1.7 2003/01/07 17:13:45 southa * Fixes for gcc 3.1 * * Revision 1.6 2002/12/29 21:00:00 southa * More build fixes * * Revision 1.5 2002/12/29 20:30:57 southa * Work for gcc 3.1 build * * Revision 1.4 2002/12/20 13:17:46 southa * Namespace changes, licence changes and source conditioning * * Revision 1.3 2002/12/17 12:53:34 southa * Mustl library * * Revision 1.2 2002/12/12 18:38:25 southa * Mustl separation * * Revision 1.14 2002/11/23 14:39:06 southa * Store ports in network order * * Revision 1.13 2002/11/22 11:42:07 southa * Added developer controls * * Revision 1.12 2002/11/18 14:11:04 southa * win32 support * * Revision 1.11 2002/11/15 11:47:56 southa * Web processing and error handling * * Revision 1.10 2002/11/14 11:40:28 southa * Configuration handling * * Revision 1.9 2002/11/12 18:02:13 southa * POST handling and handlepostvalues command * * Revision 1.8 2002/11/12 17:05:01 southa * Tidied localweb server * * Revision 1.7 2002/11/12 11:49:22 southa * Initial MHTML processing * * Revision 1.6 2002/11/08 11:54:40 southa * Web fixes * * Revision 1.5 2002/11/08 11:29:24 southa * Web fixes and debug * * Revision 1.4 2002/11/08 00:15:31 southa * Fixed errors * * Revision 1.3 2002/11/07 00:53:37 southa * localweb work * * Revision 1.2 2002/11/06 14:16:57 southa * Basic web server * * Revision 1.1 2002/11/05 18:15:17 southa * Web server * */ #include "MustlWebLink.h" #include "Mustl.h" #include "MustlHTTP.h" #include "MustlPlatform.h" #include "MustlSTL.h" #include "MustlMushcore.h" using namespace Mustl; using namespace std; MUSHCORE_DATA_INSTANCE(MustlWebLink); string MustlWebLink::m_webPath=""; MustlWebLink::MustlWebLink(tSocket inSocket) : m_receiveState(kReceiveInitial), m_tcpSocket(MustlPlatform::InvalidSocketValueGet()), m_linkErrors(0), m_isDead(false) { // I am the server end of the link try { m_tcpSocket = inSocket; MustlPlatform::SocketNonBlockingSet(m_tcpSocket); } catch (...) { MustlPlatform::SocketClose(inSocket); throw; } m_linkState=kLinkStateNew; m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); m_creationMsec=m_currentMsec; m_lastAccessMsec=m_currentMsec; // Not used } MustlWebLink::~MustlWebLink() { MustlLog::Sgl().WebLog() << "Closing web link" << endl; try { Disconnect(); } catch (exception& e) { MustlLog::Sgl().WebLog() << "~MustlWebLink exception: " << e.what() << endl; } } void MustlWebLink::Disconnect(void) { if (m_tcpSocket != MustlPlatform::InvalidSocketValueGet()) { MustlPlatform::SocketClose(m_tcpSocket); m_tcpSocket=MustlPlatform::InvalidSocketValueGet(); } m_isDead = true; } void MustlWebLink::Tick(void) { m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); } bool MustlWebLink::IsDead(void) { m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); if (m_isDead || m_currentMsec > m_creationMsec + kLinkLifetime || m_linkErrors > kErrorLimit) { return true; } return false; } bool MustlWebLink::Receive(string& outStr) { if (m_isDead) return false; U8 byte='-'; int result; outStr=""; do { try { result=MustlPlatform::TCPReceive(m_tcpSocket, &byte, 1); } catch (MustlPermanentFail &e) { (void) e; Disconnect(); throw; } catch (MustlTemporaryFail &e) { (void) e; ++m_linkErrors; throw; } if (result == 1) { outStr += byte; if (byte == 0xa) break; } } while (result > 0); // MustlLog::Sgl().WebLog() << "Received " << MustlUtils::MakePrintable(outStr) << endl; return (outStr.size() != 0); } void MustlWebLink::Send(MustlData& ioData) { if (m_isDead) { throw(MustlFail("Attempt to send on dead WebLink")); } try { U32 sendSize = ioData.ReadSizeGet(); MustlPlatform::TCPSend(m_tcpSocket, ioData.ReadPtrGet(), sendSize); ioData.ReadPosAdd(sendSize); } catch (MustlPermanentFail &e) { (void) e; Disconnect(); throw; } catch (MustlTemporaryFail &e) { (void) e; ++m_linkErrors; throw; } // MustlLog::Sgl().WebLog() << "Sending " << ioData << endl; } void MustlWebLink::Send(const string& inStr) { MustlData netData;; netData.Write(inStr); Send(netData); } void MustlWebLink::Send(istream& ioStream) { MustlData netData; while (ioStream.good() && !ioStream.eof()) { netData.PrepareForWrite(); ioStream.read(reinterpret_cast<char *>(netData.WritePtrGet()), netData.WriteSizeGet()); U32 length=ioStream.gcount(); netData.WritePosAdd(length); if (length == 0) break; } Send(netData); } void MustlWebLink::ReceivedProcess(const string& inStr) { switch (m_receiveState) { case kReceiveInitial: { if (inStr.substr(0,3) == "GET") { m_requestLine = inStr; m_requestType = kRequestGet; } else if (inStr.substr(0,4) == "POST") { m_requestLine = inStr; m_requestType = kRequestPost; } } m_receiveState = kReceiveHeaders; break; case kReceiveHeaders: { bool lineEnd=false; if (inStr.size() > 0 && (inStr[0] == 0xd || inStr[0] == 0xa)) { lineEnd=true; } switch (m_requestType) { case kRequestGet: if (lineEnd) { GetProcess(m_requestLine.substr(4)); m_receiveState = kReceiveInitial; } break; case kRequestPost: if (lineEnd) { m_receiveState = kReceiveBody; } break; default: SendErrorPage("Unrecognised request"); break; } } break; case kReceiveBody: { switch (m_requestType) { case kRequestGet: throw(MustlFail("Bad receive state for GET")); break; case kRequestPost: PostProcess(inStr); GetProcess(m_requestLine.substr(5)); break; default: SendErrorPage("Unrecognised request"); break; } } break; default: throw(MustlFail("Bad value for m_receiveState")); break; } } void MustlWebLink::GetProcess(const string& inFilename) { string localFilename; U32 dotCount=0; U32 slashCount=0; MustlLog::Sgl().WebLog() << "Serving fetch request for " << MustlUtils::MakePrintable(inFilename) << endl; try { for (U32 i=0; i<inFilename.size(); ++i) { U8 byte=inFilename[i]; if (byte == '.') { if (dotCount > 0) { throw(MustlFail("Bad filename (dots)")); } ++dotCount; localFilename+=byte; } if (byte == '/') { if (slashCount > 0) { throw(MustlFail("Bad filename (slashes)")); } ++slashCount; } if (byte >= 'a' && byte <= 'z') { localFilename+=byte; } if (byte <= ' ') { break; } } if (localFilename == "") localFilename = "index.html"; if (localFilename == "test.html") { SendTestPage(); } else { if (m_webPath == "") { const MushcoreScalar *pScalar; if (MushcoreGlobalConfig::Sgl().GetIfExists(pScalar, "MUSTL_WEB_PATH")) { m_webPath = pScalar->StringGet(); } } if (m_webPath == "") { throw(MustlFail("Path to web files (MUSTL_WEB_PATH) not set")); } localFilename = m_webPath+"/"+localFilename; SendFile(localFilename); } } catch (MushcoreNonFatalFail &e) { MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl; if (!m_isDead) { try { SendErrorPage(e.what()); } catch (MushcoreNonFatalFail &e2) { MustlLog::Sgl().WebLog() << "Exception sending error page: " << e2.what() << endl; } } } } void MustlWebLink::PostProcess(const string& inValues) { try { if (inValues.find("'") != inValues.npos) { throw(MustlFail("Invalid POST values")); } MushcoreCommand command(string("mustlpostvalues('")+inValues+"')"); command.Execute(); } catch (MushcoreNonFatalFail &e) { MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl; } } void MustlWebLink::SendFile(const string& inFilename) { bool processFile=false; ifstream fileStream(inFilename.c_str()); if (!fileStream) { throw(MustlFail("File not found: "+inFilename)); } MustlHTTP http; http.Reply200(); string::size_type dotPos = inFilename.rfind('.'); if (dotPos == string::npos) { throw(MustlFail("Unknown file type: "+inFilename)); } string fileTypeStr = inFilename.substr(dotPos+1); if (fileTypeStr == "html") { http.ContentTypeHTML(); } else if (fileTypeStr == "mhtml") { http.ContentTypeHTML(); processFile=true; } else if (fileTypeStr == "jpg" || fileTypeStr == "jpeg") { http.AllowCachingSet(); http.ContentType("image/jpeg"); } else if (fileTypeStr == "tif" || fileTypeStr == "tiff") { http.AllowCachingSet(); http.ContentType("image/tiff"); } else if (fileTypeStr == "png") { http.AllowCachingSet(); http.ContentType("image/png"); } else if (fileTypeStr == "css") { http.AllowCachingSet(); http.ContentType("text/css"); } else { throw(MustlFail("Unknown file type: "+fileTypeStr)); } if (processFile) { SendMHTML(fileStream, http); } else { http.Endl(); MustlData netData; http.ContentGet(netData); Send(netData); Send(fileStream); } Disconnect(); } void MustlWebLink::SendMHTML(istream& ioStream, MustlHTTP& ioHTTP) { MustlData netData; ioHTTP.Endl(); ioHTTP.ContentGet(netData); Send(netData); while (ioStream.good() && !ioStream.eof()) { string dataStr; getline(ioStream, dataStr, '\0'); U32 startPos; while (startPos = dataStr.find("<?mush"), startPos != dataStr.npos) { U32 endPos = dataStr.find("?>", startPos); if (endPos == dataStr.npos) { throw(MustlFail("Unterminated <?mush (expecting ?>)")); } string content=dataStr.substr(startPos+6, endPos - startPos - 6); // MustlLog::Sgl().WebLog() << "Found mush command '" << content << "'" << endl; try { MushcoreCommand command(content); ostringstream commandOutput; MushcoreEnvOutput envOutput(MushcoreEnv::Sgl(), commandOutput); command.Execute(); dataStr.replace(startPos, endPos - startPos + 2, commandOutput.str()); } catch (MushcoreNonFatalFail& e) { ostringstream errorOutput; errorOutput << "<pre>Command '" << content << "' failed: " << e.what() << "</pre>" << endl; dataStr.replace(startPos, endPos - startPos + 2, errorOutput.str()); } } Send(dataStr); } } void MustlWebLink::SendTestPage(void) { MustlHTTP http; http.Reply200(); http.ContentTypeHTML(); http.Endl(); http.Header(); http.Out() << "Mustl test page"; http.Endl(); http.Footer(); MustlData netData; http.ContentGet(netData); Send(netData); Disconnect(); } void MustlWebLink::SendErrorPage(const string& inText) { MustlHTTP http; http.Reply200(); http.ContentTypeHTML(); http.Endl(); http.Header(); http.Out() << "<h1>Error from Mustl web server</h1>"; http.Out() << "<p>" << inText << "</p>"; http.Out() << "<p><a target=\"_top\" href=\"/index.html\">Back to main page</a></p>"; http.Endl(); http.Footer(); MustlData netData; http.ContentGet(netData); Send(netData); Disconnect(); } void MustlWebLink::Print(ostream& ioOut) const { ioOut << "["; ioOut << "requestLine=" << m_requestLine; ioOut << ", requestType=" << m_requestType; ioOut << ", linkState=" << m_linkState; ioOut << ", receiveState=" << m_receiveState; ioOut << ", tcpSocket=" << m_tcpSocket; ioOut << ", currentMsec=" << m_currentMsec; ioOut << ", creationMsec=" << m_creationMsec; ioOut << ", lastAccessMsec=" << m_lastAccessMsec; ioOut << ", linkErrors=" << m_linkErrors; ioOut << ", isDead=" << m_isDead; ioOut << ", webPath=" << m_webPath; ioOut << "]"; }
24.934593
110
0.556456
mushware
dba2ac67d12ba2f8462c4ecd98d293c05d94c12b
8,588
cpp
C++
native/src/snappyclient/cpp/thrift/snappydata_struct_PrepareResult.cpp
SnappyDataInc/snappy-store
8f6a4b80fa14ffd0683752a03eeab311b545fbbd
[ "Apache-2.0" ]
38
2016-01-04T01:31:40.000Z
2020-04-07T06:35:36.000Z
native/src/snappyclient/cpp/thrift/snappydata_struct_PrepareResult.cpp
SnappyDataInc/snappy-store
8f6a4b80fa14ffd0683752a03eeab311b545fbbd
[ "Apache-2.0" ]
261
2016-01-07T09:14:26.000Z
2019-12-05T10:15:56.000Z
native/src/snappyclient/cpp/thrift/snappydata_struct_PrepareResult.cpp
SnappyDataInc/snappy-store
8f6a4b80fa14ffd0683752a03eeab311b545fbbd
[ "Apache-2.0" ]
22
2016-03-09T05:47:09.000Z
2020-04-02T17:55:30.000Z
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "impl/pch.h" #include <iosfwd> #include <thrift/Thrift.h> #include <thrift/TApplicationException.h> #include <thrift/protocol/TProtocol.h> #include <thrift/transport/TTransport.h> #include <functional> #include <memory> #include "snappydata_struct_PrepareResult.h" #include <algorithm> #include <ostream> #include <thrift/TToString.h> namespace io { namespace snappydata { namespace thrift { PrepareResult::~PrepareResult() noexcept { } void PrepareResult::__set_statementId(const int64_t val) { this->statementId = val; } void PrepareResult::__set_statementType(const int8_t val) { this->statementType = val; } void PrepareResult::__set_parameterMetaData(const std::vector<ColumnDescriptor> & val) { this->parameterMetaData = val; } void PrepareResult::__set_resultSetMetaData(const std::vector<ColumnDescriptor> & val) { this->resultSetMetaData = val; __isset.resultSetMetaData = true; } void PrepareResult::__set_warnings(const SnappyExceptionData& val) { this->warnings = val; __isset.warnings = true; } std::ostream& operator<<(std::ostream& out, const PrepareResult& obj) { obj.printTo(out); return out; } uint32_t PrepareResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_statementId = false; bool isset_statementType = false; bool isset_parameterMetaData = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->statementId); isset_statementId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BYTE) { xfer += iprot->readByte(this->statementType); isset_statementType = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->parameterMetaData.clear(); uint32_t _size258; ::apache::thrift::protocol::TType _etype261; xfer += iprot->readListBegin(_etype261, _size258); this->parameterMetaData.resize(_size258); uint32_t _i262; for (_i262 = 0; _i262 < _size258; ++_i262) { xfer += this->parameterMetaData[_i262].read(iprot); } xfer += iprot->readListEnd(); } isset_parameterMetaData = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->resultSetMetaData.clear(); uint32_t _size263; ::apache::thrift::protocol::TType _etype266; xfer += iprot->readListBegin(_etype266, _size263); this->resultSetMetaData.resize(_size263); uint32_t _i267; for (_i267 = 0; _i267 < _size263; ++_i267) { xfer += this->resultSetMetaData[_i267].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.resultSetMetaData = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->warnings.read(iprot); this->__isset.warnings = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_statementId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_statementType) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_parameterMetaData) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t PrepareResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("PrepareResult"); xfer += oprot->writeFieldBegin("statementId", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->statementId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("statementType", ::apache::thrift::protocol::T_BYTE, 2); xfer += oprot->writeByte(this->statementType); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("parameterMetaData", ::apache::thrift::protocol::T_LIST, 3); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->parameterMetaData.size())); std::vector<ColumnDescriptor> ::const_iterator _iter268; for (_iter268 = this->parameterMetaData.begin(); _iter268 != this->parameterMetaData.end(); ++_iter268) { xfer += (*_iter268).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); if (this->__isset.resultSetMetaData) { xfer += oprot->writeFieldBegin("resultSetMetaData", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->resultSetMetaData.size())); std::vector<ColumnDescriptor> ::const_iterator _iter269; for (_iter269 = this->resultSetMetaData.begin(); _iter269 != this->resultSetMetaData.end(); ++_iter269) { xfer += (*_iter269).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.warnings) { xfer += oprot->writeFieldBegin("warnings", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->warnings.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(PrepareResult &a, PrepareResult &b) { using ::std::swap; swap(a.statementId, b.statementId); swap(a.statementType, b.statementType); swap(a.parameterMetaData, b.parameterMetaData); swap(a.resultSetMetaData, b.resultSetMetaData); swap(a.warnings, b.warnings); swap(a.__isset, b.__isset); } PrepareResult::PrepareResult(const PrepareResult& other270) { statementId = other270.statementId; statementType = other270.statementType; parameterMetaData = other270.parameterMetaData; resultSetMetaData = other270.resultSetMetaData; warnings = other270.warnings; __isset = other270.__isset; } PrepareResult::PrepareResult( PrepareResult&& other271) { statementId = std::move(other271.statementId); statementType = std::move(other271.statementType); parameterMetaData = std::move(other271.parameterMetaData); resultSetMetaData = std::move(other271.resultSetMetaData); warnings = std::move(other271.warnings); __isset = std::move(other271.__isset); } PrepareResult& PrepareResult::operator=(const PrepareResult& other272) { statementId = other272.statementId; statementType = other272.statementType; parameterMetaData = other272.parameterMetaData; resultSetMetaData = other272.resultSetMetaData; warnings = other272.warnings; __isset = other272.__isset; return *this; } PrepareResult& PrepareResult::operator=(PrepareResult&& other273) { statementId = std::move(other273.statementId); statementType = std::move(other273.statementType); parameterMetaData = std::move(other273.parameterMetaData); resultSetMetaData = std::move(other273.resultSetMetaData); warnings = std::move(other273.warnings); __isset = std::move(other273.__isset); return *this; } void PrepareResult::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "PrepareResult("; out << "statementId=" << to_string(statementId); out << ", " << "statementType=" << to_string(statementType); out << ", " << "parameterMetaData=" << to_string(parameterMetaData); out << ", " << "resultSetMetaData="; (__isset.resultSetMetaData ? (out << to_string(resultSetMetaData)) : (out << "<null>")); out << ", " << "warnings="; (__isset.warnings ? (out << to_string(warnings)) : (out << "<null>")); out << ")"; } }}} // namespace
31.807407
129
0.655799
SnappyDataInc
dba4d9a746be6ba2d82434da36f3277e81013982
1,368
cpp
C++
copasi/MIRIAM/CRaptorInit.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/MIRIAM/CRaptorInit.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/MIRIAM/CRaptorInit.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <raptor.h> #include <string.h> #include <stdlib.h> #include "copasi/copasi.h" #include "CRaptorInit.h" // static bool CRaptorInit::Initialized = false; CRaptorInit::CRaptorInit() { if (!Initialized) { raptor_init(); Initialized = true; atexit(&raptor_finish); } } CRaptorInit::~CRaptorInit() {} // static bool CRaptorInit::isLocalURI(raptor_uri * pURI) { raptor_uri * pTmp = raptor_new_uri_for_retrieval(pURI); bool isLocal = (strcmp("/", (char *) raptor_uri_as_string(pTmp)) == 0); pRaptorFreeUri(pTmp); return isLocal; }
23.586207
72
0.712719
SzVarga
dba705a2bf4e02a3050ed8fd84f1169e358482c0
308
cpp
C++
aql/benchmark/lib_23/class_9.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_23/class_9.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_23/class_9.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
#include "class_9.h" #include "class_6.h" #include "class_7.h" #include "class_1.h" #include "class_3.h" #include "class_8.h" #include <lib_7/class_1.h> #include <lib_3/class_0.h> #include <lib_13/class_8.h> #include <lib_9/class_5.h> #include <lib_1/class_9.h> class_9::class_9() {} class_9::~class_9() {}
20.533333
27
0.711039
menify
dba7f28d32a79d69a3ee8f32882ba02fec1d9bac
2,841
cpp
C++
unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
2
2019-01-21T17:49:19.000Z
2019-06-20T03:01:06.000Z
unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
1
2022-01-27T16:05:47.000Z
2022-01-27T16:05:47.000Z
unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
null
null
null
/*================================================= * FileName: FishManager.cpp * * Created by: Komodoman * Project name: OceanProject * Unreal Engine version: 4.18.3 * Created on: 2015/03/17 * * Last Edited on: 2018/03/15 * Last Edited by: Felipe "Zoc" Silveira * * ------------------------------------------------- * For parts referencing UE4 code, the following copyright applies: * Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. * * Feel free to use this software in any commercial/free game. * Selling this as a plugin/item, in whole or part, is not allowed. * See "OceanProject\License.md" for full licensing details. * =================================================*/ #include "Fish/FishManager.h" #include "Fish/FlockFish.h" #include "Classes/Kismet/GameplayStatics.h" #include "Classes/Engine/World.h" AFishManager::AFishManager(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; } void AFishManager::Tick(float val) { setup(); if (attachToPlayer) { moveToPlayer(); } } void AFishManager::moveToPlayer() { if (player) this->SetActorLocation(player->GetActorLocation()); } float AFishManager::getMinZ() { return minZ; } float AFishManager::getMaxZ() { return maxZ; } void AFishManager::setup() { if (isSetup == false){ if (!areFishSpawned) { maxX = GetActorLocation().X + underwaterBoxLength; maxY = GetActorLocation().Y + underwaterBoxLength; minX = GetActorLocation().X - underwaterBoxLength; minY = GetActorLocation().Y - underwaterBoxLength; UWorld* const world = GetWorld(); int numFlocks = flockTypes.Num(); for (int i = 0; i < numFlocks; i++) { FVector spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ)); AFlockFish *leaderFish = NULL; for (int j = 0; j < numInFlock[i]; j++) { AFlockFish *aFish = Cast<AFlockFish>(world->SpawnActor(flockTypes[i])); aFish->isLeader = false; aFish->DebugMode = DebugMode; aFish->underwaterMax = FVector(maxX, maxY, maxZ); aFish->underwaterMin = FVector(minX, minY, minZ); aFish->underwaterBoxLength = underwaterBoxLength; spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ)); if (j == 0) { aFish->isLeader = true; leaderFish = aFish; } else if (leaderFish != NULL) { aFish->leader = leaderFish; } aFish->SetActorLocation(spawnLoc); } } areFishSpawned = true; } if (attachToPlayer) { TArray<AActor*> aPlayerList; UGameplayStatics::GetAllActorsOfClass(this, playerType, aPlayerList); if (aPlayerList.Num() > 0) { player = aPlayerList[0]; isSetup = true; } } else { isSetup = true; } } }
24.704348
124
0.641675
explore-astrum
dba88550b5a913aafa78706f1d035fa13c634cc4
8,051
cpp
C++
src/qt/outmessagelistpage.cpp
gtacoin-dev/gtacoin
f66f063b47ba973856c200074db1b95abf5ab794
[ "MIT" ]
null
null
null
src/qt/outmessagelistpage.cpp
gtacoin-dev/gtacoin
f66f063b47ba973856c200074db1b95abf5ab794
[ "MIT" ]
null
null
null
src/qt/outmessagelistpage.cpp
gtacoin-dev/gtacoin
f66f063b47ba973856c200074db1b95abf5ab794
[ "MIT" ]
null
null
null
#include "outmessagelistpage.h" #include "ui_messagelistpage.h" #include "guiutil.h" #include "messagetablemodel.h" #include "optionsmodel.h" #include "walletmodel.h" #include "newmessagedialog.h" #include "platformstyle.h" #include "messageinfodialog.h" #include "csvmodelwriter.h" #include "ui_interface.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QKeyEvent> #include <QSettings> #include <QMenu> using namespace std; OutMessageListPage::OutMessageListPage(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::MessageListPage), model(0), optionsModel(0) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->exportButton->setIcon(QIcon()); ui->newMessage->setIcon(QIcon()); ui->detailButton->setIcon(QIcon()); ui->copyMessage->setIcon(QIcon()); ui->refreshButton->setIcon(QIcon()); } else { ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/export")); ui->newMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add")); ui->detailButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/details")); ui->copyMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editcopy")); ui->refreshButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/refresh")); } ui->labelExplanation->setText(tr("These are Gtacoin messages you have sent.")); // Context menu actions QAction *copyGuidAction = new QAction(ui->copyMessage->text(), this); QAction *copySubjectAction = new QAction(tr("Copy Subject"), this); QAction *copyMessageAction = new QAction(tr("Copy Msg"), this); QAction *newMessageAction = new QAction(tr("New Msg"), this); QAction *detailsAction = new QAction(tr("Details"), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyGuidAction); contextMenu->addAction(copySubjectAction); contextMenu->addAction(copyMessageAction); contextMenu->addAction(detailsAction); contextMenu->addSeparator(); contextMenu->addAction(newMessageAction); // Connect signals for context menu actions connect(copyGuidAction, SIGNAL(triggered()), this, SLOT(on_copyGuid_clicked())); connect(copySubjectAction, SIGNAL(triggered()), this, SLOT(on_copySubject_clicked())); connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(on_copyMessage_clicked())); connect(newMessageAction, SIGNAL(triggered()), this, SLOT(on_newMessage_clicked())); connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_detailButton_clicked())); connect(detailsAction, SIGNAL(triggered()), this, SLOT(on_detailButton_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); } void OutMessageListPage::on_detailButton_clicked() { if(!ui->tableView->selectionModel()) return; QModelIndexList selection = ui->tableView->selectionModel()->selectedRows(); if(!selection.isEmpty()) { MessageInfoDialog dlg; QModelIndex origIndex = proxyModel->mapToSource(selection.at(0)); dlg.setModel(walletModel, model); dlg.loadRow(origIndex.row()); dlg.exec(); } } void OutMessageListPage::on_newMessage_clicked() { NewMessageDialog dlg(NewMessageDialog::NewMessage); dlg.setModel(walletModel, model); dlg.exec(); } OutMessageListPage::~OutMessageListPage() { delete ui; } void OutMessageListPage::showEvent ( QShowEvent * event ) { if(!walletModel) return; } void OutMessageListPage::setModel(WalletModel* walletModel, MessageTableModel *model) { this->model = model; this->walletModel = walletModel; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterRole(MessageTableModel::TypeRole); ui->tableView->setModel(proxyModel); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); // Set column widths ui->tableView->setColumnWidth(0, 75); //guid ui->tableView->setColumnWidth(1, 75); //time ui->tableView->setColumnWidth(2, 100); //from ui->tableView->setColumnWidth(3, 100); //to ui->tableView->setColumnWidth(4, 300); //subject ui->tableView->setColumnWidth(5, 300); //message ui->tableView->horizontalHeader()->setStretchLastSection(true); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created outmessage connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewMessage(QModelIndex,int,int))); selectionChanged(); } void OutMessageListPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void OutMessageListPage::on_refreshButton_clicked() { if(!model) return; model->refreshMessageTable(); } void OutMessageListPage::on_copyMessage_clicked() { GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Message); } void OutMessageListPage::on_copyGuid_clicked() { GUIUtil::copyEntryData(ui->tableView, MessageTableModel::GUID); } void OutMessageListPage::on_copySubject_clicked() { GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Subject); } void OutMessageListPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { ui->copyMessage->setEnabled(true); ui->detailButton->setEnabled(true); } else { ui->copyMessage->setEnabled(false); ui->detailButton->setEnabled(false); } } void OutMessageListPage::keyPressEvent(QKeyEvent * event) { if( event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter ) { on_newMessage_clicked(); event->accept(); } else QDialog::keyPressEvent( event ); } void OutMessageListPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Message Data"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn(tr("GUID"), MessageTableModel::GUID, Qt::EditRole); writer.addColumn(tr("Time"), MessageTableModel::Time, Qt::EditRole); writer.addColumn(tr("From"), MessageTableModel::From, Qt::EditRole); writer.addColumn(tr("To"), MessageTableModel::To, Qt::EditRole); writer.addColumn(tr("Subject"), MessageTableModel::Subject, Qt::EditRole); writer.addColumn(tr("Message"), MessageTableModel::Message, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file: ") + filename, QMessageBox::Abort, QMessageBox::Abort); } } void OutMessageListPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void OutMessageListPage::selectNewMessage(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, MessageTableModel::GUID, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newMessageToSelect)) { // Select row of newly created outmessage, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newMessageToSelect.clear(); } }
32.595142
113
0.708732
gtacoin-dev
dbab1ffd5252e094a29808633d5cf15a2e0a2f5d
1,450
cpp
C++
lib/src/DriverTimerLocal.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
1
2021-02-02T09:01:24.000Z
2021-02-02T09:01:24.000Z
lib/src/DriverTimerLocal.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
null
null
null
lib/src/DriverTimerLocal.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
2
2021-02-02T09:01:45.000Z
2021-10-02T13:08:16.000Z
#include "DriverTimerLocal.h" #include "HostImplementation.h" #ifdef GENERIC_TARGET_IMPLEMENTATION #include <GenericTarget.hpp> #include <TargetTime.hpp> #endif void CreateDriverTimerLocal(void){ #ifndef GENERIC_TARGET_IMPLEMENTATION #ifdef HOST_IMPLEMENTATION HostImplementation::CreateDriverTimerLocal(); #endif #endif } void DeleteDriverTimerLocal(void){ #ifndef GENERIC_TARGET_IMPLEMENTATION #ifdef HOST_IMPLEMENTATION HostImplementation::DeleteDriverTimerLocal(); #endif #endif } void OutputDriverTimerLocal(int32_t* nanoseconds, int32_t* second, int32_t* minute, int32_t* hour, int32_t* mday, int32_t* mon, int32_t* year, int32_t* wday, int32_t* yday, int32_t* isdst){ #ifdef GENERIC_TARGET_IMPLEMENTATION TargetTime t = GenericTarget::GetTargetTime(); *nanoseconds = t.local.nanoseconds; *second = t.local.second; *minute = t.local.minute; *hour = t.local.hour; *mday = t.local.mday; *mon = t.local.mon; *year = t.local.year; *wday = t.local.wday; *yday = t.local.yday; *isdst = t.local.isdst; #else #ifdef HOST_IMPLEMENTATION HostImplementation::OutputDriverTimerLocal(nanoseconds, second, minute, hour, mday, mon, year, wday, yday, isdst); #else *nanoseconds = 0; *second = 0; *minute = 0; *hour = 0; *mday = 1; *mon = 0; *year = 0; *wday = 1; *yday = 0; *isdst = -1; #endif #endif }
25.892857
189
0.678621
RobertDamerius
dbab996704340fbf821569adb51777c56f6a9c60
291
hpp
C++
src/PhongMaterial.hpp
lozog/CS488-raytracer
e566f8e2ca112088900b0320b7f3e2d5b2b370dd
[ "MIT" ]
null
null
null
src/PhongMaterial.hpp
lozog/CS488-raytracer
e566f8e2ca112088900b0320b7f3e2d5b2b370dd
[ "MIT" ]
null
null
null
src/PhongMaterial.hpp
lozog/CS488-raytracer
e566f8e2ca112088900b0320b7f3e2d5b2b370dd
[ "MIT" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include "Material.hpp" class PhongMaterial : public Material { public: PhongMaterial(const glm::vec3& kd, const glm::vec3& ks, double shininess); virtual ~PhongMaterial(); // private: glm::vec3 m_kd; glm::vec3 m_ks; double m_shininess; };
16.166667
76
0.701031
lozog
dbb0b606c652ee73670756441ba63cc120555c8e
34,309
cpp
C++
tests/TestLogMemoryUtilities.cpp
Nuovations/LogUtilities
8a367c33757dcf5a7df9ad5abbdc833e6cc21437
[ "Apache-2.0" ]
1
2021-03-02T20:55:22.000Z
2021-03-02T20:55:22.000Z
tests/TestLogMemoryUtilities.cpp
Nuovations/LogUtilities
8a367c33757dcf5a7df9ad5abbdc833e6cc21437
[ "Apache-2.0" ]
null
null
null
tests/TestLogMemoryUtilities.cpp
Nuovations/LogUtilities
8a367c33757dcf5a7df9ad5abbdc833e6cc21437
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Nuovation System Designs, LLC * 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. */ /** * @file * This file implements a unit test for Log::Utilities::Memory */ #include <LogUtilities/LogFilterAlways.hpp> #include <LogUtilities/LogFormatterPlain.hpp> #include <LogUtilities/LogGlobals.hpp> #include <LogUtilities/LogIndenterNone.hpp> #include <LogUtilities/LogLogger.hpp> #include <LogUtilities/LogMemoryUtilities.hpp> #include <LogUtilities/LogWriterDescriptor.hpp> #include <ostream> #include <regex> #include <string> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <cppunit/TestAssert.h> #include <cppunit/extensions/HelperMacros.h> #include "TestLogUtilitiesBasis.hpp" using namespace Nuovations; using namespace std; class TestMemoryLines { public: TestMemoryLines(const char * inMemoryLines); ~TestMemoryLines(void) = default; bool operator ==(const TestMemoryLines & inMemoryLines) const; size_t size(void) const; const std::string & operator ()(void) const; std::string & operator ()(void); std::ostream & operator <<(const TestMemoryLines & inMemoryLines) const; private: class MemoryLine { public: MemoryLine(void); bool operator ==(const MemoryLine & inMemoryLine) const; bool operator !=(const MemoryLine & inMemoryLine) const; MemoryLine & operator =(const MemoryLine & inMemoryLine); MemoryLine operator ++(int inDummy); public: size_t mAddressPosition; size_t mDataPosition; size_t mNewlinePosition; private: friend class TestMemoryLines; MemoryLine(const TestMemoryLines & inMemoryLines); MemoryLine(const TestMemoryLines & inMemoryLines, const size_t & inAddressPosition, const size_t & inDataPosition, const size_t & inNewlinePosition); const TestMemoryLines * mTestMemoryLines; }; MemoryLine begin(void) const; MemoryLine end(void) const; bool CompareAddress(const MemoryLine & inOurLine, const TestMemoryLines & inTheirLines, const MemoryLine & inTheirLine) const; bool CompareData(const MemoryLine & inOurLine, const TestMemoryLines & inTheirLines, const MemoryLine & inTheirLine) const; private: std::string mMemoryLines; }; class TestLogMemoryUtilities : public TestLogUtilitiesBasis { CPPUNIT_TEST_SUITE(TestLogMemoryUtilities); CPPUNIT_TEST(TestWithExplicitLoggerWithInvalidWidth); CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentAndLevel); CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentWithLevel); CPPUNIT_TEST(TestWithExplicitLoggerWithIndentAndLevel); CPPUNIT_TEST(TestWithImplicitLoggerWithInvalidWidth); CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentAndLevel); CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentWithLevel); CPPUNIT_TEST(TestWithImplicitLoggerWithIndentAndLevel); CPPUNIT_TEST_SUITE_END(); public: void TestWithExplicitLoggerWithInvalidWidth(void); void TestWithExplicitLoggerWithDefaultIndentAndLevel(void); void TestWithExplicitLoggerWithDefaultIndentWithLevel(void); void TestWithExplicitLoggerWithIndentAndLevel(void); void TestWithImplicitLoggerWithInvalidWidth(void); void TestWithImplicitLoggerWithDefaultIndentAndLevel(void); void TestWithImplicitLoggerWithDefaultIndentWithLevel(void); void TestWithImplicitLoggerWithIndentAndLevel(void); private: int CreateTemporaryFile(char * aPathBuffer); void CheckResults(const char * aPathBuffer, const TestMemoryLines & aExpected); static constexpr uint8_t kUint8x8s[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; static constexpr uint8_t kUint32x8s[32] = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f }; static constexpr uint16_t kUint16s[16] = { 0x3000, 0x3001, 0x3002, 0x3003, 0x3004, 0x3005, 0x3006, 0x3007, 0x3008, 0x3009, 0x300a, 0x300b, 0x300c, 0x300d, 0x300e, 0x300f }; static constexpr uint32_t kUint32s[8] = { 0x40000000, 0x40000001, 0x40000002, 0x40000003, 0x40000004, 0x40000005, 0x40000006, 0x40000007, }; static constexpr uint64_t kUint64s[8] = { 0x5000000000000000, 0x5000000000000001, 0x5000000000000002, 0x5000000000000003, 0x5000000000000004, 0x5000000000000005, 0x5000000000000006, 0x5000000000000007 }; static constexpr size_t kOffsets[2] = { 0, 3 }; static const TestMemoryLines kExpectedMemoryLines; }; constexpr uint8_t TestLogMemoryUtilities ::kUint8x8s[]; constexpr uint8_t TestLogMemoryUtilities ::kUint32x8s[]; constexpr uint16_t TestLogMemoryUtilities ::kUint16s[]; constexpr uint32_t TestLogMemoryUtilities ::kUint32s[]; constexpr uint64_t TestLogMemoryUtilities ::kUint64s[]; constexpr size_t TestLogMemoryUtilities ::kOffsets[]; const TestMemoryLines TestLogMemoryUtilities ::kExpectedMemoryLines = "<address>: 00 01 02 03 04 05 06 07 '................'\n" "<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n" "<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n" "<address>: 00 30 01 30 02 30 03 30 04 30 05 30 06 30 07 30 '.0.0.0.0.0.0.0.0'\n" "<address>: 00 00 00 40 01 00 00 40 '...@...@........'\n" "<address>: 00 00 00 00 00 00 00 50 '.......P........'\n" "<address>: 00 01 02 03 04 05 06 07 '................'\n" "<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n" "<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n" "<address>: 3000 3001 3002 3003 3004 3005 3006 3007 '.0.0.0.0.0.0.0.0'\n" "<address>: 3008 3009 300a 300b 300c 300d 300e 300f '.0.0.0.0.0.0.0.0'\n" "<address>: 40000000 40000001 40000002 40000003 '...@...@...@...@'\n" "<address>: 40000004 40000005 40000006 40000007 '...@...@...@...@'\n" "<address>: 5000000000000000 5000000000000001 '.......P.......P'\n" "<address>: 5000000000000002 5000000000000003 '.......P.......P'\n" "<address>: 5000000000000004 5000000000000005 '.......P.......P'\n" "<address>: 5000000000000006 5000000000000007 '.......P.......P'\n" "<address>: 03 04 05 06 07 '................'\n" "<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n" "<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n" "<address>: 03 30 04 30 05 30 06 30 07 30 08 30 09 '.0.0.0.0.0.0....'\n" "<address>: 03 00 00 40 04 '...@............'\n" "<address>: 03 00 00 00 00 '................'\n" "<address>: 03 04 05 06 07 '................'\n" "<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n" "<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n" "<address>: 3003 3004 3005 3006 3007 3008 3009 300a '.0.0.0.0.0.0.0.0'\n" "<address>: 300b 300c 300d 300e 300f '.0.0.0.0.0......'\n" "<address>: 40000003 40000004 40000005 40000006 '...@...@...@...@'\n" "<address>: 40000007 '...@............'\n" "<address>: 5000000000000003 5000000000000004 '.......P.......P'\n" "<address>: 5000000000000005 5000000000000006 '.......P.......P'\n" "<address>: 5000000000000007 '.......P........'\n"; TestMemoryLines :: TestMemoryLines(const char * inMemoryLines) : mMemoryLines(inMemoryLines) { return; } TestMemoryLines :: MemoryLine :: MemoryLine(void) : mAddressPosition(0), mDataPosition(0), mNewlinePosition(0), mTestMemoryLines(nullptr) { return; } TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines) : mAddressPosition(0), mDataPosition(0), mNewlinePosition(0), mTestMemoryLines(&inTestMemoryLines) { return; } TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines, const size_t & inAddressPosition, const size_t & inDataPosition, const size_t & inNewlinePosition) : mAddressPosition(inAddressPosition), mDataPosition(inDataPosition), mNewlinePosition(inNewlinePosition), mTestMemoryLines(&inTestMemoryLines) { return; } bool TestMemoryLines :: MemoryLine ::operator ==(const MemoryLine & inMemoryLine) const { bool lRetval; lRetval = ((mAddressPosition == inMemoryLine.mAddressPosition) && (mDataPosition == inMemoryLine.mDataPosition ) && (mNewlinePosition == inMemoryLine.mNewlinePosition) && (mTestMemoryLines == inMemoryLine.mTestMemoryLines)); return (lRetval); } bool TestMemoryLines :: MemoryLine :: operator !=(const MemoryLine & inMemoryLine) const { return (!(*this == inMemoryLine)); } TestMemoryLines::MemoryLine & TestMemoryLines :: MemoryLine :: operator =(const MemoryLine & inMemoryLine) { mAddressPosition = inMemoryLine.mAddressPosition; mDataPosition = inMemoryLine.mDataPosition; mNewlinePosition = inMemoryLine.mNewlinePosition; mTestMemoryLines = inMemoryLine.mTestMemoryLines; return (*this); } TestMemoryLines::MemoryLine TestMemoryLines :: MemoryLine :: operator ++(int inDummy) { static const char kColon = ':'; static const char kNewline = '\n'; const MemoryLine lCurrentLine = *this; const size_t lNextAddressPosition = mNewlinePosition + 1; (void)inDummy; // When this has incremented past the last line, ALL of the data // members should be set to string::npos. The find method covers // that for data and newline. We have to manually handle it for // the address. mAddressPosition = ((lNextAddressPosition >= mTestMemoryLines->size()) ? string::npos : lNextAddressPosition); mDataPosition = mTestMemoryLines->mMemoryLines.find(kColon, mAddressPosition); mNewlinePosition = mTestMemoryLines->mMemoryLines.find(kNewline, mAddressPosition); return (lCurrentLine); } TestMemoryLines::MemoryLine TestMemoryLines :: begin(void) const { static const char kColon = ':'; static const char kNewline = '\n'; MemoryLine lMemoryLine(*this); lMemoryLine.mAddressPosition = 0; lMemoryLine.mDataPosition = mMemoryLines.find(kColon, lMemoryLine.mAddressPosition); lMemoryLine.mNewlinePosition = mMemoryLines.find(kNewline, lMemoryLine.mAddressPosition); // If we found no data and no newline, then the lines are either // malformed or we are at the end. Regardless, return the end // iterator. Otherwise, return the start iterator. if ((lMemoryLine.mDataPosition == string::npos) && (lMemoryLine.mNewlinePosition == string::npos)) { return (end()); } else { return (lMemoryLine); } } TestMemoryLines::MemoryLine TestMemoryLines :: end(void) const { const MemoryLine kLastMemoryLine(*this, string::npos, string::npos, string::npos); return (kLastMemoryLine); } bool TestMemoryLines :: CompareAddress(const MemoryLine & inOurLine, const TestMemoryLines & inTheirLines, const MemoryLine & inTheirLine) const { const auto ourAddressIteratorBegin = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mAddressPosition); const auto ourAddressIteratorEnd = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mDataPosition); const auto theirAddressIteratorBegin = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mAddressPosition); const auto theirAddressIteratorEnd = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mDataPosition); const regex lRegex("(<address>|0x[[:xdigit:]]{4,16})"); bool lRetval = true; if (!regex_match(ourAddressIteratorBegin, ourAddressIteratorEnd, lRegex) || !regex_match(theirAddressIteratorBegin, theirAddressIteratorEnd, lRegex)) { lRetval = false; } return (lRetval); } bool TestMemoryLines :: CompareData(const MemoryLine & inOurLine, const TestMemoryLines & inTheirLines, const MemoryLine & inTheirLine) const { const size_t ourDataLength = inOurLine.mNewlinePosition - inOurLine.mDataPosition; const size_t theirDataLength = inTheirLine.mNewlinePosition - inTheirLine.mDataPosition; int lCompare; lCompare = mMemoryLines.compare(inOurLine.mDataPosition, ourDataLength, inTheirLines.mMemoryLines, inTheirLine.mDataPosition, theirDataLength); return (lCompare == 0); } bool TestMemoryLines :: operator ==(const TestMemoryLines & inTheirLines) const { MemoryLine lOurLine; MemoryLine lTheirLine; bool lRetval = true; // Walk through each line, ours and theirs, comparing the address // portion for equivalence and comparing the data portion for // equality. lOurLine = begin(); lTheirLine = inTheirLines.begin(); while (lRetval) { const bool lOurEnd = (lOurLine == end()); const bool lTheirEnd = (lTheirLine == inTheirLines.end()); // If we are at our end but not theirs or vice versa, then we // have a line number mismatch and the lines, collectively are // not equivalent. if ((lOurEnd && !lTheirEnd) || (!lOurEnd && lTheirEnd)) { lRetval = false; break; } if (lOurEnd && lTheirEnd) { break; } // Check the address and the data portion lRetval = (CompareAddress(lOurLine, inTheirLines, lTheirLine) && CompareData(lOurLine, inTheirLines, lTheirLine)); // Get our and their next line lOurLine++; lTheirLine++; } return (lRetval); } size_t TestMemoryLines :: size(void) const { return (mMemoryLines.size()); } const std::string & TestMemoryLines :: operator ()(void) const { return (mMemoryLines); } std::string & TestMemoryLines :: operator ()(void) { return (mMemoryLines); } static std::ostream & operator <<(std::ostream & inStream, const TestMemoryLines & inMemoryLines) { const std::string & lString = (const std::string &)(inMemoryLines); inStream << lString; return (inStream); } namespace Detail { template <typename T, size_t N> constexpr size_t elementsof(const T (&)[N]) { return (N); } }; // namespace Detail CPPUNIT_TEST_SUITE_REGISTRATION(TestLogMemoryUtilities); void TestLogMemoryUtilities :: TestWithExplicitLoggerWithInvalidWidth(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Logger lLogger(lAlwaysFilter, lNoneIndenter, lPlainFormatter, lDescriptorWriter); for (auto lOffset : kOffsets) { static constexpr unsigned int kWidth = 3; // Default indent and level Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth); Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth); Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth); Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth); Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth); } } close(lDescriptor); CheckResults(lPathBuffer, ""); } void TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentAndLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Logger lLogger(lAlwaysFilter, lNoneIndenter, lPlainFormatter, lDescriptorWriter); for (auto lOffset : kOffsets) { // Default indent, level, and width Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // Default indent and level Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } void TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentWithLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { const Log::Level kLevel = 0; Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Logger lLogger(lAlwaysFilter, lNoneIndenter, lPlainFormatter, lDescriptorWriter); for (auto lOffset : kOffsets) { // Default indent with level and default width Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // Default indent with level Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } void TestLogMemoryUtilities :: TestWithExplicitLoggerWithIndentAndLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { const Log::Indent kIndent = 0; const Log::Level kLevel = 0; Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Logger lLogger(lAlwaysFilter, lNoneIndenter, lPlainFormatter, lDescriptorWriter); for (auto lOffset : kOffsets) { // With indent and level and default width Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // With indent and level Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } void TestLogMemoryUtilities :: TestWithImplicitLoggerWithInvalidWidth(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Debug().SetFilter(lAlwaysFilter); Log::Debug().SetIndenter(lNoneIndenter); Log::Debug().SetFormatter(lPlainFormatter); Log::Debug().SetWriter(lDescriptorWriter); for (auto lOffset : kOffsets) { static constexpr unsigned int kWidth = 3; // Default indent and level Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth); Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth); Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth); Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth); Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth); } } close(lDescriptor); CheckResults(lPathBuffer, ""); } void TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentAndLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Debug().SetFilter(lAlwaysFilter); Log::Debug().SetIndenter(lNoneIndenter); Log::Debug().SetFormatter(lPlainFormatter); Log::Debug().SetWriter(lDescriptorWriter); for (auto lOffset : kOffsets) { // Default indent, level, and width Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // Default indent and level Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } void TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentWithLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { const Log::Level kLevel = 0; Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Debug().SetFilter(lAlwaysFilter); Log::Debug().SetIndenter(lNoneIndenter); Log::Debug().SetFormatter(lPlainFormatter); Log::Debug().SetWriter(lDescriptorWriter); for (auto lOffset : kOffsets) { // Default indent with level and default width Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // Default indent with level Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } void TestLogMemoryUtilities :: TestWithImplicitLoggerWithIndentAndLevel(void) { Log::Filter::Always lAlwaysFilter; Log::Indenter::None lNoneIndenter; Log::Formatter::Plain lPlainFormatter; char lPathBuffer[PATH_MAX]; int lDescriptor; lDescriptor = CreateTemporaryFile(lPathBuffer); CPPUNIT_ASSERT(lDescriptor > 0); { const Log::Indent kIndent = 0; const Log::Level kLevel = 0; Log::Writer::Descriptor lDescriptorWriter(lDescriptor); Log::Debug().SetFilter(lAlwaysFilter); Log::Debug().SetIndenter(lNoneIndenter); Log::Debug().SetFormatter(lPlainFormatter); Log::Debug().SetWriter(lDescriptorWriter); for (auto lOffset : kOffsets) { // With indent and level and default width Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset); // With indent and level Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset])); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset])); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset])); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset])); Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset])); } } close(lDescriptor); CheckResults(lPathBuffer, kExpectedMemoryLines); } int TestLogMemoryUtilities :: CreateTemporaryFile(char * aPathBuffer) { static const char * const kTestName = "memory-utilities"; int lStatus; lStatus = CreateTemporaryFileFromName(kTestName, aPathBuffer); return (lStatus); } void TestLogMemoryUtilities :: CheckResults(const char * aPathBuffer, const TestMemoryLines & aExpected) { struct stat lStat; int lStatus; int lDescriptor; char * lBuffer; ssize_t lResidual; lStatus = stat(aPathBuffer, &lStat); CPPUNIT_ASSERT(lStatus == 0); lDescriptor = open(aPathBuffer, O_RDONLY); CPPUNIT_ASSERT(lDescriptor > 0); lBuffer = new char[static_cast<size_t>(lStat.st_size) + 1]; CPPUNIT_ASSERT(lBuffer != NULL); lResidual = read(lDescriptor, &lBuffer[0], static_cast<size_t>(lStat.st_size)); CPPUNIT_ASSERT_EQUAL(lStat.st_size, static_cast<off_t>(lResidual)); close(lDescriptor); lBuffer[static_cast<size_t>(lStat.st_size)] = '\0'; CPPUNIT_ASSERT_EQUAL(aExpected, TestMemoryLines(lBuffer)); delete [] lBuffer; lStatus = unlink(aPathBuffer); CPPUNIT_ASSERT(lStatus == 0); }
40.602367
162
0.635518
Nuovations
dbb0e1820c9150119aba27b89136bdfbc0b93966
20,078
cpp
C++
drape/texture_manager.cpp
Kazing/organicmaps
687a6e21c7bda306558fe177608835f35d1b5d14
[ "Apache-2.0" ]
null
null
null
drape/texture_manager.cpp
Kazing/organicmaps
687a6e21c7bda306558fe177608835f35d1b5d14
[ "Apache-2.0" ]
null
null
null
drape/texture_manager.cpp
Kazing/organicmaps
687a6e21c7bda306558fe177608835f35d1b5d14
[ "Apache-2.0" ]
null
null
null
#include "drape/texture_manager.hpp" #include "drape/gl_functions.hpp" #include "drape/font_texture.hpp" #include "drape/symbols_texture.hpp" #include "drape/static_texture.hpp" #include "drape/stipple_pen_resource.hpp" #include "drape/support_manager.hpp" #include "drape/texture_of_colors.hpp" #include "drape/tm_read_resources.hpp" #include "drape/utils/glyph_usage_tracker.hpp" #include "base/file_name_utils.hpp" #include "base/stl_helpers.hpp" #include <algorithm> #include <cstdint> #include <limits> #include <sstream> #include <string> #include <utility> #include <vector> namespace dp { namespace { uint32_t const kMaxTextureSize = 1024; uint32_t const kStippleTextureWidth = 512; /// @todo Should be equal with kMaxStipplePenLength? uint32_t const kMinStippleTextureHeight = 64; uint32_t const kMinColorTextureSize = 32; uint32_t const kGlyphsTextureSize = 1024; size_t const kInvalidGlyphGroup = std::numeric_limits<size_t>::max(); // Reserved for elements like RuleDrawer or other LineShapes. uint32_t const kReservedPatterns = 10; size_t const kReservedColors = 20; float const kGlyphAreaMultiplier = 1.2f; float const kGlyphAreaCoverage = 0.9f; std::string const kSymbolTextures[] = { "symbols" }; uint32_t const kDefaultSymbolsIndex = 0; void MultilineTextToUniString(TextureManager::TMultilineText const & text, strings::UniString & outString) { size_t cnt = 0; for (strings::UniString const & str : text) cnt += str.size(); outString.clear(); outString.reserve(cnt); for (strings::UniString const & str : text) outString.append(str.begin(), str.end()); } template <typename ToDo> void ParseColorsList(std::string const & colorsFile, ToDo toDo) { ReaderStreamBuf buffer(GetPlatform().GetReader(colorsFile)); std::istream is(&buffer); while (is.good()) { uint32_t color; is >> color; toDo(dp::Extract(color)); } } m2::PointU StipplePenTextureSize(size_t patternsCount, uint32_t maxTextureSize) { uint32_t const sz = base::NextPowOf2(static_cast<uint32_t>(patternsCount) + kReservedPatterns); // No problem if assert will fire here. Just pen texture will be 2x bigger :) //ASSERT_LESS_OR_EQUAL(sz, kMinStippleTextureHeight, (patternsCount)); uint32_t const stippleTextureHeight = std::min(maxTextureSize, std::max(sz, kMinStippleTextureHeight)); return m2::PointU(kStippleTextureWidth, stippleTextureHeight); } m2::PointU ColorTextureSize(size_t colorsCount, uint32_t maxTextureSize) { uint32_t const sz = static_cast<uint32_t>(floor(sqrt(colorsCount + kReservedColors))); // No problem if assert will fire here. Just color texture will be 2x bigger :) ASSERT_LESS_OR_EQUAL(sz, kMinColorTextureSize, (colorsCount)); uint32_t colorTextureSize = std::max(base::NextPowOf2(sz), kMinColorTextureSize); colorTextureSize *= ColorTexture::GetColorSizeInPixels(); colorTextureSize = std::min(maxTextureSize, colorTextureSize); return m2::PointU(colorTextureSize, colorTextureSize); } } // namespace TextureManager::TextureManager(ref_ptr<GlyphGenerator> glyphGenerator) : m_maxTextureSize(0) , m_maxGlypsCount(0) , m_glyphGenerator(glyphGenerator) { m_nothingToUpload.test_and_set(); } TextureManager::BaseRegion::BaseRegion() : m_info(nullptr) , m_texture(nullptr) {} bool TextureManager::BaseRegion::IsValid() const { return m_info != nullptr && m_texture != nullptr; } void TextureManager::BaseRegion::SetResourceInfo(ref_ptr<Texture::ResourceInfo> info) { m_info = info; } void TextureManager::BaseRegion::SetTexture(ref_ptr<Texture> texture) { m_texture = texture; } m2::PointF TextureManager::BaseRegion::GetPixelSize() const { if (!IsValid()) return m2::PointF(0.0f, 0.0f); m2::RectF const & texRect = m_info->GetTexRect(); return m2::PointF(texRect.SizeX() * m_texture->GetWidth(), texRect.SizeY() * m_texture->GetHeight()); } float TextureManager::BaseRegion::GetPixelHeight() const { if (!IsValid()) return 0.0f; return m_info->GetTexRect().SizeY() * m_texture->GetHeight(); } m2::RectF const & TextureManager::BaseRegion::GetTexRect() const { if (!IsValid()) { static m2::RectF nilRect(0.0f, 0.0f, 0.0f, 0.0f); return nilRect; } return m_info->GetTexRect(); } float TextureManager::GlyphRegion::GetOffsetX() const { ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ()); return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xOffset; } float TextureManager::GlyphRegion::GetOffsetY() const { ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ()); return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yOffset; } float TextureManager::GlyphRegion::GetAdvanceX() const { ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ()); return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xAdvance; } float TextureManager::GlyphRegion::GetAdvanceY() const { ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ()); return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yAdvance; } m2::PointU TextureManager::StippleRegion::GetMaskPixelSize() const { ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ()); return ref_ptr<StipplePenResourceInfo>(m_info)->GetMaskPixelSize(); } //uint32_t TextureManager::StippleRegion::GetPatternPixelLength() const //{ // ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ()); // return ref_ptr<StipplePenResourceInfo>(m_info)->GetPatternPixelLength(); //} void TextureManager::Release() { m_hybridGlyphGroups.clear(); m_symbolTextures.clear(); m_stipplePenTexture.reset(); m_colorTexture.reset(); m_trafficArrowTexture.reset(); m_hatchingTexture.reset(); m_smaaAreaTexture.reset(); m_smaaSearchTexture.reset(); m_glyphTextures.clear(); m_glyphManager.reset(); m_glyphGenerator->FinishGeneration(); m_isInitialized = false; m_nothingToUpload.test_and_set(); } bool TextureManager::UpdateDynamicTextures(ref_ptr<dp::GraphicsContext> context) { if (!HasAsyncRoutines() && m_nothingToUpload.test_and_set()) { auto const apiVersion = context->GetApiVersion(); if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3) { // For some reasons OpenGL can not update textures immediately. // Here we use some timeout to prevent rendering frozening. double const kUploadTimeoutInSeconds = 2.0; return m_uploadTimer.ElapsedSeconds() < kUploadTimeoutInSeconds; } if (apiVersion == dp::ApiVersion::Metal || apiVersion == dp::ApiVersion::Vulkan) return false; CHECK(false, ("Unsupported API version.")); } CHECK(m_isInitialized, ()); m_uploadTimer.Reset(); CHECK(m_colorTexture != nullptr, ()); m_colorTexture->UpdateState(context); CHECK(m_stipplePenTexture != nullptr, ()); m_stipplePenTexture->UpdateState(context); UpdateGlyphTextures(context); CHECK(m_textureAllocator != nullptr, ()); m_textureAllocator->Flush(); return true; } void TextureManager::UpdateGlyphTextures(ref_ptr<dp::GraphicsContext> context) { std::lock_guard<std::mutex> lock(m_glyphTexturesMutex); for (auto & texture : m_glyphTextures) texture->UpdateState(context); } bool TextureManager::HasAsyncRoutines() const { CHECK(m_glyphGenerator != nullptr, ()); return !m_glyphGenerator->IsSuspended(); } ref_ptr<Texture> TextureManager::AllocateGlyphTexture() { std::lock_guard<std::mutex> lock(m_glyphTexturesMutex); m2::PointU size(kGlyphsTextureSize, kGlyphsTextureSize); m_glyphTextures.push_back(make_unique_dp<FontTexture>(size, make_ref(m_glyphManager), m_glyphGenerator, make_ref(m_textureAllocator))); return make_ref(m_glyphTextures.back()); } void TextureManager::GetRegionBase(ref_ptr<Texture> tex, TextureManager::BaseRegion & region, Texture::Key const & key) { bool isNew = false; region.SetResourceInfo(tex != nullptr ? tex->FindResource(key, isNew) : nullptr); region.SetTexture(tex); ASSERT(region.IsValid(), ()); if (isNew) m_nothingToUpload.clear(); } void TextureManager::GetGlyphsRegions(ref_ptr<FontTexture> tex, strings::UniString const & text, int fixedHeight, TGlyphsBuffer & regions) { ASSERT(tex != nullptr, ()); std::vector<GlyphKey> keys; keys.reserve(text.size()); for (auto const & c : text) keys.emplace_back(GlyphKey(c, fixedHeight)); bool hasNew = false; auto resourcesInfo = tex->FindResources(keys, hasNew); ASSERT_EQUAL(text.size(), resourcesInfo.size(), ()); regions.reserve(resourcesInfo.size()); for (auto const & info : resourcesInfo) { GlyphRegion reg; reg.SetResourceInfo(info); reg.SetTexture(tex); ASSERT(reg.IsValid(), ()); regions.push_back(std::move(reg)); } if (hasNew) m_nothingToUpload.clear(); } uint32_t TextureManager::GetNumberOfUnfoundCharacters(strings::UniString const & text, int fixedHeight, HybridGlyphGroup const & group) const { uint32_t cnt = 0; for (auto const & c : text) { if (group.m_glyphs.find(std::make_pair(c, fixedHeight)) == group.m_glyphs.end()) cnt++; } return cnt; } void TextureManager::MarkCharactersUsage(strings::UniString const & text, int fixedHeight, HybridGlyphGroup & group) { for (auto const & c : text) group.m_glyphs.emplace(std::make_pair(c, fixedHeight)); } size_t TextureManager::FindHybridGlyphsGroup(strings::UniString const & text, int fixedHeight) { if (m_hybridGlyphGroups.empty()) { m_hybridGlyphGroups.push_back(HybridGlyphGroup()); return 0; } HybridGlyphGroup & group = m_hybridGlyphGroups.back(); bool hasEnoughSpace = true; if (group.m_texture != nullptr) hasEnoughSpace = group.m_texture->HasEnoughSpace(static_cast<uint32_t>(text.size())); // If we have got the only hybrid texture (in most cases it is) // we can omit checking of glyphs usage. if (hasEnoughSpace) { size_t const glyphsCount = group.m_glyphs.size() + text.size(); if (m_hybridGlyphGroups.size() == 1 && glyphsCount < m_maxGlypsCount) return 0; } // Looking for a hybrid texture which contains text entirely. for (size_t i = 0; i < m_hybridGlyphGroups.size() - 1; i++) { if (GetNumberOfUnfoundCharacters(text, fixedHeight, m_hybridGlyphGroups[i]) == 0) return i; } // Check if we can contain text in the last hybrid texture. uint32_t const unfoundChars = GetNumberOfUnfoundCharacters(text, fixedHeight, group); uint32_t const newCharsCount = static_cast<uint32_t>(group.m_glyphs.size()) + unfoundChars; if (newCharsCount >= m_maxGlypsCount || !group.m_texture->HasEnoughSpace(unfoundChars)) m_hybridGlyphGroups.push_back(HybridGlyphGroup()); return m_hybridGlyphGroups.size() - 1; } size_t TextureManager::FindHybridGlyphsGroup(TMultilineText const & text, int fixedHeight) { strings::UniString combinedString; MultilineTextToUniString(text, combinedString); return FindHybridGlyphsGroup(combinedString, fixedHeight); } void TextureManager::Init(ref_ptr<dp::GraphicsContext> context, Params const & params) { CHECK(!m_isInitialized, ()); m_resPostfix = params.m_resPostfix; m_textureAllocator = CreateAllocator(context); m_maxTextureSize = std::min(kMaxTextureSize, dp::SupportManager::Instance().GetMaxTextureSize()); auto const apiVersion = context->GetApiVersion(); if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3) GLFunctions::glPixelStore(gl_const::GLUnpackAlignment, 1); // Initialize symbols. for (auto const & texName : kSymbolTextures) { m_symbolTextures.push_back(make_unique_dp<SymbolsTexture>(context, m_resPostfix, texName, make_ref(m_textureAllocator))); } // Initialize static textures. m_trafficArrowTexture = make_unique_dp<StaticTexture>(context, "traffic-arrow", m_resPostfix, dp::TextureFormat::RGBA8, make_ref(m_textureAllocator)); m_hatchingTexture = make_unique_dp<StaticTexture>(context, "area-hatching", m_resPostfix, dp::TextureFormat::RGBA8, make_ref(m_textureAllocator)); // SMAA is not supported on OpenGL ES2. if (apiVersion != dp::ApiVersion::OpenGLES2) { m_smaaAreaTexture = make_unique_dp<StaticTexture>(context, "smaa-area", StaticTexture::kDefaultResource, dp::TextureFormat::RedGreen, make_ref(m_textureAllocator)); m_smaaSearchTexture = make_unique_dp<StaticTexture>(context, "smaa-search", StaticTexture::kDefaultResource, dp::TextureFormat::Alpha, make_ref(m_textureAllocator)); } // Initialize patterns (reserved ./data/patterns.txt lines count). std::set<PenPatternT> patterns; double const visualScale = params.m_visualScale; uint32_t rowsCount = 0; impl::ParsePatternsList(params.m_patterns, [&](buffer_vector<double, 8> const & pattern) { PenPatternT toAdd; for (double d : pattern) toAdd.push_back(impl::PatternFloat2Pixel(d * visualScale)); if (!patterns.insert(toAdd).second) return; if (IsTrianglePattern(toAdd)) { rowsCount = rowsCount + toAdd[2] + toAdd[3]; } else { ASSERT_EQUAL(toAdd.size(), 2, ()); ++rowsCount; } }); m_stipplePenTexture = make_unique_dp<StipplePenTexture>(StipplePenTextureSize(rowsCount, m_maxTextureSize), make_ref(m_textureAllocator)); LOG(LDEBUG, ("Patterns texture size =", m_stipplePenTexture->GetWidth(), m_stipplePenTexture->GetHeight())); ref_ptr<StipplePenTexture> stipplePenTex = make_ref(m_stipplePenTexture); for (auto const & p : patterns) stipplePenTex->ReservePattern(p); // Initialize colors (reserved ./data/colors.txt lines count). std::vector<dp::Color> colors; colors.reserve(512); ParseColorsList(params.m_colors, [&colors](dp::Color const & color) { colors.push_back(color); }); m_colorTexture = make_unique_dp<ColorTexture>(ColorTextureSize(colors.size(), m_maxTextureSize), make_ref(m_textureAllocator)); LOG(LDEBUG, ("Colors texture size =", m_colorTexture->GetWidth(), m_colorTexture->GetHeight())); ref_ptr<ColorTexture> colorTex = make_ref(m_colorTexture); for (auto const & c : colors) colorTex->ReserveColor(c); // Initialize glyphs. m_glyphManager = make_unique_dp<GlyphManager>(params.m_glyphMngParams); uint32_t const textureSquare = kGlyphsTextureSize * kGlyphsTextureSize; uint32_t const baseGlyphHeight = static_cast<uint32_t>(params.m_glyphMngParams.m_baseGlyphHeight * kGlyphAreaMultiplier); uint32_t const averageGlyphSquare = baseGlyphHeight * baseGlyphHeight; m_maxGlypsCount = static_cast<uint32_t>(ceil(kGlyphAreaCoverage * textureSquare / averageGlyphSquare)); m_isInitialized = true; m_nothingToUpload.clear(); } void TextureManager::OnSwitchMapStyle(ref_ptr<dp::GraphicsContext> context) { CHECK(m_isInitialized, ()); // Here we need invalidate only textures which can be changed in map style switch. // Now we update only symbol textures, if we need update other textures they must be added here. // For Vulkan we use m_texturesToCleanup to defer textures destroying. for (size_t i = 0; i < m_symbolTextures.size(); ++i) { ASSERT(m_symbolTextures[i] != nullptr, ()); ASSERT(dynamic_cast<SymbolsTexture *>(m_symbolTextures[i].get()) != nullptr, ()); ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]); if (context->GetApiVersion() != dp::ApiVersion::Vulkan) symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator)); else symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator), m_texturesToCleanup); } } void TextureManager::GetTexturesToCleanup(std::vector<drape_ptr<HWTexture>> & textures) { CHECK(m_isInitialized, ()); std::swap(textures, m_texturesToCleanup); } void TextureManager::GetSymbolRegion(std::string const & symbolName, SymbolRegion & region) { CHECK(m_isInitialized, ()); for (size_t i = 0; i < m_symbolTextures.size(); ++i) { ASSERT(m_symbolTextures[i] != nullptr, ()); ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]); if (symbolsTexture->IsSymbolContained(symbolName)) { GetRegionBase(symbolsTexture, region, SymbolsTexture::SymbolKey(symbolName)); region.SetTextureIndex(static_cast<uint32_t>(i)); return; } } LOG(LWARNING, ("Detected using of unknown symbol ", symbolName)); } bool TextureManager::HasSymbolRegion(std::string const & symbolName) const { CHECK(m_isInitialized, ()); for (size_t i = 0; i < m_symbolTextures.size(); ++i) { ASSERT(m_symbolTextures[i] != nullptr, ()); ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]); if (symbolsTexture->IsSymbolContained(symbolName)) return true; } return false; } void TextureManager::GetStippleRegion(PenPatternT const & pen, StippleRegion & region) { CHECK(m_isInitialized, ()); GetRegionBase(make_ref(m_stipplePenTexture), region, StipplePenKey(pen)); } void TextureManager::GetColorRegion(Color const & color, ColorRegion & region) { CHECK(m_isInitialized, ()); GetRegionBase(make_ref(m_colorTexture), region, ColorKey(color)); } void TextureManager::GetGlyphRegions(TMultilineText const & text, int fixedHeight, TMultilineGlyphsBuffer & buffers) { std::lock_guard<std::mutex> lock(m_calcGlyphsMutex); CalcGlyphRegions<TMultilineText, TMultilineGlyphsBuffer>(text, fixedHeight, buffers); } void TextureManager::GetGlyphRegions(strings::UniString const & text, int fixedHeight, TGlyphsBuffer & regions) { std::lock_guard<std::mutex> lock(m_calcGlyphsMutex); CalcGlyphRegions<strings::UniString, TGlyphsBuffer>(text, fixedHeight, regions); } uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture, strings::UniString const & text, int fixedHeight) const { if (texture == nullptr) return 0; ASSERT(dynamic_cast<FontTexture *>(texture.get()) != nullptr, ()); return static_cast<FontTexture *>(texture.get())->GetAbsentGlyphsCount(text, fixedHeight); } uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture, TMultilineText const & text, int fixedHeight) const { if (texture == nullptr) return 0; uint32_t count = 0; for (size_t i = 0; i < text.size(); ++i) count += GetAbsentGlyphsCount(texture, text[i], fixedHeight); return count; } bool TextureManager::AreGlyphsReady(strings::UniString const & str, int fixedHeight) const { CHECK(m_isInitialized, ()); return m_glyphManager->AreGlyphsReady(str, fixedHeight); } ref_ptr<Texture> TextureManager::GetSymbolsTexture() const { CHECK(m_isInitialized, ()); ASSERT(!m_symbolTextures.empty(), ()); return make_ref(m_symbolTextures[kDefaultSymbolsIndex]); } ref_ptr<Texture> TextureManager::GetTrafficArrowTexture() const { CHECK(m_isInitialized, ()); return make_ref(m_trafficArrowTexture); } ref_ptr<Texture> TextureManager::GetHatchingTexture() const { CHECK(m_isInitialized, ()); return make_ref(m_hatchingTexture); } ref_ptr<Texture> TextureManager::GetSMAAAreaTexture() const { CHECK(m_isInitialized, ()); return make_ref(m_smaaAreaTexture); } ref_ptr<Texture> TextureManager::GetSMAASearchTexture() const { CHECK(m_isInitialized, ()); return make_ref(m_smaaSearchTexture); } constexpr size_t TextureManager::GetInvalidGlyphGroup() { return kInvalidGlyphGroup; } } // namespace dp
32.436187
113
0.707839
Kazing
dbb248fe16302798afd7c52255e7ff9b70068f87
1,971
cpp
C++
tests/fingerprint/fingerprint_tests.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
9
2017-11-10T15:54:02.000Z
2021-04-15T20:57:29.000Z
libhardware/tests/fingerprint/fingerprint_tests.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
null
null
null
libhardware/tests/fingerprint/fingerprint_tests.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
7
2018-01-08T02:53:32.000Z
2020-10-15T13:01:46.000Z
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "fingerprint_test_fixtures.h" namespace tests { TEST_F(FingerprintDevice, isThereEnroll) { ASSERT_TRUE(NULL != fp_device()->enroll) << "enroll() function is not implemented"; } TEST_F(FingerprintDevice, isTherePreEnroll) { ASSERT_TRUE(NULL != fp_device()->pre_enroll) << "pre_enroll() function is not implemented"; } TEST_F(FingerprintDevice, isThereGetAuthenticatorId) { ASSERT_TRUE(NULL != fp_device()->get_authenticator_id) << "get_authenticator_id() function is not implemented"; } TEST_F(FingerprintDevice, isThereCancel) { ASSERT_TRUE(NULL != fp_device()->cancel) << "cancel() function is not implemented"; } TEST_F(FingerprintDevice, isThereRemove) { ASSERT_TRUE(NULL != fp_device()->remove) << "remove() function is not implemented"; } TEST_F(FingerprintDevice, isThereAuthenticate) { ASSERT_TRUE(NULL != fp_device()->authenticate) << "authenticate() function is not implemented"; } TEST_F(FingerprintDevice, isThereSetActiveGroup) { ASSERT_TRUE(NULL != fp_device()->set_active_group) << "set_active_group() function is not implemented"; } TEST_F(FingerprintDevice, isThereSetNotify) { ASSERT_TRUE(NULL != fp_device()->set_notify) << "set_notify() function is not implemented"; } } // namespace tests
31.285714
75
0.716388
lighthouse-os
dbb30ec722fa5128f3eb84b28860a9e5694ddd84
2,117
cpp
C++
kernels/plugins/hostctrl/tb_hostctrl.cpp
TristanLaan/ACCL
89b50a814c73571eb5c93d4c6a134328e3fa21c7
[ "Apache-2.0" ]
null
null
null
kernels/plugins/hostctrl/tb_hostctrl.cpp
TristanLaan/ACCL
89b50a814c73571eb5c93d4c6a134328e3fa21c7
[ "Apache-2.0" ]
null
null
null
kernels/plugins/hostctrl/tb_hostctrl.cpp
TristanLaan/ACCL
89b50a814c73571eb5c93d4c6a134328e3fa21c7
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* # Copyright (C) 2021 Xilinx, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # *******************************************************************************/ #include "hls_stream.h" #include "ap_int.h" #include<iostream> using namespace hls; using namespace std; void hostctrl( ap_uint<32> scenario, ap_uint<32> len, ap_uint<32> comm, ap_uint<32> root_src_dst, ap_uint<32> function, ap_uint<32> msg_tag, ap_uint<32> datapath_cfg, ap_uint<32> compression_flags, ap_uint<32> stream_flags, ap_uint<64> addra, ap_uint<64> addrb, ap_uint<64> addrc, stream<ap_uint<32>> &cmd, stream<ap_uint<32>> &sts ); int main(){ int nerrors = 0; ap_uint<64> addra, addrb, addrc; addra(31,0) = 5; addra(63,32) = 7; addrb(31,0) = 3; addrb(63,32) = 9; addrc(31,0) = 1; addrc(63,32) = 6; stream<ap_uint<32>> cmd; stream<ap_uint<32>> sts; sts.write(1); hostctrl(0, 1, 2, 3, 4, 5, 6, 7, 8, addra, addrb, addrc, cmd, sts); nerrors += (cmd.read() != 0); nerrors += (cmd.read() != 1); nerrors += (cmd.read() != 2); nerrors += (cmd.read() != 3); nerrors += (cmd.read() != 4); nerrors += (cmd.read() != 5); nerrors += (cmd.read() != 6); nerrors += (cmd.read() != 7); nerrors += (cmd.read() != 8); nerrors += (cmd.read() != addra(31,0)); nerrors += (cmd.read() != addra(63,32)); nerrors += (cmd.read() != addrb(31,0)); nerrors += (cmd.read() != addrb(63,32)); nerrors += (cmd.read() != addrc(31,0)); nerrors += (cmd.read() != addrc(63,32)); return nerrors; }
28.226667
82
0.585262
TristanLaan
dbb398f07349810c4f9c7b04daf8f7f776e97872
3,942
cpp
C++
main.cpp
jcalvarezj/snake
4c1ff055253e69c629967ce3f67048b11abeda22
[ "MIT" ]
3
2020-02-29T21:15:33.000Z
2021-12-27T18:21:02.000Z
main.cpp
jcalvarezj/snake
4c1ff055253e69c629967ce3f67048b11abeda22
[ "MIT" ]
null
null
null
main.cpp
jcalvarezj/snake
4c1ff055253e69c629967ce3f67048b11abeda22
[ "MIT" ]
3
2021-12-06T07:43:22.000Z
2022-02-19T10:38:22.000Z
/* * Snake game program using the SDL library * * @author J. Alvarez */ #include <iostream> #include <cstring> #include <vector> #include <time.h> #include <stdlib.h> #include "Snake.hpp" #include "Food.hpp" #include "Wall.hpp" #include "Screen.hpp" #include "SDL2/SDL.h" using namespace SnakeGame; bool holdGame(Screen & screen, int millis) { int startTime = SDL_GetTicks(); bool quit = false; while (SDL_GetTicks() - startTime < millis && !quit) { if(screen.processEvents() == Screen::Action::QUIT) quit = true; } return quit; } bool pauseGame(Screen & screen, bool & pause) { int startTime = SDL_GetTicks(); bool quit = false; while (!quit && pause) { int action = screen.processEvents(); switch (action) { case Screen::Action::QUIT: quit = true; break; case Screen::Action::PAUSE: pause = false; break; } } return quit; } void resetLevel(Snake & snake, Food & food, bool & starting) { snake.die(); snake.reset(); food = Food(); starting = true; } void createWalls(std::vector<Wall *> & walls) { const int N_HORIZONTAL = Screen::S_WIDTH / Wall::S_WALL_WIDTH; const int N_VERTICAL = Screen::S_HEIGHT / Wall::S_WALL_WIDTH - 2; for (int i = 0; i < N_HORIZONTAL; i++) { Wall * upperWall = new Wall(i * Wall::S_WALL_WIDTH, 0); Wall * lowerWall = new Wall(i * Wall::S_WALL_WIDTH, Screen::S_HEIGHT - 3 * Wall::S_WALL_WIDTH); walls.push_back(upperWall); walls.push_back(lowerWall); } for (int i = 1; i < N_VERTICAL - 1; i++) { Wall * leftmostWall = new Wall(0, i * Wall::S_WALL_WIDTH); Wall * rightmostWall = new Wall(Screen::S_WIDTH - Wall::S_WALL_WIDTH, i * Wall::S_WALL_WIDTH); walls.push_back(leftmostWall); walls.push_back(rightmostWall); } } void drawWalls(std::vector<Wall *> & walls, Screen & screen) { for (auto wall: walls) wall->draw(screen); } void freeWalls(std::vector<Wall *> & walls) { for (auto wall: walls) delete wall; walls.clear(); } int main(int argc, char ** argv) { srand(time(NULL)); Screen screen; Snake snake; Food food; std::vector<Wall *> walls; createWalls(walls); int score = 0; if (!screen.init()) { SDL_Log("Error initializing screen"); return -1; } bool quit = false; bool starting = true; bool pause = false; while (!quit && snake.m_lives > 0) { screen.clear(); snake.draw(screen); food.draw(screen); drawWalls(walls, screen); screen.update(score, snake.m_lives, false); if (starting) { quit = holdGame(screen, 1500); starting = false; } switch (screen.processEvents()) { case Screen::Action::QUIT: quit = true; break; case Screen::Action::PAUSE: pause = true; break; case Screen::Action::MOVE_UP: if(!snake.m_hasUpdated) snake.updateDirection(Snake::Direction::UP); break; case Screen::Action::MOVE_DOWN: if(!snake.m_hasUpdated) snake.updateDirection(Snake::Direction::DOWN); break; case Screen::Action::MOVE_LEFT: if(!snake.m_hasUpdated) snake.updateDirection(Snake::Direction::LEFT); break; case Screen::Action::MOVE_RIGHT: if(!snake.m_hasUpdated) snake.updateDirection(Snake::Direction::RIGHT); break; } if (pause) quit = pauseGame(screen, pause); int elapsed = SDL_GetTicks(); if (elapsed/10 % 6 == 0) { if (!snake.move()) resetLevel(snake, food, starting); else { if (snake.collidesWith(food)) { food = Food(); score += Food::S_VALUE; snake.addSection(); } for (auto wall: walls) if (snake.collidesWith(* wall)) resetLevel(snake, food, starting); for (int i = 1; i < snake.m_sections.size(); i++) if (snake.collidesWith(* snake.m_sections[i])) resetLevel(snake, food, starting); } } if (snake.m_lives == 0) { screen.clear(); screen.drawGameOver(); screen.update(score, snake.m_lives, true); holdGame(screen, 3000); } } freeWalls(walls); screen.close(); return 0; }
21.779006
71
0.645358
jcalvarezj
dbb483ea8fde9dc6114fe4803970c61c10d66a28
3,539
hpp
C++
include/mbgl/text/types.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
2
2017-02-28T22:41:54.000Z
2020-02-13T20:54:55.000Z
include/mbgl/text/types.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
include/mbgl/text/types.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
#ifndef MBGL_TEXT_TYPES #define MBGL_TEXT_TYPES #include <mbgl/util/vec.hpp> #include <mbgl/util/rect.hpp> #include <array> #include <vector> #include <boost/optional.hpp> namespace mbgl { typedef vec2<float> CollisionPoint; typedef vec2<float> CollisionAnchor; typedef std::array<float, 2> PlacementRange; typedef float CollisionAngle; typedef std::vector<CollisionAngle> CollisionAngles; typedef std::array<CollisionAngle, 2> CollisionRange; typedef std::vector<CollisionRange> CollisionList; typedef std::array<CollisionPoint, 4> CollisionCorners; struct CollisionRect { CollisionPoint tl; CollisionPoint br; inline explicit CollisionRect() {} inline explicit CollisionRect(CollisionPoint::Type ax, CollisionPoint::Type ay, CollisionPoint::Type bx, CollisionPoint::Type by) : tl(ax, ay), br(bx, by) {} inline explicit CollisionRect(const CollisionPoint &tl, const CollisionPoint &br) : tl(tl), br(br) {} }; // These are the glyph boxes that we want to have placed. struct GlyphBox { explicit GlyphBox() {} explicit GlyphBox(const CollisionRect &box, const CollisionAnchor &anchor, float minScale, float maxScale, float padding) : box(box), anchor(anchor), minScale(minScale), maxScale(maxScale), padding(padding) {} explicit GlyphBox(const CollisionRect &box, float minScale, float padding) : box(box), minScale(minScale), padding(padding) {} CollisionRect box; CollisionAnchor anchor; float minScale = 0.0f; float maxScale = std::numeric_limits<float>::infinity(); float padding = 0.0f; boost::optional<CollisionRect> hBox; }; typedef std::vector<GlyphBox> GlyphBoxes; // TODO: Transform the vec2<float>s to vec2<int16_t> to save bytes struct PlacedGlyph { explicit PlacedGlyph(const vec2<float> &tl, const vec2<float> &tr, const vec2<float> &bl, const vec2<float> &br, const Rect<uint16_t> &tex, float angle, const vec2<float> &anchor, float minScale, float maxScale) : tl(tl), tr(tr), bl(bl), br(br), tex(tex), angle(angle), anchor(anchor), minScale(minScale), maxScale(maxScale) {} vec2<float> tl, tr, bl, br; Rect<uint16_t> tex; float angle; vec2<float> anchor; float minScale, maxScale; }; typedef std::vector<PlacedGlyph> PlacedGlyphs; // These are the placed boxes contained in the rtree. struct PlacementBox { CollisionAnchor anchor; CollisionRect box; boost::optional<CollisionRect> hBox; PlacementRange placementRange = {{0.0f, 0.0f}}; float placementScale = 0.0f; float maxScale = std::numeric_limits<float>::infinity(); float padding = 0.0f; }; struct PlacementProperty { explicit PlacementProperty() {} explicit PlacementProperty(float zoom, const PlacementRange &rotationRange) : zoom(zoom), rotationRange(rotationRange) {} inline operator bool() const { return !std::isnan(zoom) && zoom != std::numeric_limits<float>::infinity() && rotationRange[0] != rotationRange[1]; } float zoom = std::numeric_limits<float>::infinity(); PlacementRange rotationRange = {{0.0f, 0.0f}}; }; } #endif
30.773913
95
0.626731
free1978
dbb543019697b06a8f366a7ce4db4d983912d996
1,550
cpp
C++
Tutorial2/main.cpp
asm128/gpftw
984eec9a0cb6047000dda98c03696592406154a8
[ "MIT" ]
1
2017-06-19T22:19:30.000Z
2017-06-19T22:19:30.000Z
Tutorial2/main.cpp
asm128/gpftw
984eec9a0cb6047000dda98c03696592406154a8
[ "MIT" ]
4
2017-06-16T23:25:37.000Z
2017-07-01T01:33:25.000Z
Tutorial2/main.cpp
asm128/gpftw
984eec9a0cb6047000dda98c03696592406154a8
[ "MIT" ]
null
null
null
// Tip: Hold Left ALT + SHIFT while tapping or holding the arrow keys in order to select multiple columns and write on them at once. // Also useful for copy & paste operations in which you need to copy a bunch of variable or function names and you can't afford the time of copying them one by one. // #include <stdio.h> // for printf() #include <windows.h> // for interacting with Windows with GetAsyncKeyState() // Define some functions to use from main(). These functions will contain our game code. void setup () { printf("- setup() called.\n" ); } void update () { printf("- update() called.\n" ); } void draw () { printf("- draw() called.\n" ); } int main () { setup(); // Call setup() int frameCounter = 0; // declare and initialize a variable of (int)eger type for keeping track of the number of frame since execution began. while( true ) { // Execute code between braces while the condition inside () evaluates to true. printf("Current frame number: %i\n", frameCounter); // Print the frame count. update (); // Update frame. draw (); // Render frame. if(GetAsyncKeyState(VK_ESCAPE)) // Check for escape key pressed and execute code between braces if the condition between () evaluates to "true". { break; // Exit while() loop. } Sleep(50); // Wait 50 milliseconds then continue executing frameCounter = frameCounter + 1; // increase our frame counter by 1 } return 0; // Exit from the function returning an (int)eger. }
51.666667
165
0.66
asm128
dbb6b7c9b79e37132c4742471b20dd37a9310a52
7,343
hpp
C++
include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Linq.Expressions.Interpreter.Instruction #include "System/Linq/Expressions/Interpreter/Instruction.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Forward declaring namespace: System::Linq::Expressions::Interpreter namespace System::Linq::Expressions::Interpreter { // Forward declaring type: InterpretedFrame class InterpretedFrame; } // Completed forward declares // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Forward declaring type: NewArrayInstruction class NewArrayInstruction; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Linq::Expressions::Interpreter::NewArrayInstruction); DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::NewArrayInstruction*, "System.Linq.Expressions.Interpreter", "NewArrayInstruction"); // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: System.Linq.Expressions.Interpreter.NewArrayInstruction // [TokenAttribute] Offset: FFFFFFFF class NewArrayInstruction : public ::System::Linq::Expressions::Interpreter::Instruction { public: public: // private readonly System.Type _elementType // Size: 0x8 // Offset: 0x10 ::System::Type* elementType; // Field size check static_assert(sizeof(::System::Type*) == 0x8); public: // Creating conversion operator: operator ::System::Type* constexpr operator ::System::Type*() const noexcept { return elementType; } // Get instance field reference: private readonly System.Type _elementType [[deprecated("Use field access instead!")]] ::System::Type*& dyn__elementType(); // System.Void .ctor(System.Type elementType) // Offset: 0xE941CC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NewArrayInstruction* New_ctor(::System::Type* elementType) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NewArrayInstruction::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NewArrayInstruction*, creationType>(elementType))); } // public override System.Int32 get_ConsumedStack() // Offset: 0xE941F8 // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Int32 Instruction::get_ConsumedStack() int get_ConsumedStack(); // public override System.Int32 get_ProducedStack() // Offset: 0xE94200 // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Int32 Instruction::get_ProducedStack() int get_ProducedStack(); // public override System.String get_InstructionName() // Offset: 0xE94208 // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.String Instruction::get_InstructionName() ::StringW get_InstructionName(); // public override System.Int32 Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame) // Offset: 0xE9424C // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Int32 Instruction::Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame) int Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame); }; // System.Linq.Expressions.Interpreter.NewArrayInstruction #pragma pack(pop) static check_size<sizeof(NewArrayInstruction), 16 + sizeof(::System::Type*)> __System_Linq_Expressions_Interpreter_NewArrayInstructionSizeCheck; static_assert(sizeof(NewArrayInstruction) == 0x18); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack // Il2CppName: get_ConsumedStack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ConsumedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack // Il2CppName: get_ProducedStack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ProducedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName // Il2CppName: get_InstructionName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_InstructionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::Run // Il2CppName: Run template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)(::System::Linq::Expressions::Interpreter::InterpretedFrame*)>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::Run)> { static const MethodInfo* get() { static auto* frame = &::il2cpp_utils::GetClassFromName("System.Linq.Expressions.Interpreter", "InterpretedFrame")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "Run", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{frame}); } };
57.367188
269
0.759226
v0idp
dbb81936f3b075c278b9f3a9d69dcf76e25f139a
8,454
cpp
C++
speech_recognition/cmusphinx-code/sphinxtrain/src/programs/g2p_eval/Phonetisaurus.cpp
Ohara124c41/TUB-MSc_Thesis
b1a2d5dc9c0c589a39019126cf7a5cc775baa288
[ "MIT" ]
1
2016-12-05T01:29:52.000Z
2016-12-05T01:29:52.000Z
speech_recognition/cmusphinx-code/sphinxtrain/src/programs/g2p_eval/Phonetisaurus.cpp
Ohara124c41/TUB-MSc_Thesis
b1a2d5dc9c0c589a39019126cf7a5cc775baa288
[ "MIT" ]
null
null
null
speech_recognition/cmusphinx-code/sphinxtrain/src/programs/g2p_eval/Phonetisaurus.cpp
Ohara124c41/TUB-MSc_Thesis
b1a2d5dc9c0c589a39019126cf7a5cc775baa288
[ "MIT" ]
1
2016-12-03T04:06:45.000Z
2016-12-03T04:06:45.000Z
/* * Phonetisaurus.cpp * Copyright (c) [2012-], Josef Robert Novak 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. * */ #include <stdio.h> #include <string> #include <fst/fstlib.h> #include <iostream> #include <set> #include <algorithm> #include "../g2p_train/FstPathFinder.hpp" #include "Phonetisaurus.hpp" using namespace fst; Phonetisaurus::Phonetisaurus() { //Default constructor } Phonetisaurus::Phonetisaurus(const char *_g2pmodel_file) { //Base constructor. Load the clusters file, the models and setup shop. eps = "<eps>"; sb = "<s>"; se = "</s>"; skip = "_"; skipSeqs.insert(eps); skipSeqs.insert(sb); skipSeqs.insert(se); skipSeqs.insert(skip); skipSeqs.insert("-"); g2pmodel = StdVectorFst::Read(_g2pmodel_file); isyms = (SymbolTable *) g2pmodel->InputSymbols(); tie = isyms->Find(1); //The separator symbol is reserved for index 1 osyms = (SymbolTable *) g2pmodel->OutputSymbols(); loadClusters(); epsMapper = makeEpsMapper(); //We need make sure the g2pmodel is arcsorted ILabelCompare<StdArc> icomp; ArcSort(g2pmodel, icomp); } void Phonetisaurus::loadClusters() { /* Load the clusters file containing the list of subsequences generated during multiple-to-multiple alignment */ for (size_t i = 2; i < isyms->NumSymbols(); i++) { string sym = isyms->Find(i); if (sym.find(tie) != string::npos) { char *tmpstring = (char *) sym.c_str(); char *p = strtok(tmpstring, tie.c_str()); vector <string> cluster; while (p) { cluster.push_back(p); p = strtok(NULL, tie.c_str()); } clusters[cluster] = i; } } return; } StdVectorFst Phonetisaurus::makeEpsMapper() { /* Generate a mapper FST to transform unwanted output symbols to the epsilon symbol. This can be used to remove unwanted symbols from the final result, but in tests was 7x slower than manual removal via the FstPathFinder object. */ StdVectorFst mfst; mfst.AddState(); mfst.SetStart(0); set <string>::iterator sit; for (size_t i = 0; i < osyms->NumSymbols(); i++) { string sym = osyms->Find(i); sit = skipSeqs.find(sym); if (sit != skipSeqs.end()) mfst.AddArc(0, StdArc(i, 0, 0, 0)); else mfst.AddArc(0, StdArc(i, i, 0, 0)); } mfst.SetFinal(0, 0); ILabelCompare<StdArc> icomp; ArcSort(&mfst, icomp); mfst.SetInputSymbols(osyms); mfst.SetOutputSymbols(osyms); return mfst; } StdVectorFst Phonetisaurus::entryToFSA(vector <string> entry) { /* Transform an input spelling/pronunciation into an equivalent FSA, adding extra arcs as needed to accomodate clusters. */ StdVectorFst efst; efst.AddState(); efst.SetStart(0); efst.AddState(); efst.AddArc(0, StdArc(isyms->Find(sb), isyms->Find(sb), 0, 1)); size_t i = 0; //Build the basic FSA for (i = 0; i < entry.size(); i++) { efst.AddState(); string ch = entry[i]; efst.AddArc(i + 1, StdArc(isyms->Find(ch), isyms->Find(ch), 0, i + 2)); if (i == 0) continue; } //Add any cluster arcs map<vector<string>,int>::iterator it_i; for (it_i = clusters.begin(); it_i != clusters.end(); it_i++) { vector<string>::iterator it_j; vector<string>::iterator start = entry.begin(); vector<string> cluster = (*it_i).first; while (it_j != entry.end()) { it_j = search(start, entry.end(), cluster.begin(), cluster.end()); if (it_j != entry.end()) { efst.AddArc(it_j - entry.begin() + 1, StdArc((*it_i).second, //input symbol (*it_i).second, //output symbol 0, //weight it_j - entry.begin() + cluster.size() + 1 //destination state )); start = it_j + cluster.size(); } } } efst.AddState(); efst.AddArc(i + 1, StdArc(isyms->Find(se), isyms->Find(se), 0, i + 2)); efst.SetFinal(i + 2, 0); efst.SetInputSymbols(isyms); efst.SetOutputSymbols(isyms); return efst; } vector<PathData> Phonetisaurus::phoneticize(vector <string> entry, int nbest, int beam) { /* Generate pronunciation/spelling hypotheses for an input entry. */ StdVectorFst result; StdVectorFst epsMapped; StdVectorFst shortest; StdVectorFst efst = entryToFSA(entry); StdVectorFst smbr; Compose(efst, *g2pmodel, &result); Project(&result, PROJECT_OUTPUT); if (nbest > 1) { //This is a cheesy hack. ShortestPath(result, &shortest, beam); } else { ShortestPath(result, &shortest, 1); } RmEpsilon(&shortest); FstPathFinder pathfinder(skipSeqs); pathfinder.findAllStrings(shortest); return pathfinder.paths; } void printPath(PathData * path, string onepath, int k, ofstream * hypfile, string correct, string word, bool output_cost) { if (word != "") { if (k != 0) { *hypfile << word << "(" << (k + 1) << ")" << " "; } else { *hypfile << word << " "; } } if (output_cost) { if (path) { *hypfile << path->pathcost << " " << onepath; } else { *hypfile << "999.999 " << onepath; } } else { *hypfile << onepath; } if (correct != "") *hypfile << " " << correct; *hypfile << "\n"; } bool Phonetisaurus::printPaths(vector<PathData> paths, int nbest, ofstream * hypfile, string correct, string word, bool output_cost) { /* Convenience function to print out a path vector. Will print only the first N unique entries. */ set <string> seen; set <string>::iterator sit; int numseen = 0; string onepath; size_t k; bool empty_path = true; for (k = 0; k < paths.size(); k++) { if (k >= nbest) break; size_t j; for (j = 0; j < paths[k].path.size(); j++) { if (paths[k].path[j] != tie) replace(paths[k].path[j].begin(), paths[k].path[j].end(), *tie.c_str(), ' '); onepath += paths[k].path[j]; if (j != paths[k].path.size() - 1) onepath += " "; } if (onepath == "") { continue; } empty_path = false; printPath(&paths[k], onepath, k, hypfile, correct, word, output_cost); onepath = ""; } if (empty_path) { if (k == 0) { printPath(NULL, "-", 0, hypfile, correct, word, output_cost); } else { printPath(&paths[0], "-", 0, hypfile, correct, word, output_cost); } } return empty_path; }
27.359223
94
0.573338
Ohara124c41
dbb8b3d3a659d35a5e24a26da9e4bc0b452ee38f
417
hpp
C++
src/SettingsDialog.hpp
asamy/vendace
ed949d6c7546f3a70582a0354c68a17f26aef6cd
[ "MIT" ]
1
2020-05-02T06:47:48.000Z
2020-05-02T06:47:48.000Z
src/SettingsDialog.hpp
asamy/vendace
ed949d6c7546f3a70582a0354c68a17f26aef6cd
[ "MIT" ]
null
null
null
src/SettingsDialog.hpp
asamy/vendace
ed949d6c7546f3a70582a0354c68a17f26aef6cd
[ "MIT" ]
null
null
null
#ifndef SETTINGS_DIALOG_HPP #define SETTINGS_DIALOG_HPP #include <QDialog> #include "Settings.hpp" #include "ui_settings.h" class SettingsDialog : public QDialog { Q_OBJECT public: SettingsDialog(QWidget *parent); protected slots: void editorPathChanged(QString); void browseEditorPath(); private: Ui::SettingsDialog mUi; Settings mSettings; }; #endif
15.444444
40
0.681055
asamy
dbbef1d6a5f29ac9f34d29d7a967cdc71a42b1a7
934
hpp
C++
includes.hpp
ph-moura/Spending-Control
a87836db644e35ded695c7736b11b608ba95e8a8
[ "MIT" ]
null
null
null
includes.hpp
ph-moura/Spending-Control
a87836db644e35ded695c7736b11b608ba95e8a8
[ "MIT" ]
null
null
null
includes.hpp
ph-moura/Spending-Control
a87836db644e35ded695c7736b11b608ba95e8a8
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <QAbstractBarSeries> #include <QApplication> #include <QBoxLayout> #include <QClipboard> #include <QComboBox> #include <QDateEdit> #include <QDateTimeEdit> #include <QDebug> #include <QFileInfo> #include <QFormLayout> #include <QGridLayout> #include <QHBoxLayout> #include <QIcon> #include <QLabel> #include <QLineEdit> #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QObject> #include <QProgressBar> #include <QPushButton> #include <QResource> #include <QSlider> #include <QString> #include <QStringList> #include <QTableWidget> #include <QtCharts> #include <QtCore> #include <QTextEdit> #include <QTextStream> #include <QtGui> #include <QTimeEdit> #include <QtWidgets/QToolBar> #include <QVBoxLayout> #include <QWidget> #include <sstream> #include <string> #include <tuple> #include <vector> #pragma once
19.87234
29
0.75803
ph-moura
dbbf1c1c89d206b291bb86f06297c077d52ff671
4,812
cpp
C++
src/libclang/friend_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
src/libclang/friend_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
src/libclang/friend_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
// Copyright (C) 2017-2018 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <cppast/cpp_friend.hpp> #include <cppast/cpp_template.hpp> #include <cppast/cpp_template_parameter.hpp> #include "libclang_visitor.hpp" #include "parse_functions.hpp" using namespace cppast; std::unique_ptr<cpp_entity> detail::parse_cpp_friend(const detail::parse_context& context, const CXCursor& cur) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_FriendDecl, detail::assert_handler{}); std::string comment; std::unique_ptr<cpp_entity> entity; std::unique_ptr<cpp_type> type; std::string namespace_str; type_safe::optional<cpp_template_instantiation_type::builder> inst_builder; detail::visit_children(cur, [&](const CXCursor& child) { auto kind = clang_getCursorKind(child); if (kind == CXCursor_TypeRef) { auto referenced = clang_getCursorReferenced(child); if (inst_builder) { namespace_str.clear(); inst_builder.value().add_argument( detail::parse_type(context, referenced, clang_getCursorType(referenced))); } else if (clang_getCursorKind(referenced) == CXCursor_TemplateTypeParameter) // parse template parameter type type = cpp_template_parameter_type::build( cpp_template_type_parameter_ref(detail::get_entity_id(referenced), detail::get_cursor_name(child).c_str())); else if (!namespace_str.empty()) { // parse as user defined type // we can't use the other branch here, // as then the class name would be wrong auto name = detail::get_cursor_name(referenced); type = cpp_user_defined_type::build( cpp_type_ref(detail::get_entity_id(referenced), namespace_str + "::" + name.c_str())); } else { // for some reason libclang gives a type ref here // we actually need a class decl cursor, so parse the referenced one // this might be a definition, so give friend information to the parser entity = parse_entity(context, nullptr, referenced, cur); comment = type_safe::copy(entity->comment()).value_or(""); } } else if (kind == CXCursor_NamespaceRef) namespace_str += detail::get_cursor_name(child).c_str(); else if (kind == CXCursor_TemplateRef) { if (!namespace_str.empty()) namespace_str += "::"; auto templ = cpp_template_ref(detail::get_entity_id(clang_getCursorReferenced(child)), namespace_str + detail::get_cursor_name(child).c_str()); namespace_str.clear(); if (!inst_builder) inst_builder = cpp_template_instantiation_type::builder(std::move(templ)); else inst_builder.value().add_argument(std::move(templ)); } else if (clang_isDeclaration(kind)) { entity = parse_entity(context, nullptr, child, cur); if (entity) { // steal comment comment = type_safe::copy(entity->comment()).value_or(""); entity->set_comment(type_safe::nullopt); } } else if (inst_builder && clang_isExpression(kind)) { namespace_str.clear(); inst_builder.value().add_argument(detail::parse_expression(context, child)); } }); std::unique_ptr<cpp_entity> result; if (entity) result = cpp_friend::build(std::move(entity)); else if (type) result = cpp_friend::build(std::move(type)); else if (inst_builder) result = cpp_friend::build(inst_builder.value().finish()); else DEBUG_UNREACHABLE(detail::parse_error_handler{}, cur, "unknown child entity of friend declaration"); if (!comment.empty()) // set comment of entity... result->set_comment(std::move(comment)); // ... but override if this finds a different comment // due to clang_getCursorReferenced(), this may happen context.comments.match(*result, cur); return result; }
44.146789
98
0.564838
stevencpp
dbc0643feecb461fe688b90149e7b4f4689c8283
1,375
cpp
C++
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" #include "Input.h" JF::JFCInput::JFCInput() { memset(m_bKeyCodeArray, 0, sizeof(m_bKeyCodeArray)); memset(m_bKeyCodeArrayUp, 0, sizeof(m_bKeyCodeArrayUp)); m_vMousePos = { 0, 0, 0 }; m_vClickPos = { 0, 0, 0 }; } JF::JFCInput::~JFCInput() { } void JF::JFCInput::OnKeyDown(WPARAM wParam) { m_bKeyCodeArray[wParam] = true; m_bKeyCodeArrayUp[wParam] = false; } void JF::JFCInput::OnKeyUp(WPARAM wParam) { m_bKeyCodeArray[wParam] = false; m_bKeyCodeArrayUp[wParam] = true; } void JF::JFCInput::OnMouseMove(LPARAM lParam) { m_vMousePos.x = LOWORD(lParam); m_vMousePos.y = HIWORD(lParam); } void JF::JFCInput::OnMouseClick(LPARAM lParam) { m_vClickPos.x = LOWORD(lParam); m_vClickPos.y = HIWORD(lParam); } bool JF::JFCInput::GetKey(WPARAM wParam) { return m_bKeyCodeArray[wParam]; } bool JF::JFCInput::GetKeyDown(WPARAM wParam) { return m_bKeyCodeArray[wParam]; } bool JF::JFCInput::GetKeyUP(WPARAM wParam) { bool ret = m_bKeyCodeArrayUp[wParam]; m_bKeyCodeArrayUp[wParam] = false; return ret; } bool JF::JFCInput::GetMouseButton(WPARAM wParam) { return m_bKeyCodeArray[wParam]; } bool JF::JFCInput::GetMouseButtonDown(WPARAM wParam) { return m_bKeyCodeArray[wParam]; } bool JF::JFCInput::GetMouseButtonUp(WPARAM wParam) { return m_bKeyCodeArray[wParam]; } XMFLOAT3 JF::JFCInput::GetMousePosition() const { return m_vMousePos; }
18.333333
57
0.736
Jaraffe-github
dbc0884eb86d2447e394f6e286e2598f66e75ca9
369
hpp
C++
env/assert.hpp
mapsme/travelguide
26dd50b93f55ef731175c19d12514da5bace9fa4
[ "Apache-2.0" ]
61
2015-12-05T19:34:20.000Z
2021-06-25T09:07:09.000Z
env/assert.hpp
mapsme/travelguide
26dd50b93f55ef731175c19d12514da5bace9fa4
[ "Apache-2.0" ]
9
2016-02-19T23:22:20.000Z
2017-01-03T18:41:04.000Z
env/assert.hpp
mapsme/travelguide
26dd50b93f55ef731175c19d12514da5bace9fa4
[ "Apache-2.0" ]
35
2015-12-17T00:09:14.000Z
2021-01-27T10:47:11.000Z
#pragma once #include "message_list.hpp" #include "source_address.hpp" namespace dbg { void FireAssert(SourceAddress const & sa, string const & msg); } #define CHECK(x, message) do { if (x) {} else { ::dbg::FireAssert(SRC(), ::msg::MessageList message); } } while (false) #ifdef DEBUG #define ASSERT(x, msg) CHECK(x, msg) #else #define ASSERT(x, msg) #endif
19.421053
119
0.680217
mapsme
dbc26f76e4d17f6cd3d43d3cf8e825bcb447e7cd
60,491
cc
C++
chrome/browser/task_manager/task_manager_resource_providers.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/task_manager/task_manager_resource_providers.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/task_manager/task_manager_resource_providers.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/task_manager/task_manager_resource_providers.h" #include <string> #include "base/basictypes.h" #include "base/bind.h" #include "base/file_version_info.h" #include "base/i18n/rtl.h" #include "base/memory/scoped_ptr.h" #include "base/process_util.h" #include "base/stl_util.h" #include "base/string_util.h" #include "base/threading/thread.h" #include "base/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/background/background_contents_service.h" #include "chrome/browser/background/background_contents_service_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/instant/instant_controller.h" #include "chrome/browser/prerender/prerender_manager.h" #include "chrome/browser/prerender/prerender_manager_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/tab_contents/background_contents.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_instant_controller.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_manager.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/browser/ui/tab_contents/tab_contents_iterator.h" #include "chrome/browser/view_type_utils.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/process_type.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "third_party/sqlite/sqlite3.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_skia.h" #include "v8/include/v8.h" #if defined(OS_MACOSX) #include "ui/gfx/image/image_skia_util_mac.h" #endif #if defined(OS_WIN) #include "chrome/browser/app_icon_win.h" #include "ui/gfx/icon_util.h" #endif // defined(OS_WIN) using content::BrowserChildProcessHostIterator; using content::BrowserThread; using content::WebContents; using extensions::Extension; namespace { // Returns the appropriate message prefix ID for tabs and extensions, // reflecting whether they are apps or in incognito mode. int GetMessagePrefixID(bool is_app, bool is_extension, bool is_incognito, bool is_prerender, bool is_instant_preview) { if (is_app) { if (is_incognito) return IDS_TASK_MANAGER_APP_INCOGNITO_PREFIX; else return IDS_TASK_MANAGER_APP_PREFIX; } else if (is_extension) { if (is_incognito) return IDS_TASK_MANAGER_EXTENSION_INCOGNITO_PREFIX; else return IDS_TASK_MANAGER_EXTENSION_PREFIX; } else if (is_prerender) { return IDS_TASK_MANAGER_PRERENDER_PREFIX; } else if (is_instant_preview) { return IDS_TASK_MANAGER_INSTANT_PREVIEW_PREFIX; } else { return IDS_TASK_MANAGER_TAB_PREFIX; } } string16 GetProfileNameFromInfoCache(Profile* profile) { ProfileInfoCache& cache = g_browser_process->profile_manager()->GetProfileInfoCache(); size_t index = cache.GetIndexOfProfileWithPath( profile->GetOriginalProfile()->GetPath()); if (index == std::string::npos) return string16(); else return cache.GetNameOfProfileAtIndex(index); } } // namespace //////////////////////////////////////////////////////////////////////////////// // TaskManagerRendererResource class //////////////////////////////////////////////////////////////////////////////// TaskManagerRendererResource::TaskManagerRendererResource( base::ProcessHandle process, content::RenderViewHost* render_view_host) : process_(process), render_view_host_(render_view_host), pending_stats_update_(false), fps_(0.0f), pending_fps_update_(false), v8_memory_allocated_(0), v8_memory_used_(0), pending_v8_memory_allocated_update_(false) { // We cache the process and pid as when a Tab/BackgroundContents is closed the // process reference becomes NULL and the TaskManager still needs it. pid_ = base::GetProcId(process_); unique_process_id_ = render_view_host_->GetProcess()->GetID(); memset(&stats_, 0, sizeof(stats_)); } TaskManagerRendererResource::~TaskManagerRendererResource() { } void TaskManagerRendererResource::Refresh() { if (!pending_stats_update_) { render_view_host_->Send(new ChromeViewMsg_GetCacheResourceStats); pending_stats_update_ = true; } if (!pending_fps_update_) { render_view_host_->Send( new ChromeViewMsg_GetFPS(render_view_host_->GetRoutingID())); pending_fps_update_ = true; } if (!pending_v8_memory_allocated_update_) { render_view_host_->Send(new ChromeViewMsg_GetV8HeapStats); pending_v8_memory_allocated_update_ = true; } } WebKit::WebCache::ResourceTypeStats TaskManagerRendererResource::GetWebCoreCacheStats() const { return stats_; } float TaskManagerRendererResource::GetFPS() const { return fps_; } size_t TaskManagerRendererResource::GetV8MemoryAllocated() const { return v8_memory_allocated_; } size_t TaskManagerRendererResource::GetV8MemoryUsed() const { return v8_memory_used_; } void TaskManagerRendererResource::NotifyResourceTypeStats( const WebKit::WebCache::ResourceTypeStats& stats) { stats_ = stats; pending_stats_update_ = false; } void TaskManagerRendererResource::NotifyFPS(float fps) { fps_ = fps; pending_fps_update_ = false; } void TaskManagerRendererResource::NotifyV8HeapStats( size_t v8_memory_allocated, size_t v8_memory_used) { v8_memory_allocated_ = v8_memory_allocated; v8_memory_used_ = v8_memory_used; pending_v8_memory_allocated_update_ = false; } base::ProcessHandle TaskManagerRendererResource::GetProcess() const { return process_; } int TaskManagerRendererResource::GetUniqueChildProcessId() const { return unique_process_id_; } TaskManager::Resource::Type TaskManagerRendererResource::GetType() const { return RENDERER; } int TaskManagerRendererResource::GetRoutingID() const { return render_view_host_->GetRoutingID(); } bool TaskManagerRendererResource::ReportsCacheStats() const { return true; } bool TaskManagerRendererResource::ReportsFPS() const { return true; } bool TaskManagerRendererResource::ReportsV8MemoryStats() const { return true; } bool TaskManagerRendererResource::CanInspect() const { return true; } void TaskManagerRendererResource::Inspect() const { DevToolsWindow::OpenDevToolsWindow(render_view_host_); } bool TaskManagerRendererResource::SupportNetworkUsage() const { return true; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerTabContentsResource class //////////////////////////////////////////////////////////////////////////////// // static gfx::ImageSkia* TaskManagerTabContentsResource::prerender_icon_ = NULL; TaskManagerTabContentsResource::TaskManagerTabContentsResource( TabContents* tab_contents) : TaskManagerRendererResource( tab_contents->web_contents()->GetRenderProcessHost()->GetHandle(), tab_contents->web_contents()->GetRenderViewHost()), tab_contents_(tab_contents), is_instant_preview_(false) { if (!prerender_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); prerender_icon_ = rb.GetImageSkiaNamed(IDR_PRERENDER); } for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->instant_controller()->instant() && (*i)->instant_controller()->instant()->GetPreviewContents() == tab_contents_) { is_instant_preview_ = true; break; } } } TaskManagerTabContentsResource::~TaskManagerTabContentsResource() { } void TaskManagerTabContentsResource::InstantCommitted() { DCHECK(is_instant_preview_); is_instant_preview_ = false; } bool TaskManagerTabContentsResource::IsPrerendering() const { prerender::PrerenderManager* prerender_manager = prerender::PrerenderManagerFactory::GetForProfile( tab_contents_->profile()); return prerender_manager && prerender_manager->IsWebContentsPrerendering( tab_contents_->web_contents()); } bool TaskManagerTabContentsResource::HostsExtension() const { return tab_contents_->web_contents()->GetURL().SchemeIs( chrome::kExtensionScheme); } TaskManager::Resource::Type TaskManagerTabContentsResource::GetType() const { return HostsExtension() ? EXTENSION : RENDERER; } string16 TaskManagerTabContentsResource::GetTitle() const { // Fall back on the URL if there's no title. WebContents* contents = tab_contents_->web_contents(); string16 tab_title = contents->GetTitle(); GURL url = contents->GetURL(); if (tab_title.empty()) { tab_title = UTF8ToUTF16(url.spec()); // Force URL to be LTR. tab_title = base::i18n::GetDisplayStringInLTRDirectionality(tab_title); } else { // Since the tab_title will be concatenated with // IDS_TASK_MANAGER_TAB_PREFIX, we need to explicitly set the tab_title to // be LTR format if there is no strong RTL charater in it. Otherwise, if // IDS_TASK_MANAGER_TAB_PREFIX is an RTL word, the concatenated result // might be wrong. For example, http://mail.yahoo.com, whose title is // "Yahoo! Mail: The best web-based Email!", without setting it explicitly // as LTR format, the concatenated result will be "!Yahoo! Mail: The best // web-based Email :BAT", in which the capital letters "BAT" stands for // the Hebrew word for "tab". base::i18n::AdjustStringForLocaleDirection(&tab_title); } // Only classify as an app if the URL is an app and the tab is hosting an // extension process. (It's possible to be showing the URL from before it // was installed as an app.) ExtensionService* extension_service = tab_contents_->profile()->GetExtensionService(); extensions::ProcessMap* process_map = extension_service->process_map(); bool is_app = extension_service->IsInstalledApp(url) && process_map->Contains(contents->GetRenderProcessHost()->GetID()); int message_id = GetMessagePrefixID( is_app, HostsExtension(), tab_contents_->profile()->IsOffTheRecord(), IsPrerendering(), is_instant_preview_); return l10n_util::GetStringFUTF16(message_id, tab_title); } string16 TaskManagerTabContentsResource::GetProfileName() const { return GetProfileNameFromInfoCache(tab_contents_->profile()); } gfx::ImageSkia TaskManagerTabContentsResource::GetIcon() const { if (IsPrerendering()) return *prerender_icon_; return tab_contents_->favicon_tab_helper()->GetFavicon().AsImageSkia(); } WebContents* TaskManagerTabContentsResource::GetWebContents() const { return tab_contents_->web_contents(); } const Extension* TaskManagerTabContentsResource::GetExtension() const { if (HostsExtension()) { ExtensionService* extension_service = tab_contents_->profile()->GetExtensionService(); return extension_service->extensions()->GetByID( tab_contents_->web_contents()->GetURL().host()); } return NULL; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerTabContentsResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerTabContentsResourceProvider:: TaskManagerTabContentsResourceProvider(TaskManager* task_manager) : updating_(false), task_manager_(task_manager) { } TaskManagerTabContentsResourceProvider:: ~TaskManagerTabContentsResourceProvider() { } TaskManager::Resource* TaskManagerTabContentsResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { WebContents* web_contents = tab_util::GetWebContentsByID(render_process_host_id, routing_id); if (!web_contents) // Not one of our resource. return NULL; // If an origin PID was specified then the request originated in a plugin // working on the WebContents's behalf, so ignore it. if (origin_pid) return NULL; TabContents* tab_contents = TabContents::FromWebContents(web_contents); std::map<TabContents*, TaskManagerTabContentsResource*>::iterator res_iter = resources_.find(tab_contents); if (res_iter == resources_.end()) { // Can happen if the tab was closed while a network request was being // performed. return NULL; } return res_iter->second; } void TaskManagerTabContentsResourceProvider::StartUpdating() { DCHECK(!updating_); updating_ = true; // Add all the existing TabContentses. for (TabContentsIterator iterator; !iterator.done(); ++iterator) Add(*iterator); // Then we register for notifications to get new tabs. registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_SWAPPED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_INSTANT_COMMITTED, content::NotificationService::AllBrowserContextsAndSources()); } void TaskManagerTabContentsResourceProvider::StopUpdating() { DCHECK(updating_); updating_ = false; // Then we unregister for notifications to get new tabs. registrar_.Remove( this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, content::NOTIFICATION_WEB_CONTENTS_SWAPPED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, chrome::NOTIFICATION_INSTANT_COMMITTED, content::NotificationService::AllBrowserContextsAndSources()); // Delete all the resources. STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end()); resources_.clear(); } void TaskManagerTabContentsResourceProvider::AddToTaskManager( TabContents* tab_contents) { TaskManagerTabContentsResource* resource = new TaskManagerTabContentsResource(tab_contents); resources_[tab_contents] = resource; task_manager_->AddResource(resource); } void TaskManagerTabContentsResourceProvider::Add(TabContents* tab_contents) { if (!updating_) return; // Don't add dead tabs or tabs that haven't yet connected. if (!tab_contents->web_contents()->GetRenderProcessHost()->GetHandle() || !tab_contents->web_contents()->WillNotifyDisconnection()) { return; } std::map<TabContents*, TaskManagerTabContentsResource*>::const_iterator iter = resources_.find(tab_contents); if (iter != resources_.end()) { // The case may happen that we have added a WebContents as part of the // iteration performed during StartUpdating() call but the notification that // it has connected was not fired yet. So when the notification happens, we // already know about this tab and just ignore it. return; } AddToTaskManager(tab_contents); } void TaskManagerTabContentsResourceProvider::Remove(TabContents* tab_contents) { if (!updating_) return; std::map<TabContents*, TaskManagerTabContentsResource*>::iterator iter = resources_.find(tab_contents); if (iter == resources_.end()) { // Since WebContents are destroyed asynchronously (see TabContentsCollector // in navigation_controller.cc), we can be notified of a tab being removed // that we don't know. This can happen if the user closes a tab and quickly // opens the task manager, before the tab is actually destroyed. return; } // Remove the resource from the Task Manager. TaskManagerTabContentsResource* resource = iter->second; task_manager_->RemoveResource(resource); // And from the provider. resources_.erase(iter); // Finally, delete the resource. delete resource; } void TaskManagerTabContentsResourceProvider::Update(TabContents* tab_contents) { if (!updating_) return; std::map<TabContents*, TaskManagerTabContentsResource*>::iterator iter = resources_.find(tab_contents); DCHECK(iter != resources_.end()); if (iter != resources_.end()) iter->second->InstantCommitted(); } void TaskManagerTabContentsResourceProvider::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { TabContents* tab_contents; if (type == chrome::NOTIFICATION_INSTANT_COMMITTED) { tab_contents = content::Source<TabContents>(source).ptr(); } else { tab_contents = TabContents::FromWebContents( content::Source<WebContents>(source).ptr()); } // A background page does not have a TabContents. if (!tab_contents) return; switch (type) { case content::NOTIFICATION_WEB_CONTENTS_CONNECTED: Add(tab_contents); break; case content::NOTIFICATION_WEB_CONTENTS_SWAPPED: Remove(tab_contents); Add(tab_contents); break; case content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED: Remove(tab_contents); break; case chrome::NOTIFICATION_INSTANT_COMMITTED: Update(tab_contents); break; default: NOTREACHED() << "Unexpected notification."; return; } } //////////////////////////////////////////////////////////////////////////////// // TaskManagerPanelResource class //////////////////////////////////////////////////////////////////////////////// TaskManagerPanelResource::TaskManagerPanelResource(Panel* panel) : TaskManagerRendererResource( panel->GetWebContents()->GetRenderProcessHost()->GetHandle(), panel->GetWebContents()->GetRenderViewHost()), panel_(panel) { message_prefix_id_ = GetMessagePrefixID( GetExtension()->is_app(), true, panel->profile()->IsOffTheRecord(), false, false); } TaskManagerPanelResource::~TaskManagerPanelResource() { } TaskManager::Resource::Type TaskManagerPanelResource::GetType() const { return EXTENSION; } string16 TaskManagerPanelResource::GetTitle() const { string16 title = panel_->GetWindowTitle(); // Since the title will be concatenated with an IDS_TASK_MANAGER_* prefix // we need to explicitly set the title to be LTR format if there is no // strong RTL charater in it. Otherwise, if the task manager prefix is an // RTL word, the concatenated result might be wrong. For example, // a page whose title is "Yahoo! Mail: The best web-based Email!", without // setting it explicitly as LTR format, the concatenated result will be // "!Yahoo! Mail: The best web-based Email :PPA", in which the capital // letters "PPA" stands for the Hebrew word for "app". base::i18n::AdjustStringForLocaleDirection(&title); return l10n_util::GetStringFUTF16(message_prefix_id_, title); } string16 TaskManagerPanelResource::GetProfileName() const { return GetProfileNameFromInfoCache(panel_->profile()); } gfx::ImageSkia TaskManagerPanelResource::GetIcon() const { return panel_->GetCurrentPageIcon(); } WebContents* TaskManagerPanelResource::GetWebContents() const { return panel_->GetWebContents(); } const Extension* TaskManagerPanelResource::GetExtension() const { ExtensionService* extension_service = panel_->profile()->GetExtensionService(); return extension_service->extensions()->GetByID(panel_->extension_id()); } //////////////////////////////////////////////////////////////////////////////// // TaskManagerPanelResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerPanelResourceProvider::TaskManagerPanelResourceProvider( TaskManager* task_manager) : updating_(false), task_manager_(task_manager) { } TaskManagerPanelResourceProvider::~TaskManagerPanelResourceProvider() { } TaskManager::Resource* TaskManagerPanelResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { // If an origin PID was specified, the request is from a plugin, not the // render view host process if (origin_pid) return NULL; for (PanelResourceMap::iterator i = resources_.begin(); i != resources_.end(); ++i) { WebContents* contents = i->first->GetWebContents(); if (contents && contents->GetRenderProcessHost()->GetID() == render_process_host_id && contents->GetRenderViewHost()->GetRoutingID() == routing_id) { return i->second; } } // Can happen if the panel went away while a network request was being // performed. return NULL; } void TaskManagerPanelResourceProvider::StartUpdating() { if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kBrowserlessPanels)) return; DCHECK(!updating_); updating_ = true; // Add all the Panels. std::vector<Panel*> panels = PanelManager::GetInstance()->panels(); for (size_t i = 0; i < panels.size(); ++i) Add(panels[i]); // Then we register for notifications to get new and remove closed panels. registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED, content::NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::NotificationService::AllSources()); } void TaskManagerPanelResourceProvider::StopUpdating() { if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kBrowserlessPanels)) return; DCHECK(updating_); updating_ = false; // Unregister for notifications about new/removed panels. registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED, content::NotificationService::AllSources()); registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::NotificationService::AllSources()); // Delete all the resources. STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end()); resources_.clear(); } void TaskManagerPanelResourceProvider::Add(Panel* panel) { if (!updating_) return; PanelResourceMap::const_iterator iter = resources_.find(panel); if (iter != resources_.end()) return; TaskManagerPanelResource* resource = new TaskManagerPanelResource(panel); resources_[panel] = resource; task_manager_->AddResource(resource); } void TaskManagerPanelResourceProvider::Remove(Panel* panel) { if (!updating_) return; PanelResourceMap::iterator iter = resources_.find(panel); if (iter == resources_.end()) return; TaskManagerPanelResource* resource = iter->second; task_manager_->RemoveResource(resource); resources_.erase(iter); delete resource; } void TaskManagerPanelResourceProvider::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { WebContents* web_contents = content::Source<WebContents>(source).ptr(); if (chrome::GetViewType(web_contents) != chrome::VIEW_TYPE_PANEL) return; switch (type) { case content::NOTIFICATION_WEB_CONTENTS_CONNECTED: { std::vector<Panel*>panels = PanelManager::GetInstance()->panels(); for (size_t i = 0; i < panels.size(); ++i) { if (panels[i]->GetWebContents() == web_contents) { Add(panels[i]); break; } } break; } case content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED: { for (PanelResourceMap::iterator iter = resources_.begin(); iter != resources_.end(); ++iter) { Panel* panel = iter->first; if (panel->GetWebContents() == web_contents) { Remove(panel); break; } } break; } default: NOTREACHED() << "Unexpected notificiation."; break; } } //////////////////////////////////////////////////////////////////////////////// // TaskManagerBackgroundContentsResource class //////////////////////////////////////////////////////////////////////////////// gfx::ImageSkia* TaskManagerBackgroundContentsResource::default_icon_ = NULL; // TODO(atwilson): http://crbug.com/116893 // HACK: if the process handle is invalid, we use the current process's handle. // This preserves old behavior but is incorrect, and should be fixed. TaskManagerBackgroundContentsResource::TaskManagerBackgroundContentsResource( BackgroundContents* background_contents, const string16& application_name) : TaskManagerRendererResource( background_contents->web_contents()->GetRenderProcessHost()-> GetHandle() ? background_contents->web_contents()->GetRenderProcessHost()-> GetHandle() : base::Process::Current().handle(), background_contents->web_contents()->GetRenderViewHost()), background_contents_(background_contents), application_name_(application_name) { // Just use the same icon that other extension resources do. // TODO(atwilson): Use the favicon when that's available. if (!default_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN); } // Ensure that the string has the appropriate direction markers (see comment // in TaskManagerTabContentsResource::GetTitle()). base::i18n::AdjustStringForLocaleDirection(&application_name_); } TaskManagerBackgroundContentsResource::~TaskManagerBackgroundContentsResource( ) { } string16 TaskManagerBackgroundContentsResource::GetTitle() const { string16 title = application_name_; if (title.empty()) { // No title (can't locate the parent app for some reason) so just display // the URL (properly forced to be LTR). title = base::i18n::GetDisplayStringInLTRDirectionality( UTF8ToUTF16(background_contents_->GetURL().spec())); } return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_BACKGROUND_PREFIX, title); } string16 TaskManagerBackgroundContentsResource::GetProfileName() const { return string16(); } gfx::ImageSkia TaskManagerBackgroundContentsResource::GetIcon() const { return *default_icon_; } bool TaskManagerBackgroundContentsResource::IsBackground() const { return true; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerBackgroundContentsResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerBackgroundContentsResourceProvider:: TaskManagerBackgroundContentsResourceProvider(TaskManager* task_manager) : updating_(false), task_manager_(task_manager) { } TaskManagerBackgroundContentsResourceProvider:: ~TaskManagerBackgroundContentsResourceProvider() { } TaskManager::Resource* TaskManagerBackgroundContentsResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { // If an origin PID was specified, the request is from a plugin, not the // render view host process if (origin_pid) return NULL; for (Resources::iterator i = resources_.begin(); i != resources_.end(); i++) { WebContents* tab = i->first->web_contents(); if (tab->GetRenderProcessHost()->GetID() == render_process_host_id && tab->GetRenderViewHost()->GetRoutingID() == routing_id) { return i->second; } } // Can happen if the page went away while a network request was being // performed. return NULL; } void TaskManagerBackgroundContentsResourceProvider::StartUpdating() { DCHECK(!updating_); updating_ = true; // Add all the existing BackgroundContents from every profile, including // incognito profiles. ProfileManager* profile_manager = g_browser_process->profile_manager(); std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles()); size_t num_default_profiles = profiles.size(); for (size_t i = 0; i < num_default_profiles; ++i) { if (profiles[i]->HasOffTheRecordProfile()) { profiles.push_back(profiles[i]->GetOffTheRecordProfile()); } } for (size_t i = 0; i < profiles.size(); ++i) { BackgroundContentsService* background_contents_service = BackgroundContentsServiceFactory::GetForProfile(profiles[i]); std::vector<BackgroundContents*> contents = background_contents_service->GetBackgroundContents(); ExtensionService* extension_service = profiles[i]->GetExtensionService(); for (std::vector<BackgroundContents*>::iterator iterator = contents.begin(); iterator != contents.end(); ++iterator) { string16 application_name; // Lookup the name from the parent extension. if (extension_service) { const string16& application_id = background_contents_service->GetParentApplicationId(*iterator); const Extension* extension = extension_service->GetExtensionById( UTF16ToUTF8(application_id), false); if (extension) application_name = UTF8ToUTF16(extension->name()); } Add(*iterator, application_name); } } // Then we register for notifications to get new BackgroundContents. registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED, content::NotificationService::AllBrowserContextsAndSources()); } void TaskManagerBackgroundContentsResourceProvider::StopUpdating() { DCHECK(updating_); updating_ = false; // Unregister for notifications registrar_.Remove( this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED, content::NotificationService::AllBrowserContextsAndSources()); // Delete all the resources. STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end()); resources_.clear(); } void TaskManagerBackgroundContentsResourceProvider::AddToTaskManager( BackgroundContents* background_contents, const string16& application_name) { TaskManagerBackgroundContentsResource* resource = new TaskManagerBackgroundContentsResource(background_contents, application_name); resources_[background_contents] = resource; task_manager_->AddResource(resource); } void TaskManagerBackgroundContentsResourceProvider::Add( BackgroundContents* contents, const string16& application_name) { if (!updating_) return; // TODO(atwilson): http://crbug.com/116893 // We should check that the process handle is valid here, but it won't // be in the case of NOTIFICATION_BACKGROUND_CONTENTS_OPENED. // Should never add the same BackgroundContents twice. DCHECK(resources_.find(contents) == resources_.end()); AddToTaskManager(contents, application_name); } void TaskManagerBackgroundContentsResourceProvider::Remove( BackgroundContents* contents) { if (!updating_) return; Resources::iterator iter = resources_.find(contents); DCHECK(iter != resources_.end()); // Remove the resource from the Task Manager. TaskManagerBackgroundContentsResource* resource = iter->second; task_manager_->RemoveResource(resource); // And from the provider. resources_.erase(iter); // Finally, delete the resource. delete resource; } void TaskManagerBackgroundContentsResourceProvider::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED: { // Get the name from the parent application. If no parent application is // found, just pass an empty string - BackgroundContentsResource::GetTitle // will display the URL instead in this case. This should never happen // except in rare cases when an extension is being unloaded or chrome is // exiting while the task manager is displayed. string16 application_name; ExtensionService* service = content::Source<Profile>(source)->GetExtensionService(); if (service) { std::string application_id = UTF16ToUTF8( content::Details<BackgroundContentsOpenedDetails>(details)-> application_id); const Extension* extension = service->GetExtensionById(application_id, false); // Extension can be NULL when running unit tests. if (extension) application_name = UTF8ToUTF16(extension->name()); } Add(content::Details<BackgroundContentsOpenedDetails>(details)->contents, application_name); // Opening a new BackgroundContents needs to force the display to refresh // (applications may now be considered "background" that weren't before). task_manager_->ModelChanged(); break; } case chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED: { BackgroundContents* contents = content::Details<BackgroundContents>(details).ptr(); // Should never get a NAVIGATED before OPENED. DCHECK(resources_.find(contents) != resources_.end()); // Preserve the application name. string16 application_name( resources_.find(contents)->second->application_name()); Remove(contents); Add(contents, application_name); break; } case chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED: Remove(content::Details<BackgroundContents>(details).ptr()); // Closing a BackgroundContents needs to force the display to refresh // (applications may now be considered "foreground" that weren't before). task_manager_->ModelChanged(); break; default: NOTREACHED() << "Unexpected notification."; return; } } //////////////////////////////////////////////////////////////////////////////// // TaskManagerChildProcessResource class //////////////////////////////////////////////////////////////////////////////// gfx::ImageSkia* TaskManagerChildProcessResource::default_icon_ = NULL; TaskManagerChildProcessResource::TaskManagerChildProcessResource( content::ProcessType type, const string16& name, base::ProcessHandle handle, int unique_process_id) : type_(type), name_(name), handle_(handle), unique_process_id_(unique_process_id), network_usage_support_(false) { // We cache the process id because it's not cheap to calculate, and it won't // be available when we get the plugin disconnected notification. pid_ = base::GetProcId(handle); if (!default_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN); // TODO(jabdelmalek): use different icon for web workers. } } TaskManagerChildProcessResource::~TaskManagerChildProcessResource() { } // TaskManagerResource methods: string16 TaskManagerChildProcessResource::GetTitle() const { if (title_.empty()) title_ = GetLocalizedTitle(); return title_; } string16 TaskManagerChildProcessResource::GetProfileName() const { return string16(); } gfx::ImageSkia TaskManagerChildProcessResource::GetIcon() const { return *default_icon_; } base::ProcessHandle TaskManagerChildProcessResource::GetProcess() const { return handle_; } int TaskManagerChildProcessResource::GetUniqueChildProcessId() const { return unique_process_id_; } TaskManager::Resource::Type TaskManagerChildProcessResource::GetType() const { // Translate types to TaskManager::ResourceType, since ChildProcessData's type // is not available for all TaskManager resources. switch (type_) { case content::PROCESS_TYPE_PLUGIN: case content::PROCESS_TYPE_PPAPI_PLUGIN: case content::PROCESS_TYPE_PPAPI_BROKER: return TaskManager::Resource::PLUGIN; case content::PROCESS_TYPE_NACL_LOADER: case content::PROCESS_TYPE_NACL_BROKER: return TaskManager::Resource::NACL; case content::PROCESS_TYPE_UTILITY: return TaskManager::Resource::UTILITY; case content::PROCESS_TYPE_PROFILE_IMPORT: return TaskManager::Resource::PROFILE_IMPORT; case content::PROCESS_TYPE_ZYGOTE: return TaskManager::Resource::ZYGOTE; case content::PROCESS_TYPE_SANDBOX_HELPER: return TaskManager::Resource::SANDBOX_HELPER; case content::PROCESS_TYPE_GPU: return TaskManager::Resource::GPU; default: return TaskManager::Resource::UNKNOWN; } } bool TaskManagerChildProcessResource::SupportNetworkUsage() const { return network_usage_support_; } void TaskManagerChildProcessResource::SetSupportNetworkUsage() { network_usage_support_ = true; } string16 TaskManagerChildProcessResource::GetLocalizedTitle() const { string16 title = name_; if (title.empty()) { switch (type_) { case content::PROCESS_TYPE_PLUGIN: case content::PROCESS_TYPE_PPAPI_PLUGIN: case content::PROCESS_TYPE_PPAPI_BROKER: title = l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UNKNOWN_PLUGIN_NAME); break; default: // Nothing to do for non-plugin processes. break; } } // Explicitly mark name as LTR if there is no strong RTL character, // to avoid the wrong concatenation result similar to "!Yahoo Mail: the // best web-based Email: NIGULP", in which "NIGULP" stands for the Hebrew // or Arabic word for "plugin". base::i18n::AdjustStringForLocaleDirection(&title); switch (type_) { case content::PROCESS_TYPE_UTILITY: return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UTILITY_PREFIX); case content::PROCESS_TYPE_PROFILE_IMPORT: return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UTILITY_PREFIX); case content::PROCESS_TYPE_GPU: return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_GPU_PREFIX); case content::PROCESS_TYPE_NACL_BROKER: return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NACL_BROKER_PREFIX); case content::PROCESS_TYPE_PLUGIN: case content::PROCESS_TYPE_PPAPI_PLUGIN: return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PLUGIN_PREFIX, title); case content::PROCESS_TYPE_PPAPI_BROKER: return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PLUGIN_BROKER_PREFIX, title); case content::PROCESS_TYPE_NACL_LOADER: return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_NACL_PREFIX, title); // These types don't need display names or get them from elsewhere. case content::PROCESS_TYPE_BROWSER: case content::PROCESS_TYPE_RENDERER: case content::PROCESS_TYPE_ZYGOTE: case content::PROCESS_TYPE_SANDBOX_HELPER: case content::PROCESS_TYPE_MAX: NOTREACHED(); break; case content::PROCESS_TYPE_WORKER: NOTREACHED() << "Workers are not handled by this provider."; break; case content::PROCESS_TYPE_UNKNOWN: NOTREACHED() << "Need localized name for child process type."; } return title; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerChildProcessResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerChildProcessResourceProvider:: TaskManagerChildProcessResourceProvider(TaskManager* task_manager) : task_manager_(task_manager), updating_(false) { } TaskManagerChildProcessResourceProvider:: ~TaskManagerChildProcessResourceProvider() { } TaskManager::Resource* TaskManagerChildProcessResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { PidResourceMap::iterator iter = pid_to_resources_.find(origin_pid); if (iter != pid_to_resources_.end()) return iter->second; else return NULL; } void TaskManagerChildProcessResourceProvider::StartUpdating() { DCHECK(!updating_); updating_ = true; // Register for notifications to get new child processes. registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED, content::NotificationService::AllBrowserContextsAndSources()); // Get the existing child processes. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &TaskManagerChildProcessResourceProvider::RetrieveChildProcessData, this)); } void TaskManagerChildProcessResourceProvider::StopUpdating() { DCHECK(updating_); updating_ = false; // Unregister for notifications to get new plugin processes. registrar_.Remove( this, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED, content::NotificationService::AllBrowserContextsAndSources()); // Delete all the resources. STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end()); resources_.clear(); pid_to_resources_.clear(); } void TaskManagerChildProcessResourceProvider::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { content::ChildProcessData data = *content::Details<content::ChildProcessData>(details).ptr(); switch (type) { case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED: Add(data); break; case content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED: Remove(data); break; default: NOTREACHED() << "Unexpected notification."; return; } } void TaskManagerChildProcessResourceProvider::Add( const content::ChildProcessData& child_process_data) { if (!updating_) return; // Workers are handled by TaskManagerWorkerResourceProvider. if (child_process_data.type == content::PROCESS_TYPE_WORKER) return; if (resources_.count(child_process_data.handle)) { // The case may happen that we have added a child_process_info as part of // the iteration performed during StartUpdating() call but the notification // that it has connected was not fired yet. So when the notification // happens, we already know about this plugin and just ignore it. return; } AddToTaskManager(child_process_data); } void TaskManagerChildProcessResourceProvider::Remove( const content::ChildProcessData& child_process_data) { if (!updating_) return; if (child_process_data.type == content::PROCESS_TYPE_WORKER) return; ChildProcessMap::iterator iter = resources_.find(child_process_data.handle); if (iter == resources_.end()) { // ChildProcessData disconnection notifications are asynchronous, so we // might be notified for a plugin we don't know anything about (if it was // closed before the task manager was shown and destroyed after that). return; } // Remove the resource from the Task Manager. TaskManagerChildProcessResource* resource = iter->second; task_manager_->RemoveResource(resource); // Remove it from the provider. resources_.erase(iter); // Remove it from our pid map. PidResourceMap::iterator pid_iter = pid_to_resources_.find(resource->process_id()); DCHECK(pid_iter != pid_to_resources_.end()); if (pid_iter != pid_to_resources_.end()) pid_to_resources_.erase(pid_iter); // Finally, delete the resource. delete resource; } void TaskManagerChildProcessResourceProvider::AddToTaskManager( const content::ChildProcessData& child_process_data) { TaskManagerChildProcessResource* resource = new TaskManagerChildProcessResource( child_process_data.type, child_process_data.name, child_process_data.handle, child_process_data.id); resources_[child_process_data.handle] = resource; pid_to_resources_[resource->process_id()] = resource; task_manager_->AddResource(resource); } // The ChildProcessData::Iterator has to be used from the IO thread. void TaskManagerChildProcessResourceProvider::RetrieveChildProcessData() { std::vector<content::ChildProcessData> child_processes; for (BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) { // Only add processes which are already started, since we need their handle. if (iter.GetData().handle == base::kNullProcessHandle) continue; child_processes.push_back(iter.GetData()); } // Now notify the UI thread that we have retrieved information about child // processes. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &TaskManagerChildProcessResourceProvider::ChildProcessDataRetreived, this, child_processes)); } // This is called on the UI thread. void TaskManagerChildProcessResourceProvider::ChildProcessDataRetreived( const std::vector<content::ChildProcessData>& child_processes) { for (size_t i = 0; i < child_processes.size(); ++i) Add(child_processes[i]); content::NotificationService::current()->Notify( chrome::NOTIFICATION_TASK_MANAGER_CHILD_PROCESSES_DATA_READY, content::Source<TaskManagerChildProcessResourceProvider>(this), content::NotificationService::NoDetails()); } //////////////////////////////////////////////////////////////////////////////// // TaskManagerExtensionProcessResource class //////////////////////////////////////////////////////////////////////////////// gfx::ImageSkia* TaskManagerExtensionProcessResource::default_icon_ = NULL; TaskManagerExtensionProcessResource::TaskManagerExtensionProcessResource( content::RenderViewHost* render_view_host) : render_view_host_(render_view_host) { if (!default_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN); } process_handle_ = render_view_host_->GetProcess()->GetHandle(); unique_process_id_ = render_view_host->GetProcess()->GetID(); pid_ = base::GetProcId(process_handle_); string16 extension_name = UTF8ToUTF16(GetExtension()->name()); DCHECK(!extension_name.empty()); Profile* profile = Profile::FromBrowserContext( render_view_host->GetProcess()->GetBrowserContext()); int message_id = GetMessagePrefixID(GetExtension()->is_app(), true, profile->IsOffTheRecord(), false, false); title_ = l10n_util::GetStringFUTF16(message_id, extension_name); } TaskManagerExtensionProcessResource::~TaskManagerExtensionProcessResource() { } string16 TaskManagerExtensionProcessResource::GetTitle() const { return title_; } string16 TaskManagerExtensionProcessResource::GetProfileName() const { return GetProfileNameFromInfoCache(Profile::FromBrowserContext( render_view_host_->GetProcess()->GetBrowserContext())); } gfx::ImageSkia TaskManagerExtensionProcessResource::GetIcon() const { return *default_icon_; } base::ProcessHandle TaskManagerExtensionProcessResource::GetProcess() const { return process_handle_; } int TaskManagerExtensionProcessResource::GetUniqueChildProcessId() const { return unique_process_id_; } TaskManager::Resource::Type TaskManagerExtensionProcessResource::GetType() const { return EXTENSION; } bool TaskManagerExtensionProcessResource::CanInspect() const { return true; } void TaskManagerExtensionProcessResource::Inspect() const { DevToolsWindow::OpenDevToolsWindow(render_view_host_); } bool TaskManagerExtensionProcessResource::SupportNetworkUsage() const { return true; } void TaskManagerExtensionProcessResource::SetSupportNetworkUsage() { NOTREACHED(); } const Extension* TaskManagerExtensionProcessResource::GetExtension() const { Profile* profile = Profile::FromBrowserContext( render_view_host_->GetProcess()->GetBrowserContext()); ExtensionProcessManager* process_manager = extensions::ExtensionSystem::Get(profile)->process_manager(); return process_manager->GetExtensionForRenderViewHost(render_view_host_); } bool TaskManagerExtensionProcessResource::IsBackground() const { WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host_); chrome::ViewType view_type = chrome::GetViewType(web_contents); return view_type == chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerExtensionProcessResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerExtensionProcessResourceProvider:: TaskManagerExtensionProcessResourceProvider(TaskManager* task_manager) : task_manager_(task_manager), updating_(false) { } TaskManagerExtensionProcessResourceProvider:: ~TaskManagerExtensionProcessResourceProvider() { } TaskManager::Resource* TaskManagerExtensionProcessResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { std::map<int, TaskManagerExtensionProcessResource*>::iterator iter = pid_to_resources_.find(origin_pid); if (iter != pid_to_resources_.end()) return iter->second; else return NULL; } void TaskManagerExtensionProcessResourceProvider::StartUpdating() { DCHECK(!updating_); updating_ = true; // Add all the existing extension views from all Profiles, including those // from incognito split mode. ProfileManager* profile_manager = g_browser_process->profile_manager(); std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles()); size_t num_default_profiles = profiles.size(); for (size_t i = 0; i < num_default_profiles; ++i) { if (profiles[i]->HasOffTheRecordProfile()) { profiles.push_back(profiles[i]->GetOffTheRecordProfile()); } } for (size_t i = 0; i < profiles.size(); ++i) { ExtensionProcessManager* process_manager = profiles[i]->GetExtensionProcessManager(); if (process_manager) { const ExtensionProcessManager::ViewSet all_views = process_manager->GetAllViews(); ExtensionProcessManager::ViewSet::const_iterator jt = all_views.begin(); for (; jt != all_views.end(); ++jt) { content::RenderViewHost* rvh = *jt; // Don't add dead extension processes. if (!rvh->IsRenderViewLive()) continue; AddToTaskManager(rvh); } } } // Register for notifications about extension process changes. registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED, content::NotificationService::AllBrowserContextsAndSources()); } void TaskManagerExtensionProcessResourceProvider::StopUpdating() { DCHECK(updating_); updating_ = false; // Unregister for notifications about extension process changes. registrar_.Remove( this, chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Remove( this, chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED, content::NotificationService::AllBrowserContextsAndSources()); // Delete all the resources. STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end()); resources_.clear(); pid_to_resources_.clear(); } void TaskManagerExtensionProcessResourceProvider::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED: AddToTaskManager( content::Details<content::RenderViewHost>(details).ptr()); break; case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: RemoveFromTaskManager( content::Details<extensions::ExtensionHost>(details).ptr()-> render_view_host()); break; case chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED: RemoveFromTaskManager( content::Details<content::RenderViewHost>(details).ptr()); break; default: NOTREACHED() << "Unexpected notification."; return; } } bool TaskManagerExtensionProcessResourceProvider:: IsHandledByThisProvider(content::RenderViewHost* render_view_host) { // Don't add WebContents (those are handled by // TaskManagerTabContentsResourceProvider) or background contents (handled // by TaskManagerBackgroundResourceProvider). WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host); chrome::ViewType view_type = chrome::GetViewType(web_contents); #if defined(USE_ASH) return (view_type != chrome::VIEW_TYPE_TAB_CONTENTS && view_type != chrome::VIEW_TYPE_BACKGROUND_CONTENTS); #else return (view_type != chrome::VIEW_TYPE_TAB_CONTENTS && view_type != chrome::VIEW_TYPE_BACKGROUND_CONTENTS && view_type != chrome::VIEW_TYPE_PANEL); #endif // USE_ASH } void TaskManagerExtensionProcessResourceProvider::AddToTaskManager( content::RenderViewHost* render_view_host) { if (!IsHandledByThisProvider(render_view_host)) return; TaskManagerExtensionProcessResource* resource = new TaskManagerExtensionProcessResource(render_view_host); DCHECK(resources_.find(render_view_host) == resources_.end()); resources_[render_view_host] = resource; pid_to_resources_[resource->process_id()] = resource; task_manager_->AddResource(resource); } void TaskManagerExtensionProcessResourceProvider::RemoveFromTaskManager( content::RenderViewHost* render_view_host) { if (!updating_) return; std::map<content::RenderViewHost*, TaskManagerExtensionProcessResource*> ::iterator iter = resources_.find(render_view_host); if (iter == resources_.end()) return; // Remove the resource from the Task Manager. TaskManagerExtensionProcessResource* resource = iter->second; task_manager_->RemoveResource(resource); // Remove it from the provider. resources_.erase(iter); // Remove it from our pid map. std::map<int, TaskManagerExtensionProcessResource*>::iterator pid_iter = pid_to_resources_.find(resource->process_id()); DCHECK(pid_iter != pid_to_resources_.end()); if (pid_iter != pid_to_resources_.end()) pid_to_resources_.erase(pid_iter); // Finally, delete the resource. delete resource; } //////////////////////////////////////////////////////////////////////////////// // TaskManagerBrowserProcessResource class //////////////////////////////////////////////////////////////////////////////// gfx::ImageSkia* TaskManagerBrowserProcessResource::default_icon_ = NULL; TaskManagerBrowserProcessResource::TaskManagerBrowserProcessResource() : title_() { int pid = base::GetCurrentProcId(); bool success = base::OpenPrivilegedProcessHandle(pid, &process_); DCHECK(success); #if defined(OS_WIN) if (!default_icon_) { HICON icon = GetAppIcon(); if (icon) { scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON(icon)); default_icon_ = new gfx::ImageSkia(*bitmap); } } #elif defined(OS_POSIX) && !defined(OS_MACOSX) if (!default_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); default_icon_ = rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_16); } #elif defined(OS_MACOSX) if (!default_icon_) { // IDR_PRODUCT_LOGO_16 doesn't quite look like chrome/mac's icns icon. Load // the real app icon (requires a nsimage->image_skia->nsimage // conversion :-(). default_icon_ = new gfx::ImageSkia(gfx::ApplicationIconAtSize(16)); } #else // TODO(port): Port icon code. NOTIMPLEMENTED(); #endif // defined(OS_WIN) } TaskManagerBrowserProcessResource::~TaskManagerBrowserProcessResource() { base::CloseProcessHandle(process_); } // TaskManagerResource methods: string16 TaskManagerBrowserProcessResource::GetTitle() const { if (title_.empty()) { title_ = l10n_util::GetStringUTF16(IDS_TASK_MANAGER_WEB_BROWSER_CELL_TEXT); } return title_; } string16 TaskManagerBrowserProcessResource::GetProfileName() const { return string16(); } gfx::ImageSkia TaskManagerBrowserProcessResource::GetIcon() const { return *default_icon_; } size_t TaskManagerBrowserProcessResource::SqliteMemoryUsedBytes() const { return static_cast<size_t>(sqlite3_memory_used()); } base::ProcessHandle TaskManagerBrowserProcessResource::GetProcess() const { return base::GetCurrentProcessHandle(); // process_; } int TaskManagerBrowserProcessResource::GetUniqueChildProcessId() const { return 0; } TaskManager::Resource::Type TaskManagerBrowserProcessResource::GetType() const { return BROWSER; } bool TaskManagerBrowserProcessResource::SupportNetworkUsage() const { return true; } void TaskManagerBrowserProcessResource::SetSupportNetworkUsage() { NOTREACHED(); } bool TaskManagerBrowserProcessResource::ReportsSqliteMemoryUsed() const { return true; } // BrowserProcess uses v8 for proxy resolver in certain cases. bool TaskManagerBrowserProcessResource::ReportsV8MemoryStats() const { const CommandLine* command_line = CommandLine::ForCurrentProcess(); bool using_v8 = !command_line->HasSwitch(switches::kWinHttpProxyResolver); if (using_v8 && command_line->HasSwitch(switches::kSingleProcess)) { using_v8 = false; } return using_v8; } size_t TaskManagerBrowserProcessResource::GetV8MemoryAllocated() const { v8::HeapStatistics stats; v8::V8::GetHeapStatistics(&stats); return stats.total_heap_size(); } size_t TaskManagerBrowserProcessResource::GetV8MemoryUsed() const { v8::HeapStatistics stats; v8::V8::GetHeapStatistics(&stats); return stats.used_heap_size(); } //////////////////////////////////////////////////////////////////////////////// // TaskManagerBrowserProcessResourceProvider class //////////////////////////////////////////////////////////////////////////////// TaskManagerBrowserProcessResourceProvider:: TaskManagerBrowserProcessResourceProvider(TaskManager* task_manager) : updating_(false), task_manager_(task_manager) { } TaskManagerBrowserProcessResourceProvider:: ~TaskManagerBrowserProcessResourceProvider() { } TaskManager::Resource* TaskManagerBrowserProcessResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { if (origin_pid || render_process_host_id != -1) { return NULL; } return &resource_; } void TaskManagerBrowserProcessResourceProvider::StartUpdating() { task_manager_->AddResource(&resource_); } void TaskManagerBrowserProcessResourceProvider::StopUpdating() { }
35.562022
80
0.720339
Crystalnix
dbc6d19e3ee35fe7a472a8e29bf60303513845ae
1,528
hpp
C++
example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
105
2015-01-24T13:26:41.000Z
2022-02-18T15:36:53.000Z
example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
37
2015-09-04T06:57:10.000Z
2021-09-09T18:01:44.000Z
example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
23
2015-01-27T11:09:18.000Z
2021-10-04T02:23:30.000Z
// Copyright (C) 2016 Vicente J. Botet Escriba // // 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 JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP #define JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP #if __cplusplus >= 201402L #include <type_traits> #include <experimental/meta.hpp> #include <cstddef> // mem_usage_able/mem_usage.hpp namespace std { namespace experimental { inline namespace fundamental_v3 { namespace mem_usage_able { template <typename T, typename Enabler=void> struct traits : traits<T, meta::when<true>> {}; template <typename R, bool B> struct traits<R, meta::when<B>> { template <typename T> static constexpr size_t apply(T&& v) = delete; }; template <typename R> struct traits<R, meta::when<std::is_trivial<R>::value>> { template <typename T> static constexpr size_t apply(T&& ) noexcept { return sizeof ( remove_cv_t<remove_reference_t<T>> ); } }; template <typename T> constexpr auto mem_usage(T&& v) noexcept -> decltype(traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v))) { return traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v)); } template <typename R> struct traits<R*> { template <typename T> static constexpr auto apply(T* v) noexcept -> decltype( mem_usage_able::mem_usage ( *v ) ) { return sizeof v + (v?mem_usage_able::mem_usage ( *v ):0); } }; } } } } #endif #endif
23.875
125
0.700916
jwakely
3a79ae0112806f5d82d7682409448ed0ad6f2758
634
hpp
C++
source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/** *\file * TestBufferView.h *\author * Sylvain Doremus */ #ifndef ___D3D11Renderer_BufferView_HPP___ #define ___D3D11Renderer_BufferView_HPP___ #pragma once #include "renderer/D3D11Renderer/D3D11RendererPrerequisites.hpp" namespace ashes::d3d11 { class BufferView { public: BufferView( VkDevice device , VkBufferViewCreateInfo createInfo ); ~BufferView(); inline ID3D11ShaderResourceView * getView()const { return m_view; } inline VkDevice getDevice()const { return m_device; } private: VkDevice m_device; VkBufferViewCreateInfo m_createInfo; ID3D11ShaderResourceView * m_view; }; } #endif
15.85
64
0.757098
DragonJoker
3a79f70814e9b0f0cfaeda0a987dc27d744ba1f5
5,800
cpp
C++
src/xercesc/internal/ValidationContextImpl.cpp
rsn8887/xerces-c-1
be81663b9a6907a0db4d5a893a393865a1ebcbc6
[ "Apache-2.0" ]
486
2018-03-07T17:15:03.000Z
2019-05-06T20:05:44.000Z
src/xercesc/internal/ValidationContextImpl.cpp
rsn8887/xerces-c-1
be81663b9a6907a0db4d5a893a393865a1ebcbc6
[ "Apache-2.0" ]
172
2019-05-14T18:56:36.000Z
2022-03-30T16:35:24.000Z
src/xercesc/internal/ValidationContextImpl.cpp
rsn8887/xerces-c-1
be81663b9a6907a0db4d5a893a393865a1ebcbc6
[ "Apache-2.0" ]
83
2019-05-29T18:38:36.000Z
2022-03-17T07:34:16.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/ValidationContextImpl.hpp> #include <xercesc/framework/XMLRefInfo.hpp> #include <xercesc/validators/DTD/DTDEntityDecl.hpp> #include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp> #include <xercesc/validators/schema/NamespaceScope.hpp> #include <xercesc/internal/ElemStack.hpp> #include <xercesc/internal/XMLScanner.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Constructor and Destructor // --------------------------------------------------------------------------- ValidationContextImpl::~ValidationContextImpl() { if (fIdRefList) delete fIdRefList; } ValidationContextImpl::ValidationContextImpl(MemoryManager* const manager) :ValidationContext(manager) ,fIdRefList(0) ,fEntityDeclPool(0) ,fToCheckIdRefList(true) ,fValidatingMemberType(0) ,fElemStack(0) ,fScanner(0) ,fNamespaceScope(0) { fIdRefList = new (fMemoryManager) RefHashTableOf<XMLRefInfo>(109, fMemoryManager); } /** * IdRefList * */ RefHashTableOf<XMLRefInfo>* ValidationContextImpl::getIdRefList() const { return fIdRefList; } void ValidationContextImpl::setIdRefList(RefHashTableOf<XMLRefInfo>* const newIdRefList) { if (fIdRefList) delete fIdRefList; fIdRefList = newIdRefList; } void ValidationContextImpl::clearIdRefList() { if (fIdRefList) fIdRefList->removeAll(); } void ValidationContextImpl::addId(const XMLCh * const content) { if (!fIdRefList || !fToCheckIdRefList) return; XMLRefInfo* idEntry = fIdRefList->get(content); if (idEntry) { if (idEntry->getDeclared()) { ThrowXMLwithMemMgr1(InvalidDatatypeValueException , XMLExcepts::VALUE_ID_Not_Unique , content , fMemoryManager); } } else { idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager); fIdRefList->put((void*)idEntry->getRefName(), idEntry); } // // Mark it declared // idEntry->setDeclared(true); } void ValidationContextImpl::addIdRef(const XMLCh * const content) { if (!fIdRefList || !fToCheckIdRefList) return; XMLRefInfo* idEntry = fIdRefList->get(content); if (!idEntry) { idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager); fIdRefList->put((void*)idEntry->getRefName(), idEntry); } // // Mark it used // idEntry->setUsed(true); } void ValidationContextImpl::toCheckIdRefList(bool toCheck) { fToCheckIdRefList = toCheck; } /** * EntityDeclPool * */ const NameIdPool<DTDEntityDecl>* ValidationContextImpl::getEntityDeclPool() const { return fEntityDeclPool; } const NameIdPool<DTDEntityDecl>* ValidationContextImpl::setEntityDeclPool(const NameIdPool<DTDEntityDecl>* const newEntityDeclPool) { // we don't own it so we return the existing one for the owner to delete const NameIdPool<DTDEntityDecl>* tempPool = fEntityDeclPool; fEntityDeclPool = newEntityDeclPool; return tempPool; } void ValidationContextImpl::checkEntity(const XMLCh * const content) const { if (fEntityDeclPool) { const DTDEntityDecl* decl = fEntityDeclPool->getByKey(content); if (!decl || !decl->isUnparsed()) { ThrowXMLwithMemMgr1(InvalidDatatypeValueException , XMLExcepts::VALUE_ENTITY_Invalid , content , fMemoryManager); } } else { ThrowXMLwithMemMgr1 ( InvalidDatatypeValueException , XMLExcepts::VALUE_ENTITY_Invalid , content , fMemoryManager ); } } /* QName */ bool ValidationContextImpl::isPrefixUnknown(XMLCh* prefix) { bool unknown = false; if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) { return true; } else if (!XMLString::equals(prefix, XMLUni::fgXMLString)) { if(fElemStack && !fElemStack->isEmpty()) fElemStack->mapPrefixToURI(prefix, unknown); else if(fNamespaceScope) unknown = (fNamespaceScope->getNamespaceForPrefix(prefix)==fNamespaceScope->getEmptyNamespaceId()); } return unknown; } const XMLCh* ValidationContextImpl::getURIForPrefix(XMLCh* prefix) { bool unknown = false; unsigned int uriId = 0; if(fElemStack) uriId = fElemStack->mapPrefixToURI(prefix, unknown); else if(fNamespaceScope) { uriId = fNamespaceScope->getNamespaceForPrefix(prefix); unknown = uriId == fNamespaceScope->getEmptyNamespaceId(); } if (!unknown) return fScanner->getURIText(uriId); return XMLUni::fgZeroLenString; } XERCES_CPP_NAMESPACE_END
26.605505
131
0.648276
rsn8887
3a7bbd57a30f1c50d1cdcbea7e816a3f1cbd565e
267
inl
C++
ace/OS_NS_math.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
ace/OS_NS_math.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
ace/OS_NS_math.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
// -*- C++ -*- // $Id: OS_NS_math.inl 1861 2011-08-31 16:18:08Z mesnierp $ ACE_BEGIN_VERSIONED_NAMESPACE_DECL namespace ACE_OS { ACE_INLINE double log2 (double x) { return ace_log2_helper (x); } } // ACE_OS namespace ACE_END_VERSIONED_NAMESPACE_DECL
15.705882
59
0.70412
binary42
3a808b47a696adfe6813a4eb586d4916de517bab
6,734
hpp
C++
MathIO.hpp
Elfhir/WoodyNatasha
febdae58ca3ad16fdf2b5fc4273b7ab177ed392f
[ "Beerware" ]
1
2015-01-30T22:30:57.000Z
2015-01-30T22:30:57.000Z
MathIO.hpp
Elfhir/WoodyNatasha
febdae58ca3ad16fdf2b5fc4273b7ab177ed392f
[ "Beerware" ]
null
null
null
MathIO.hpp
Elfhir/WoodyNatasha
febdae58ca3ad16fdf2b5fc4273b7ab177ed392f
[ "Beerware" ]
null
null
null
/* * Anti-doublon */ #ifndef __OPENKN_MATH__MATH_IO_HPP__ #define __OPENKN_MATH__MATH_IO_HPP__ /* * External Includes */ #include <cstring> #include <iostream> #include <fstream> #include <vector> #include <sstream> #include "Eigen/Dense" using namespace Eigen; /* * Namespace */ namespace kn { /** * \cond * \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function. * \param matrixFile the input matrix ifstream * \return true if the matrix format is spefifyed, false otherwise * \throw MathException invalid format */ bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &row, unsigned int &column); /// \endcond /** * \cond * \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function. * \param matrixFile the input matrix ifstream * \return true if the matrix format is spefifyed, false otherwise * \throw MathException invalid format */ bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &mat); /// \endcond /** * \brief Load a Matrix from a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content. * \param M the Matrix to be loaded * \param fileName the name of the file to open * \throw MathException matrix size is incorrect / error opening file / invalid format */ template <class EigenMatrix> void loadMatrix(EigenMatrix &M, const std::string &fileName){ // open the file std::ifstream matrixFile(fileName.c_str()); if(!matrixFile.is_open()){ std::cerr << "error opening file : " << fileName << std::endl; exit(0); } // read header unsigned int row = 0; unsigned int column = 0; bool header = readMatrixHeader(matrixFile,row,column); // read the data if(header) readMatrixFromHeader(M,matrixFile,row,column); else readMatrix(M,matrixFile); // close matrixFile.close(); } /** * \cond * \brief read the content of a Matrix from the header information (row,col); the user should not use this function. * \param M the Matrix to be filled * \param matrixFile the input matrix ifstream * \param row the expected matrix row number * \param column the expected matrix column number * \throw MathException incompatible matrix size */ template <class EigenMatrix> void readMatrixFromHeader(EigenMatrix &M, std::ifstream &matrixFile, const unsigned int &row, const unsigned int &column) { // if the matrix is already build if((unsigned int)M.rows() != row || (unsigned int)M.cols() != column) M.resize(row,column); // read the matrix for(unsigned int i=0; i<row; ++i) for(unsigned int j=0; j<column; ++j) matrixFile >> M(i,j); } /// \endcond /** * \cond * \brief read the content of a Matrix without any size information (row,col); the user should not use this function. * \param M the Matrix to be filled * \param matrixFile the input matrix ifstream * \throw MathException incompatible matrix size / invalid matrix file */ template <class EigenMatrix> void readMatrix(EigenMatrix &M, std::ifstream &matrixFile){ unsigned int row = 0; int column = -1; // unknown while you didn't read a line std::vector<double> content; std::string stringContent; // first read the matrix in a std::vector to check the consistency of the data do{ // for every line std::getline(matrixFile,stringContent); std::istringstream readContent(stringContent, std::istringstream::in); unsigned int index = 0; while(!readContent.eof() && stringContent != ""){ // for every element of a line double value; readContent >> value; content.push_back(value); index++; } // remove the eof //content.erase(content.end()-1); //index--; if(column == -1 && index != 0){ // 1st line : find 'column' column = index; row++; }else{ if(index != 0){ // check empty line or invalid column if(column != (int)index ){ std::cerr << "readMatrix : invalid matrix file" << std::endl; exit(0); }else row++; }else{ //Matrix reading complete (empty line found) break; } } } while(!matrixFile.eof()); if(row==0 && column==-1) return; // if the matrix is already build if((unsigned int)M.rows() != row || M.cols() != column) M.resize(row,column); // copy the data for(unsigned int i=0; i<row; ++i) for(int j=0; j<column; ++j) M(i,j) = content[i*column+j]; //std::copy(content.begin(), content.end(), M.data()); } /// \endcond /** * \brief Export a Matrix in a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content. * \param M the Matrix to be exported * \param fileName the name of the target file * \param headerMode if true, write the number of row and colums before the data, else write directly the data * \param comments add some comments at the begining of the file, the caracter "#" is automatically added * \throw MathException error opening file */ template <class EigenMatrix> void saveMatrix(const EigenMatrix &M, const std::string &fileName, const bool headerMode = false, const std::string &comments = "") { // open the file std::ofstream matrixFile(fileName.c_str()); if(!matrixFile.is_open()){ std::cerr << "error opening file : " << fileName << std::endl; exit(0); } // write comments if(comments != "") matrixFile << "# " << comments << std::endl; // write header if(headerMode) matrixFile << "row " << M.rows() << std::endl << "col " << M.cols() << std::endl; // additional line if(comments != "" || headerMode) matrixFile << std::endl; // write matrix content for (unsigned int i=0; i<(unsigned int)M.rows(); ++i){ for (unsigned int j=0; j<(unsigned int)M.cols(); ++j) matrixFile << M(i,j) << " "; matrixFile << std::endl; } // close file matrixFile.close(); } /* * End of Namespace */ } /* * End of Anti-doublon */ #endif
29.665198
250
0.619246
Elfhir
3a8263eabf5396b9aa9415df7bb9ce3be77a3a21
18,274
cpp
C++
cegui/src/widgets/Scrollbar.cpp
rpaciorek/cegui
f64435721df7d0ef0393bf7ace72473d1da1f1ac
[ "MIT" ]
257
2020-01-03T10:13:29.000Z
2022-03-26T14:55:12.000Z
cegui/src/widgets/Scrollbar.cpp
rpaciorek/cegui
f64435721df7d0ef0393bf7ace72473d1da1f1ac
[ "MIT" ]
116
2020-01-09T18:13:13.000Z
2022-03-15T18:32:02.000Z
cegui/src/widgets/Scrollbar.cpp
rpaciorek/cegui
f64435721df7d0ef0393bf7ace72473d1da1f1ac
[ "MIT" ]
58
2020-01-09T03:07:02.000Z
2022-03-22T17:21:36.000Z
/*********************************************************************** created: 13/4/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/Scrollbar.h" #include "CEGUI/widgets/Thumb.h" #include "CEGUI/WindowManager.h" #include "CEGUI/Exceptions.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const String Scrollbar::EventNamespace("Scrollbar"); const String Scrollbar::WidgetTypeName("CEGUI/Scrollbar"); //----------------------------------------------------------------------------// const String Scrollbar::EventScrollPositionChanged("ScrollPositionChanged"); const String Scrollbar::EventThumbTrackStarted("ThumbTrackStarted"); const String Scrollbar::EventThumbTrackEnded("ThumbTrackEnded"); const String Scrollbar::EventScrollConfigChanged("ScrollConfigChanged"); //----------------------------------------------------------------------------// const String Scrollbar::ThumbName("__auto_thumb__"); const String Scrollbar::IncreaseButtonName("__auto_incbtn__"); const String Scrollbar::DecreaseButtonName("__auto_decbtn__"); //----------------------------------------------------------------------------// ScrollbarWindowRenderer::ScrollbarWindowRenderer(const String& name) : WindowRenderer(name, Scrollbar::EventNamespace) { } //----------------------------------------------------------------------------// Scrollbar::Scrollbar(const String& type, const String& name) : Window(type, name), d_documentSize(1.0f), d_pageSize(0.0f), d_stepSize(1.0f), d_overlapSize(0.0f), d_position(0.0f), d_endLockPosition(false) { addScrollbarProperties(); } //----------------------------------------------------------------------------// Scrollbar::~Scrollbar(void) { } //----------------------------------------------------------------------------// void Scrollbar::initialiseComponents() { // Set up thumb Thumb* const t = getThumb(); t->subscribeEvent(Thumb::EventThumbPositionChanged, Event::Subscriber(&CEGUI::Scrollbar::handleThumbMoved, this)); t->subscribeEvent(Thumb::EventThumbTrackStarted, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackStarted, this)); t->subscribeEvent(Thumb::EventThumbTrackEnded, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackEnded, this)); // set up Increase button getIncreaseButton()-> subscribeEvent(PushButton::EventCursorPressHold, Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked, this)); // set up Decrease button getDecreaseButton()-> subscribeEvent(PushButton::EventCursorPressHold, Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked, this)); // do initial layout Window::initialiseComponents(); } //----------------------------------------------------------------------------// void Scrollbar::setDocumentSize(float document_size) { if (d_documentSize != document_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_documentSize = document_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setPageSize(float page_size) { if (d_pageSize != page_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_pageSize = page_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setStepSize(float step_size) { if (d_stepSize != step_size) { d_stepSize = step_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setOverlapSize(float overlap_size) { if (d_overlapSize != overlap_size) { d_overlapSize = overlap_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setScrollPosition(float position) { const bool modified = setScrollPosition_impl(position); updateThumb(); // notification if required if (modified) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// bool Scrollbar::validateWindowRenderer(const WindowRenderer* renderer) const { return dynamic_cast<const ScrollbarWindowRenderer*>(renderer) != nullptr; } //----------------------------------------------------------------------------// void Scrollbar::onScrollPositionChanged(WindowEventArgs& e) { fireEvent(EventScrollPositionChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackStarted(WindowEventArgs& e) { fireEvent(EventThumbTrackStarted, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackEnded(WindowEventArgs& e) { fireEvent(EventThumbTrackEnded, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onScrollConfigChanged(WindowEventArgs& e) { performChildLayout(false, false); fireEvent(EventScrollConfigChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onCursorPressHold(CursorInputEventArgs& e) { // base class processing Window::onCursorPressHold(e); if (e.source != CursorInputSource::Left) return; const float adj = getAdjustDirectionFromPoint(e.position); if (adj > 0) scrollForwardsByPage(); else if (adj < 0) scrollBackwardsByPage(); ++e.handled; } //----------------------------------------------------------------------------// void Scrollbar::onScroll(CursorInputEventArgs& e) { // base class processing Window::onScroll(e); // scroll by vertical scroll * stepSize setScrollPosition(d_position + d_stepSize * -e.scroll); // ensure the message does not go to our parent. ++e.handled; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbMoved(const EventArgs&) { // adjust scroll bar position as required. setScrollPosition(getValueFromThumb()); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleIncreaseClicked(const EventArgs& e) { if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left) return false; scrollForwardsByStep(); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleDecreaseClicked(const EventArgs& e) { if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left) return false; scrollBackwardsByStep(); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackStarted(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackStarted(args); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackEnded(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackEnded(args); return true; } //----------------------------------------------------------------------------// void Scrollbar::addScrollbarProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(Scrollbar, float, "DocumentSize", "Property to get/set the document size for the Scrollbar. Value is a float.", &Scrollbar::setDocumentSize, &Scrollbar::getDocumentSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "PageSize", "Property to get/set the page size for the Scrollbar. Value is a float.", &Scrollbar::setPageSize, &Scrollbar::getPageSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "StepSize", "Property to get/set the step size for the Scrollbar. Value is a float.", &Scrollbar::setStepSize, &Scrollbar::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "OverlapSize", "Property to get/set the overlap size for the Scrollbar. Value is a float.", &Scrollbar::setOverlapSize, &Scrollbar::getOverlapSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "ScrollPosition", "Property to get/set the scroll position of the Scrollbar. Value is a float.", &Scrollbar::setScrollPosition, &Scrollbar::getScrollPosition, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "UnitIntervalScrollPosition", "Property to access the scroll position of the Scrollbar as a value in " "the interval [0, 1]. Value is a float.", &Scrollbar::setUnitIntervalScrollPosition, &Scrollbar::getUnitIntervalScrollPosition, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, bool, "EndLockEnabled", "Property to get/set the 'end lock' mode setting for the Scrollbar. " "Value is either \"true\" or \"false\".", &Scrollbar::setEndLockEnabled, &Scrollbar::isEndLockEnabled, false ); } //----------------------------------------------------------------------------// void Scrollbar::banPropertiesForAutoWindow() { Window::banPropertiesForAutoWindow(); banPropertyFromXML("DocumentSize"); banPropertyFromXML("PageSize"); banPropertyFromXML("StepSize"); banPropertyFromXML("OverlapSize"); banPropertyFromXML("ScrollPosition"); banPropertyFromXML("Visible"); } //----------------------------------------------------------------------------// PushButton* Scrollbar::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } //----------------------------------------------------------------------------// PushButton* Scrollbar::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } //----------------------------------------------------------------------------// Thumb* Scrollbar::getThumb() const { return static_cast<Thumb*>(getChild(ThumbName)); } //----------------------------------------------------------------------------// void Scrollbar::updateThumb(void) { if (!d_windowRenderer) throw InvalidRequestException( "This function must be implemented by the window renderer object " "(no window renderer is assigned.)"); static_cast<ScrollbarWindowRenderer*>(d_windowRenderer)->updateThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getValueFromThumb(void) const { if (!d_windowRenderer) throw InvalidRequestException( "This function must be implemented by the window renderer object " "(no window renderer is assigned.)"); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getValueFromThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const { if (!d_windowRenderer) throw InvalidRequestException( "This function must be implemented by the window renderer object " "(no window renderer is assigned.)"); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getAdjustDirectionFromPoint(pt); } //----------------------------------------------------------------------------// bool Scrollbar::setScrollPosition_impl(const float position) { const float old_pos = d_position; const float max_pos = getMaxScrollPosition(); // limit position to valid range: 0 <= position <= max_pos d_position = (position >= 0) ? ((position <= max_pos) ? position : max_pos) : 0.0f; return d_position != old_pos; } //----------------------------------------------------------------------------// void Scrollbar::setConfig(const float* const document_size, const float* const page_size, const float* const step_size, const float* const overlap_size, const float* const position) { const bool reset_max_position = d_endLockPosition && isAtEnd(); bool config_changed = false; bool position_changed = false; if (document_size && (d_documentSize != *document_size)) { d_documentSize = *document_size; config_changed = true; } if (page_size && (d_pageSize != *page_size)) { d_pageSize = *page_size; config_changed = true; } if (step_size && (d_stepSize != *step_size)) { d_stepSize = *step_size; config_changed = true; } if (overlap_size && (d_overlapSize != *overlap_size)) { d_overlapSize = *overlap_size; config_changed = true; } if (position) position_changed = setScrollPosition_impl(*position); else if (reset_max_position) position_changed = setScrollPosition_impl(getMaxScrollPosition()); // _always_ update the thumb to keep things in sync. (though this // can cause a double-trigger of EventScrollPositionChanged, which // also happens with setScrollPosition anyway). updateThumb(); // // Fire appropriate events based on actions we took. // if (config_changed) { WindowEventArgs args(this); onScrollConfigChanged(args); } if (position_changed) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// float Scrollbar::getMaxScrollPosition() const { // max position is (docSize - pageSize) // but must be at least 0 (in case doc size is very small) return std::max((d_documentSize - d_pageSize), 0.0f); } //----------------------------------------------------------------------------// bool Scrollbar::isAtEnd() const { return d_position >= getMaxScrollPosition(); } //----------------------------------------------------------------------------// void Scrollbar::setEndLockEnabled(const bool enabled) { d_endLockPosition = enabled; } //----------------------------------------------------------------------------// bool Scrollbar::isEndLockEnabled() const { return d_endLockPosition; } //----------------------------------------------------------------------------// float Scrollbar::getUnitIntervalScrollPosition() const { const float range = d_documentSize - d_pageSize; return (range > 0) ? d_position / range : 0.0f; } //----------------------------------------------------------------------------// void Scrollbar::setUnitIntervalScrollPosition(float position) { const float range = d_documentSize - d_pageSize; setScrollPosition(range > 0 ? position * range : 0.0f); } //----------------------------------------------------------------------------// void Scrollbar::scrollForwardsByStep() { setScrollPosition(d_position + d_stepSize); } //----------------------------------------------------------------------------// void Scrollbar::scrollBackwardsByStep() { setScrollPosition(d_position - d_stepSize); } //----------------------------------------------------------------------------// void Scrollbar::scrollForwardsByPage() { setScrollPosition(d_position + (d_pageSize - d_overlapSize)); } //----------------------------------------------------------------------------// void Scrollbar::scrollBackwardsByPage() { setScrollPosition(d_position - (d_pageSize - d_overlapSize)); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
33.045208
105
0.534585
rpaciorek
3a82de6238849e035f2d7e70077ea56728893741
2,008
cpp
C++
src/code/Library/SequentialCounter.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
33
2017-04-13T18:32:42.000Z
2021-12-21T07:53:59.000Z
src/code/Library/SequentialCounter.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
1
2021-09-24T07:21:03.000Z
2021-09-29T23:39:41.000Z
src/code/Library/SequentialCounter.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
5
2017-04-12T17:46:03.000Z
2021-03-31T00:50:12.000Z
/* SequentialCounter.cpp Li-Yi Wei 07/07/2007 */ #include "SequentialCounter.hpp" SequentialCounter::SequentialCounter(void) { // nothing else to do } SequentialCounter::SequentialCounter(const int dimension, const int digit_min, const int digit_max) : Counter(dimension), _digit_min(dimension), _digit_max(dimension), _value(dimension) { for(int i = 0; i < dimension; i++) { _digit_min[i] = digit_min; _digit_max[i] = digit_max; } Reset(); } SequentialCounter::SequentialCounter(const int dimension, const vector<int> & digit_min, const vector<int> & digit_max) : Counter(dimension), _digit_min(digit_min), _digit_max(digit_max), _value(dimension) { Reset(); } SequentialCounter::~SequentialCounter(void) { // nothing to do } int SequentialCounter::Reset(void) { for(unsigned int i = 0; i < _value.size(); i++) { _value[i] = _digit_min[i]; } return 1; } int SequentialCounter::Get(vector<int> & value) const { value = _value; return 1; } int SequentialCounter::Next(void) { unsigned int which_dim = 0; for(which_dim = 0; which_dim < _value.size(); which_dim++) { if(_value[which_dim] < _digit_max[which_dim]) { _value[which_dim]++; for(unsigned int i = 0; i < which_dim; i++) { _value[i] = _digit_min[i]; } break; } } return (which_dim < _value.size()); } int SequentialCounter::Reset(const int dimension, const int digit_min, const int digit_max) { return Reset(dimension, vector<int>(dimension, digit_min), vector<int>(dimension, digit_max)); } int SequentialCounter::Reset(const int dimension, const vector<int> & digit_min, const vector<int> & digit_max) { if(! Counter::Reset(dimension)) { return 0; } else { _value.resize(dimension); _digit_min = digit_min; _digit_max = digit_max; return Reset(); } }
21.136842
205
0.624004
1iyiwei
3a82f5ff6fbda9260f7b1179dd660112d5537c3d
2,130
cpp
C++
Server/Source/App.cpp
deaf80/audiogridder
c688ec21f6d4141308885f725cb05a456b493ec9
[ "MIT" ]
null
null
null
Server/Source/App.cpp
deaf80/audiogridder
c688ec21f6d4141308885f725cb05a456b493ec9
[ "MIT" ]
null
null
null
Server/Source/App.cpp
deaf80/audiogridder
c688ec21f6d4141308885f725cb05a456b493ec9
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Andreas Pohl * Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING) * * Author: Andreas Pohl */ #include "App.hpp" #include <signal.h> #include "Server.hpp" namespace e47 { App::App() : m_menuWindow(this) {} void App::initialise(const String& commandLineParameters) { m_logger = FileLogger::createDateStampedLogger(getApplicationName(), "Main_", ".log", ""); Logger::setCurrentLogger(m_logger); signal(SIGPIPE, SIG_IGN); showSplashWindow(); setSplashInfo("Starting server..."); m_server = std::make_unique<Server>(); m_server->startThread(); } void App::shutdown() { m_server->signalThreadShouldExit(); m_server->waitForThreadToExit(1000); Logger::setCurrentLogger(nullptr); delete m_logger; } void App::restartServer() { hideEditor(); hidePluginList(); hideServerSettings(); m_server->signalThreadShouldExit(); m_server->waitForThreadToExit(1000); m_server = std::make_unique<Server>(); m_server->startThread(); } const KnownPluginList& App::getPluginList() { return m_server->getPluginList(); } void App::showEditor(std::shared_ptr<AudioProcessor> proc, Thread::ThreadID tid, WindowCaptureCallback func) { if (proc->hasEditor()) { std::lock_guard<std::mutex> lock(m_windowMtx); m_windowOwner = tid; m_windowProc = proc; m_windowFunc = func; m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc); } } void App::hideEditor(Thread::ThreadID tid) { if (tid == 0 || tid == m_windowOwner) { std::lock_guard<std::mutex> lock(m_windowMtx); m_window.reset(); m_windowOwner = 0; m_windowProc.reset(); m_windowFunc = nullptr; } } void App::resetEditor() { std::lock_guard<std::mutex> lock(m_windowMtx); m_window.reset(); } void App::restartEditor() { std::lock_guard<std::mutex> lock(m_windowMtx); m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc); } } // namespace e47 // This kicks the whole thing off.. START_JUCE_APPLICATION(e47::App)
25.97561
110
0.679343
deaf80
3a83b3d671dd28684bee0b966cb3455cfbe6a2f7
1,020
cc
C++
CPP/No430.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/No430.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/No430.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
/** * Created by Xiaozhong on 2020/9/19. * Copyright (c) 2020/9/19 Xiaozhong. All rights reserved. */ #include "iostream" #include "vector" #include "algorithm" using namespace std; class Node { public: int val; Node *prev; Node *next; Node *child; }; class Solution { private: Node *dfs(Node *prev, Node *curr) { if (!curr) return prev; // 首先将当前节点和前一个节点连接好 curr->prev = prev; prev->next = curr; // 记录下当前节点的下一个节点,因为在递归操作中,会把 curr 的 next 修改掉,所以先暂存,下面要进行使用 Node *temp = curr->next; // 将分支进行处理 Node *tail = dfs(curr, curr->child); // 断开分支 curr->child = nullptr; // 从分支的尾部和 curr 原来的 next 进行处理 return dfs(tail, temp); } public: Node *flatten(Node *head) { if (!head) return head; // 建立一个虚拟头部节点,方便操作 Node *pseudoHead = new Node(); dfs(pseudoHead, head); // 将虚拟头部节点与主体断开连接 pseudoHead->next->prev = nullptr; return pseudoHead->next; } };
22.173913
66
0.569608
hxz1998
3a85dc37ee71596b99213185c7b10cd5029cd305
9,305
cpp
C++
TAO/CIAO/connectors/dds4ccm/examples/Hello/Sender/Hello_Sender_exec.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/CIAO/connectors/dds4ccm/examples/Hello/Sender/Hello_Sender_exec.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/CIAO/connectors/dds4ccm/examples/Hello/Sender/Hello_Sender_exec.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // $Id: Hello_Sender_exec.cpp 97306 2013-08-31 14:05:50Z johnnyw $ #include "Hello_Sender_exec.h" #include "ace/Guard_T.h" #include "ace/Log_Msg.h" #include "tao/ORB_Core.h" #include "ace/Date_Time.h" #include "ace/OS_NS_unistd.h" #include "ace/Reactor.h" namespace CIAO_Hello_Sender_Impl { // TAO_IDL - Generated from // be/be_visitor_component/facet_exs.cpp:75 //============================================================ // Facet Executor Implementation Class: connector_status_exec_i //============================================================ connector_status_exec_i::connector_status_exec_i ( ::Hello::CCM_Sender_Context_ptr ctx, Atomic_Boolean &ready_to_start) : ciao_context_ ( ::Hello::CCM_Sender_Context::_duplicate (ctx)), ready_to_start_(ready_to_start) { } connector_status_exec_i::~connector_status_exec_i (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("~connector_status_exec_i\n"))); } // Operations from ::CCM_DDS::ConnectorStatusListener void connector_status_exec_i::on_inconsistent_topic ( ::DDS::Topic_ptr /* the_topic */, const ::DDS::InconsistentTopicStatus & /* status */) { /* Your code here. */ } void connector_status_exec_i::on_requested_incompatible_qos ( ::DDS::DataReader_ptr /* the_reader */, const ::DDS::RequestedIncompatibleQosStatus & /* status */) { /* Your code here. */ } void connector_status_exec_i::on_sample_rejected ( ::DDS::DataReader_ptr /* the_reader */, const ::DDS::SampleRejectedStatus & /* status */) { /* Your code here. */ } void connector_status_exec_i::on_offered_deadline_missed ( ::DDS::DataWriter_ptr /* the_writer */, const ::DDS::OfferedDeadlineMissedStatus & /* status */) { /* Your code here. */ } void connector_status_exec_i::on_offered_incompatible_qos ( ::DDS::DataWriter_ptr /* the_writer */, const ::DDS::OfferedIncompatibleQosStatus & /* status */) { /* Your code here. */ } void connector_status_exec_i::on_unexpected_status ( ::DDS::Entity_ptr /* the_entity */, ::DDS::StatusKind status_kind) { if (status_kind == DDS::PUBLICATION_MATCHED_STATUS) { // be aware that when only the sender runs, ready_to_start will never // be true. this->ready_to_start_ = true; } } //============================================================ // Pulse generator //============================================================ pulse_Generator::pulse_Generator (Sender_exec_i &callback) : pulse_callback_ (callback) { } pulse_Generator::~pulse_Generator () { } int pulse_Generator::handle_timeout (const ACE_Time_Value &, const void *) { // Notify the subscribers this->pulse_callback_.tick (); return 0; } //============================================================ // Component Executor Implementation Class: Sender_exec_i //============================================================ Sender_exec_i::Sender_exec_i (void) : rate_ (1), iteration_ (0), iterations_ (1000), log_time_ (false), msg_ ("Hello World!"), ready_to_start_(false) { this->ticker_ = new pulse_Generator (*this); } Sender_exec_i::~Sender_exec_i (void) { delete this->ticker_; } // Supported operations and attributes. // Component attributes and port operations. ::CORBA::ULong Sender_exec_i::rate (void) { return this->rate_; } void Sender_exec_i::rate ( ::CORBA::ULong rate) { if (rate == 0) { rate = 1; } else { this->rate_ = rate; } } ::CORBA::ULong Sender_exec_i::iterations (void) { return this->iterations_; } void Sender_exec_i::iterations ( ::CORBA::ULong iterations) { this->iterations_ = iterations; } char * Sender_exec_i::message (void) { return CORBA::string_dup (this->msg_.c_str()); } void Sender_exec_i::message ( const char * message) { this->msg_ = message; } ::CORBA::Boolean Sender_exec_i::log_time (void) { return this->log_time_; } void Sender_exec_i::log_time ( ::CORBA::Boolean log_time) { this->log_time_ = log_time; } ::CCM_DDS::CCM_ConnectorStatusListener_ptr Sender_exec_i::get_connector_status (void) { if ( ::CORBA::is_nil (this->ciao_connector_status_.in ())) { connector_status_exec_i *tmp = 0; ACE_NEW_RETURN ( tmp, connector_status_exec_i ( this->ciao_context_.in (), this->ready_to_start_), ::CCM_DDS::CCM_ConnectorStatusListener::_nil ()); this->ciao_connector_status_ = tmp; } return ::CCM_DDS::CCM_ConnectorStatusListener::_duplicate ( this->ciao_connector_status_.in ()); } ACE_CString Sender_exec_i::create_message (const ACE_CString &msg) { if (!this->log_time_) return msg; char timestamp[16]; ACE_Date_Time now; ACE_OS::sprintf (timestamp, "%02d.%06d", static_cast<int> (now.second()), static_cast<int> (now.microsec ())); ACE_CString ret (timestamp); ret = ret + " " + msg; return ret.c_str (); } void Sender_exec_i::tick () { // Start writing after DataWriter find first DataReader that matched the // Topic It is still possible that other Readers aren't yet ready to // receive data, for that case in the profile the durability is set to // TRANSIENT_DURABILITY_QOS, so each Reader should receive each message. if(this->ready_to_start_.value()) { if (this->iteration_ < this->iterations_) { Hello::Writer_var writer = this->ciao_context_->get_connection_info_in_data (); if (! ::CORBA::is_nil (writer.in ())) { DDSHello new_msg; ACE_CString msg = create_message (this->msg_); new_msg.hello = msg.c_str (); new_msg.iterator = ++this->iteration_; writer->write_one (new_msg, ::DDS::HANDLE_NIL); ACE_DEBUG ((LM_DEBUG, "Sender_exec_i::tick - " "Written sample: <%C> - <%u>\n", msg.c_str (), new_msg.iterator)); } } else { // We are done this->stop (); } } } void Sender_exec_i::start (void) { ACE_Reactor* reactor = 0; ::CORBA::Object_var ccm_object = this->ciao_context_->get_CCM_object(); if (!::CORBA::is_nil (ccm_object.in ())) { ::CORBA::ORB_var orb = ccm_object->_get_orb (); if (!::CORBA::is_nil (orb.in ())) { reactor = orb->orb_core ()->reactor (); } } if (reactor) { // calculate the interval time long const usec = 1000000 / this->rate_; if (reactor->schedule_timer ( this->ticker_, 0, ACE_Time_Value (3, usec), ACE_Time_Value (0, usec)) == -1) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("Sender_exec_i::start : ") ACE_TEXT ("Error scheduling timer"))); } } else { throw ::CORBA::INTERNAL (); } } void Sender_exec_i::stop (void) { ACE_Reactor* reactor = 0; ::CORBA::Object_var ccm_object = this->ciao_context_->get_CCM_object(); if (!::CORBA::is_nil (ccm_object.in ())) { ::CORBA::ORB_var orb = ccm_object->_get_orb (); if (!::CORBA::is_nil (orb.in ())) { reactor = orb->orb_core ()->reactor (); } } if (reactor) { reactor->cancel_timer (this->ticker_); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Sender_exec_i::stop : Timer canceled.\n"))); } else { throw ::CORBA::INTERNAL (); } if (!this->ready_to_start_.value()) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("Sender_exec_i::stop - ") ACE_TEXT ("Sender never got ready to start\n"))); } } // Operations from Components::SessionComponent. void Sender_exec_i::set_session_context ( ::Components::SessionContext_ptr ctx) { this->ciao_context_ = ::Hello::CCM_Sender_Context::_narrow (ctx); if ( ::CORBA::is_nil (this->ciao_context_.in ())) { throw ::CORBA::INTERNAL (); } } void Sender_exec_i::configuration_complete (void) { /* Your code here. */ } void Sender_exec_i::ccm_activate (void) { this->start (); } void Sender_exec_i::ccm_passivate (void) { this->stop (); } void Sender_exec_i::ccm_remove (void) { /* Your code here. */ } extern "C" HELLO_SENDER_EXEC_Export ::Components::EnterpriseComponent_ptr create_Hello_Sender_Impl (void) { ::Components::EnterpriseComponent_ptr retval = ::Components::EnterpriseComponent::_nil (); ACE_NEW_NORETURN ( retval, Sender_exec_i); return retval; } }
24.106218
85
0.559592
cflowe
3a867f75c013ffe41c376db9a78de4f3d1e29483
1,538
cpp
C++
problem_solving/12_the_love_letter_mystery/main.cpp
JonathanSchmalhofer/HackerRankSandbox
6cb547bdd5b94d6f3d3569dc846e30fbbbf4203b
[ "MIT" ]
1
2020-06-11T16:31:35.000Z
2020-06-11T16:31:35.000Z
problem_solving/12_the_love_letter_mystery/main.cpp
JonathanSchmalhofer/HackerRankSandbox
6cb547bdd5b94d6f3d3569dc846e30fbbbf4203b
[ "MIT" ]
null
null
null
problem_solving/12_the_love_letter_mystery/main.cpp
JonathanSchmalhofer/HackerRankSandbox
6cb547bdd5b94d6f3d3569dc846e30fbbbf4203b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <limits> using namespace std; int count_changes_to_palindrom(string s) { int changes{0}; for (size_t idx = 0; idx < s.length(); ++idx) { auto current_letter = s.at(idx); auto mirror_letter = s.at(s.length() - idx - 1); cout << current_letter << "--" << mirror_letter; // Rule 1 int change_cost{0}; if (int(current_letter) < int(mirror_letter)) { cout << " is not allowed" << endl; } else { change_cost = int(current_letter) - int(mirror_letter); } cout << " costs " << to_string(change_cost) << endl; changes += change_cost; } cout << " Total Cost: " << changes << endl; return changes; } // Complete the theLoveLetterMystery function below. int theLoveLetterMystery(string s) { cout << "Input: " << s << endl; int changes_left = count_changes_to_palindrom(s); cout << "---" << endl; reverse(s.begin(), s.end()); cout << "Reversed: " << s << endl; int changes_right = count_changes_to_palindrom(s); cout << "=================" << endl; return min(changes_left, changes_right); } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { string s; getline(cin, s); int result = theLoveLetterMystery(s); fout << result << "\n"; } fout.close(); return 0; }
25.633333
67
0.553966
JonathanSchmalhofer
3a871a82a1fe6f65822d6c0042bdf31cc37f9e6a
948
cpp
C++
algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if (obstacleGrid.empty() || obstacleGrid[0].empty()){ return 0; } int row = obstacleGrid.size(); int column = obstacleGrid[0].size(); vector<vector<int>> board(row, vector<int>(column, 0)); if (obstacleGrid[0][0] == 1){ return 0; } board[0][0] = 1; for (int i = 1; i < column; ++i){ board[0][i] = (obstacleGrid[0][i] == 1) ? 0 : board[0][i - 1] ; } for (int i = 1; i < row; ++i){ board[i][0] = (obstacleGrid[i][0] == 1) ? 0 : board[i - 1][0]; } for (int i = 1; i < row; i ++){ for (int j = 1; j < column; ++j){ board[i][j] = (obstacleGrid[i][j] == 1) ? 0 : board[i - 1][j] + board[i][j - 1]; } } return board[row - 1][column - 1]; } };
28.727273
96
0.439873
23468234
3a8a336bee0403140fd92bb5b26bbcd45bbae34a
2,626
cc
C++
agent_based_epidemic_sim/core/hazard_transmission_model.cc
Xtuden-com/agent-based-epidemic-sim
49ba724b402605ff85f2892bfbcb6338281fc97c
[ "Apache-2.0" ]
null
null
null
agent_based_epidemic_sim/core/hazard_transmission_model.cc
Xtuden-com/agent-based-epidemic-sim
49ba724b402605ff85f2892bfbcb6338281fc97c
[ "Apache-2.0" ]
null
null
null
agent_based_epidemic_sim/core/hazard_transmission_model.cc
Xtuden-com/agent-based-epidemic-sim
49ba724b402605ff85f2892bfbcb6338281fc97c
[ "Apache-2.0" ]
null
null
null
#include "agent_based_epidemic_sim/core/hazard_transmission_model.h" #include <array> #include <iterator> #include <numeric> #include <vector> #include "absl/random/distributions.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "agent_based_epidemic_sim/core/constants.h" #include "agent_based_epidemic_sim/core/integral_types.h" #include "agent_based_epidemic_sim/core/random.h" #include "agent_based_epidemic_sim/port/logging.h" namespace abesim { // TODO: Fix variable naming in this implementation. For now it is // easiest to simply mirror the python implementation until it is stable. float HazardTransmissionModel::ComputeDose(const float distance, absl::Duration duration, const Exposure* exposure) { const float t = absl::ToDoubleMinutes(duration); const float fd = risk_at_distance_function_(distance); // TODO: Thread these factors through on the Exposure in the // Location phase (e.g. Location::ProcessVisits). const float finf = exposure->infectivity; const float fsym = exposure->symptom_factor; const float floc = exposure->location_transmissibility; const float fage = exposure->susceptibility; const float h = t * fd * finf * fsym * floc * fage; return h; } HealthTransition HazardTransmissionModel::GetInfectionOutcome( absl::Span<const Exposure* const> exposures) { absl::Time latest_exposure_time = absl::InfinitePast(); float sum_dose = 0; for (const Exposure* exposure : exposures) { if (exposure->infectivity == 0 || exposure->symptom_factor == 0 || exposure->location_transmissibility == 0 || exposure->susceptibility == 0) { continue; } latest_exposure_time = std::max(latest_exposure_time, exposure->start_time + exposure->duration); // TODO: Remove proximity_trace. if (exposure->distance >= 0) { sum_dose += ComputeDose(exposure->distance, exposure->duration, exposure); } else { for (const float& proximity : exposure->proximity_trace.values) { sum_dose += ComputeDose(proximity, kProximityTraceInterval, exposure); } } } const float prob_infection = 1 - std::exp(-lambda_ * sum_dose); HealthTransition health_transition; health_transition.time = latest_exposure_time; health_transition.health_state = absl::Bernoulli(GetBitGen(), prob_infection) ? HealthState::EXPOSED : HealthState::SUSCEPTIBLE; return health_transition; } } // namespace abesim
38.057971
80
0.685453
Xtuden-com
3a8a46267c5419858e16d55b76c150540a427a0c
609
cpp
C++
src/Client/App/Dibujadores/Recortes/spritesPersonajesSaltando/RecorteMarioSaltando.cpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
4
2021-02-21T17:12:46.000Z
2021-02-25T20:36:27.000Z
src/Client/App/Dibujadores/Recortes/spritesPersonajesSaltando/RecorteMarioSaltando.cpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
null
null
null
src/Client/App/Dibujadores/Recortes/spritesPersonajesSaltando/RecorteMarioSaltando.cpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
2
2021-02-20T19:49:33.000Z
2021-02-25T20:35:22.000Z
#include "RecorteMarioSaltando.hpp" #define ESTADOS_MARIO 12 #define DESPLAZAMIENTO_X 20 #define ALTO 28 #define ANCHO 20 RecorteMarioSaltando::RecorteMarioSaltando(){ estadoActual = 0; inicializarEstados(ESTADOS_MARIO,DESPLAZAMIENTO_X,ALTO,ANCHO); } void RecorteMarioSaltando::actualizarSprite(){ if(ciclos%5==0){ estadoActual++; if(estadoActual==11 && ciclos%5==0){ estadoActual=0; } } ciclos++; } SDL_Rect RecorteMarioSaltando::obtenerRecorte(int recorte) { return Recorte::obtenerRecorte(estadoActual); } #include "RecorteMarioSaltando.hpp"
22.555556
66
0.714286
brunograssano
3a8c0426188f56e75e6505fbff3368e99c5555c7
2,433
hpp
C++
src/classical/plim/rm3_graph.hpp
msoeken/cirkit-addon-plim
3af61430ec85754a1c63e50b3284781e80274407
[ "MIT" ]
null
null
null
src/classical/plim/rm3_graph.hpp
msoeken/cirkit-addon-plim
3af61430ec85754a1c63e50b3284781e80274407
[ "MIT" ]
null
null
null
src/classical/plim/rm3_graph.hpp
msoeken/cirkit-addon-plim
3af61430ec85754a1c63e50b3284781e80274407
[ "MIT" ]
null
null
null
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2016 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * @file rm3_graph.hpp * * @brief A dedicated data-structure for RM3 graphs * * @author Mathias Soeken * @since 2.3 */ #ifndef RM3_GRAPH_HPP #define RM3_GRAPH_HPP #include <iostream> #include <string> #include <unordered_map> #include <vector> #include <core/utils/hash_utils.hpp> namespace cirkit { using rm3_node = unsigned; class rm3_graph { public: rm3_graph( unsigned num_vars = 0u ); void create_po( const rm3_node& n, const std::string& name = std::string() ); rm3_node create_rm3( const rm3_node& x, const rm3_node& y, const rm3_node& z ); rm3_node create_not( const rm3_node& x ); unsigned num_gates() const; unsigned num_inputs() const; unsigned num_outputs() const; void print_statistics( std::ostream& os ) const; private: unsigned num_vars = 0u; std::vector<unsigned> nodes; std::vector<std::string> inputs; std::vector<std::pair<unsigned, std::string>> outputs; using rm3_graph_hash_key_t = std::tuple<rm3_node, rm3_node, rm3_node>; std::unordered_map<rm3_graph_hash_key_t, rm3_node, hash<rm3_graph_hash_key_t>> strash; }; } #endif // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
28.290698
88
0.733251
msoeken
3a8c17345fb877dd3920a09cafc7e902fcbe306d
13,473
cpp
C++
modules/calib3d/test/test_chessboardgenerator.cpp
satnamsingh8912/opencv
9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6
[ "BSD-3-Clause" ]
163
2019-06-04T02:00:58.000Z
2022-03-26T14:23:10.000Z
modules/calib3d/test/test_chessboardgenerator.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
8
2019-11-03T10:16:58.000Z
2022-03-16T17:00:14.000Z
modules/calib3d/test/test_chessboardgenerator.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
29
2019-01-08T05:43:58.000Z
2022-03-24T00:07:03.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "test_chessboardgenerator.hpp" namespace cv { ChessBoardGenerator::ChessBoardGenerator(const Size& _patternSize) : sensorWidth(32), sensorHeight(24), squareEdgePointsNum(200), min_cos(std::sqrt(3.f)*0.5f), cov(0.5), patternSize(_patternSize), rendererResolutionMultiplier(4), tvec(Mat::zeros(1, 3, CV_32F)) { rvec.create(3, 1, CV_32F); cvtest::Rodrigues(Mat::eye(3, 3, CV_32F), rvec); } void ChessBoardGenerator::generateEdge(const Point3f& p1, const Point3f& p2, vector<Point3f>& out) const { Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum); for(size_t n = 0; n < squareEdgePointsNum; ++n) out.push_back( p1 + step * (float)n); } Size ChessBoardGenerator::cornersSize() const { return Size(patternSize.width-1, patternSize.height-1); } struct Mult { float m; Mult(int mult) : m((float)mult) {} Point2f operator()(const Point2f& p)const { return p * m; } }; void ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const { RNG& rng = theRNG(); Vec3f n; for(;;) { n[0] = rng.uniform(-1.f, 1.f); n[1] = rng.uniform(-1.f, 1.f); n[2] = rng.uniform(0.0f, 1.f); float len = (float)norm(n); if (len < 1e-3) continue; n[0]/=len; n[1]/=len; n[2]/=len; if (n[2] > min_cos) break; } Vec3f n_temp = n; n_temp[0] += 100; Vec3f b1 = n.cross(n_temp); Vec3f b2 = n.cross(b1); float len_b1 = (float)norm(b1); float len_b2 = (float)norm(b2); pb1 = Point3f(b1[0]/len_b1, b1[1]/len_b1, b1[2]/len_b1); pb2 = Point3f(b2[0]/len_b1, b2[1]/len_b2, b2[2]/len_b2); } Mat ChessBoardGenerator::generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Point3f& zero, const Point3f& pb1, const Point3f& pb2, float sqWidth, float sqHeight, const vector<Point3f>& whole, vector<Point2f>& corners) const { vector< vector<Point> > squares_black; for(int i = 0; i < patternSize.width; ++i) for(int j = 0; j < patternSize.height; ++j) if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) ) { vector<Point3f> pts_square3d; vector<Point2f> pts_square2d; Point3f p1 = zero + (i + 0) * sqWidth * pb1 + (j + 0) * sqHeight * pb2; Point3f p2 = zero + (i + 1) * sqWidth * pb1 + (j + 0) * sqHeight * pb2; Point3f p3 = zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2; Point3f p4 = zero + (i + 0) * sqWidth * pb1 + (j + 1) * sqHeight * pb2; generateEdge(p1, p2, pts_square3d); generateEdge(p2, p3, pts_square3d); generateEdge(p3, p4, pts_square3d); generateEdge(p4, p1, pts_square3d); projectPoints(Mat(pts_square3d), rvec, tvec, camMat, distCoeffs, pts_square2d); squares_black.resize(squares_black.size() + 1); vector<Point2f> temp; approxPolyDP(Mat(pts_square2d), temp, 1.0, true); transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier)); } /* calculate corners */ corners3d.clear(); for(int j = 0; j < patternSize.height - 1; ++j) for(int i = 0; i < patternSize.width - 1; ++i) corners3d.push_back(zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2); corners.clear(); projectPoints(Mat(corners3d), rvec, tvec, camMat, distCoeffs, corners); vector<Point3f> whole3d; vector<Point2f> whole2d; generateEdge(whole[0], whole[1], whole3d); generateEdge(whole[1], whole[2], whole3d); generateEdge(whole[2], whole[3], whole3d); generateEdge(whole[3], whole[0], whole3d); projectPoints(Mat(whole3d), rvec, tvec, camMat, distCoeffs, whole2d); vector<Point2f> temp_whole2d; approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true); vector< vector<Point > > whole_contour(1); transform(temp_whole2d.begin(), temp_whole2d.end(), back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier)); Mat result; if (rendererResolutionMultiplier == 1) { result = bg.clone(); drawContours(result, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA); drawContours(result, squares_black, -1, Scalar::all(0), FILLED, LINE_AA); } else { Mat tmp; resize(bg, tmp, bg.size() * rendererResolutionMultiplier, 0, 0, INTER_LINEAR_EXACT); drawContours(tmp, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA); drawContours(tmp, squares_black, -1, Scalar::all(0), FILLED, LINE_AA); resize(tmp, result, bg.size(), 0, 0, INTER_AREA); } return result; } Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const { cov = std::min(cov, 0.8); double fovx, fovy, focalLen; Point2d principalPoint; double aspect; calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight, fovx, fovy, focalLen, principalPoint, aspect); RNG& rng = theRNG(); float d1 = static_cast<float>(rng.uniform(0.1, 10.0)); float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180); float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180); Point3f p; p.z = cos(ah) * d1; p.x = sin(ah) * d1; p.y = p.z * tan(av); Point3f pb1, pb2; generateBasis(pb1, pb2); float cbHalfWidth = static_cast<float>(norm(p) * sin( std::min(fovx, fovy) * 0.5 * CV_PI / 180)); float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width; float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; vector<Point3f> pts3d(4); vector<Point2f> pts2d(4); for(;;) { pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; /* can remake with better perf */ projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0; bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0; bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0; bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0; if (inrect1 && inrect2 && inrect3 && inrect4) break; cbHalfWidth*=0.8f; cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width; cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; } Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; float sqWidth = 2 * cbHalfWidth/patternSize.width; float sqHeight = 2 * cbHalfHeight/patternSize.height; return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners); } Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, vector<Point2f>& corners) const { cov = std::min(cov, 0.8); double fovx, fovy, focalLen; Point2d principalPoint; double aspect; calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight, fovx, fovy, focalLen, principalPoint, aspect); RNG& rng = theRNG(); float d1 = static_cast<float>(rng.uniform(0.1, 10.0)); float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180); float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180); Point3f p; p.z = cos(ah) * d1; p.x = sin(ah) * d1; p.y = p.z * tan(av); Point3f pb1, pb2; generateBasis(pb1, pb2); float cbHalfWidth = squareSize.width * patternSize.width * 0.5f; float cbHalfHeight = squareSize.height * patternSize.height * 0.5f; float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; vector<Point3f> pts3d(4); vector<Point2f> pts2d(4); for(;;) { pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; /* can remake with better perf */ projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0; bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0; bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0; bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0; if ( inrect1 && inrect2 && inrect3 && inrect4) break; p.z *= 1.1f; } Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, squareSize.width, squareSize.height, pts3d, corners); } Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, const Point3f& pos, vector<Point2f>& corners) const { cov = std::min(cov, 0.8); Point3f p = pos; Point3f pb1, pb2; generateBasis(pb1, pb2); float cbHalfWidth = squareSize.width * patternSize.width * 0.5f; float cbHalfHeight = squareSize.height * patternSize.height * 0.5f; float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; vector<Point3f> pts3d(4); vector<Point2f> pts2d(4); pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; /* can remake with better perf */ projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, squareSize.width, squareSize.height, pts3d, corners); } } // namespace
40.581325
125
0.61768
satnamsingh8912
3a8ccd33b7f16948c3f3fdf813b7a86a98a607dc
105,333
cpp
C++
kit/Kit.cpp
CaptainVal/online
a5de33496ccd27ca6d11a245c69f70fd28457092
[ "BSD-2-Clause" ]
1
2021-07-25T06:22:35.000Z
2021-07-25T06:22:35.000Z
kit/Kit.cpp
CaptainVal/online
a5de33496ccd27ca6d11a245c69f70fd28457092
[ "BSD-2-Clause" ]
null
null
null
kit/Kit.cpp
CaptainVal/online
a5de33496ccd27ca6d11a245c69f70fd28457092
[ "BSD-2-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * The main entry point for the LibreOfficeKit process serving * a document editing session. */ #include <config.h> #include <dlfcn.h> #ifdef __linux__ #include <ftw.h> #include <sys/vfs.h> #include <linux/magic.h> #include <sys/capability.h> #include <sys/sysmacros.h> #endif #ifdef __FreeBSD__ #include <sys/capsicum.h> #include <ftw.h> #define FTW_CONTINUE 0 #define FTW_STOP (-1) #define FTW_SKIP_SUBTREE 0 #define FTW_ACTIONRETVAL 0 #endif #include <unistd.h> #include <utime.h> #include <sys/time.h> #include <sys/resource.h> #include <sysexits.h> #include <atomic> #include <cassert> #include <climits> #include <condition_variable> #include <chrono> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <string> #include <sstream> #include <thread> #define LOK_USE_UNSTABLE_API #include <LibreOfficeKit/LibreOfficeKitInit.h> #include <Poco/File.h> #include <Poco/Exception.h> #include <Poco/JSON/Object.h> #include <Poco/JSON/Parser.h> #include <Poco/Net/Socket.h> #include <Poco/URI.h> #include "ChildSession.hpp" #include <Common.hpp> #include <MobileApp.hpp> #include <FileUtil.hpp> #include <common/JailUtil.hpp> #include <common/JsonUtil.hpp> #include "KitHelper.hpp" #include "Kit.hpp" #include <Protocol.hpp> #include <Log.hpp> #include <Png.hpp> #include <Rectangle.hpp> #include <TileDesc.hpp> #include <Unit.hpp> #include <UserMessages.hpp> #include <Util.hpp> #include "Watermark.hpp" #include "RenderTiles.hpp" #include "SetupKitEnvironment.hpp" #include <common/ConfigUtil.hpp> #include <common/TraceEvent.hpp> #if !MOBILEAPP #include <common/SigUtil.hpp> #include <common/Seccomp.hpp> #include <utility> #endif #ifdef FUZZER #include <kit/DummyLibreOfficeKit.hpp> #include <wsd/COOLWSD.hpp> #endif #if MOBILEAPP #include "COOLWSD.hpp" #endif #ifdef IOS #include "ios.h" #endif #define LIB_SOFFICEAPP "lib" "sofficeapp" ".so" #define LIB_MERGED "lib" "mergedlo" ".so" using Poco::Exception; using Poco::File; using Poco::JSON::Array; using Poco::JSON::Object; using Poco::JSON::Parser; using Poco::URI; #ifndef BUILDING_TESTS using Poco::Path; #endif using namespace COOLProtocol; extern "C" { void dump_kit_state(void); /* easy for gdb */ } #if !MOBILEAPP // A Kit process hosts only a single document in its lifetime. class Document; static Document *singletonDocument = nullptr; #endif /// Used for test code to accelerating waiting until idle and to /// flush sockets with a 'processtoidle' -> 'idle' reply. static std::chrono::steady_clock::time_point ProcessToIdleDeadline; #ifndef BUILDING_TESTS static bool AnonymizeUserData = false; static uint64_t AnonymizationSalt = 82589933; #endif /// When chroot is enabled, this is blank as all /// the paths inside the jail, relative to it's jail. /// E.g. /tmp/user/docs/... /// However, without chroot, the jail path is /// absolute in the system root. /// I.e. ChildRoot/JailId/tmp/user/docs/... /// We need to know where the jail really is /// because WSD doesn't know if chroot will succeed /// or fail, but it assumes the document path to /// be relative to the root of the jail (i.e. chroot /// expected to succeed). If it fails, or when caps /// are disabled, file paths would be relative to the /// system root, not the jail. static std::string JailRoot; #if !MOBILEAPP static void flushTraceEventRecordings(); #endif // Abnormally we get LOK events from another thread, which must be // push safely into our main poll loop to process to keep all // socket buffer & event processing in a single, thread. bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data); #if !MOBILEAPP static LokHookFunction2* initFunction = nullptr; namespace { #ifndef BUILDING_TESTS enum class LinkOrCopyType { All, LO }; LinkOrCopyType linkOrCopyType; std::string sourceForLinkOrCopy; Path destinationForLinkOrCopy; bool forceInitialCopy; // some stackable file-systems have very slow first hard link creation std::string linkableForLinkOrCopy; // Place to stash copies that we can hard-link from std::chrono::time_point<std::chrono::steady_clock> linkOrCopyStartTime; bool linkOrCopyVerboseLogging = false; unsigned linkOrCopyFileCount = 0; // Track to help quantify the link-or-copy performance. constexpr unsigned SlowLinkOrCopyLimitInSecs = 2; // After this many seconds, start spamming the logs. bool detectSlowStackingFileSystem(const std::string &directory) { #ifdef __linux__ #ifndef OVERLAYFS_SUPER_MAGIC // From linux/magic.h. #define OVERLAYFS_SUPER_MAGIC 0x794c7630 #endif struct statfs fs; if (::statfs(directory.c_str(), &fs) != 0) { LOG_SYS("statfs failed on '" << directory << "'"); return false; } switch (fs.f_type) { // case FUSE_SUPER_MAGIC: ? case OVERLAYFS_SUPER_MAGIC: return true; default: return false; } #else (void)directory; return false; #endif } /// Returns the LinkOrCopyType as a human-readable string (for logging). std::string linkOrCopyTypeString(LinkOrCopyType type) { switch (type) { case LinkOrCopyType::LO: return "LibreOffice"; case LinkOrCopyType::All: return "all"; default: assert(!"Unknown LinkOrCopyType."); return "unknown"; } } bool shouldCopyDir(const char *path) { switch (linkOrCopyType) { case LinkOrCopyType::LO: return strcmp(path, "program/wizards") != 0 && strcmp(path, "sdk") != 0 && strcmp(path, "debugsource") != 0 && strcmp(path, "share/basic") != 0 && strncmp(path, "share/extensions/dict-", // preloaded sizeof("share/extensions/dict")) != 0 && strcmp(path, "share/Scripts/java") != 0 && strcmp(path, "share/Scripts/javascript") != 0 && strcmp(path, "share/config/wizard") != 0 && strcmp(path, "readmes") != 0 && strcmp(path, "help") != 0; default: // LinkOrCopyType::All return true; } } bool shouldLinkFile(const char *path) { switch (linkOrCopyType) { case LinkOrCopyType::LO: { if (strstr(path, "LICENSE") || strstr(path, "EULA") || strstr(path, "CREDITS") || strstr(path, "NOTICE")) return false; const char* dot = strrchr(path, '.'); if (!dot) return true; if (!strcmp(dot, ".dbg")) return false; if (!strcmp(dot, ".so")) { // NSS is problematic ... if (strstr(path, "libnspr4") || strstr(path, "libplds4") || strstr(path, "libplc4") || strstr(path, "libnss3") || strstr(path, "libnssckbi") || strstr(path, "libnsutil3") || strstr(path, "libssl3") || strstr(path, "libsoftokn3") || strstr(path, "libsqlite3") || strstr(path, "libfreeblpriv3")) return true; // As is Python ... if (strstr(path, "python-core")) return true; // otherwise drop the rest of the code. return false; } const char *vers; if ((vers = strstr(path, ".so."))) // .so.[digit]+ { for(int i = sizeof (".so."); vers[i] != '\0'; ++i) if (!isdigit(vers[i]) && vers[i] != '.') return true; return false; } return true; } default: // LinkOrCopyType::All return true; } } void linkOrCopyFile(const char* fpath, const std::string& newPath) { ++linkOrCopyFileCount; if (linkOrCopyVerboseLogging) LOG_INF("Linking file \"" << fpath << "\" to \"" << newPath << '"'); if (!forceInitialCopy) { // first try a simple hard-link if (link(fpath, newPath.c_str()) == 0) return; } // else always copy before linking to linkable/ // incrementally build our 'linkable/' copy nearby static bool canChown = true; // only if we can get permissions right if ((forceInitialCopy || errno == EXDEV) && canChown) { // then copy somewhere closer and hard link from there if (!forceInitialCopy) LOG_TRC("link(\"" << fpath << "\", \"" << newPath << "\") failed: " << strerror(errno) << ". Will try to link template."); std::string linkableCopy = linkableForLinkOrCopy + fpath; if (::link(linkableCopy.c_str(), newPath.c_str()) == 0) return; if (errno == ENOENT) { File(Path(linkableCopy).parent()).createDirectories(); if (!FileUtil::copy(fpath, linkableCopy.c_str(), /*log=*/false, /*throw_on_error=*/false)) LOG_TRC("Failed to create linkable copy [" << fpath << "] to [" << linkableCopy.c_str() << "]"); else { // Match system permissions, so a file we can write is not shared across jails. struct stat ownerInfo; if (::stat(fpath, &ownerInfo) != 0 || ::chown(linkableCopy.c_str(), ownerInfo.st_uid, ownerInfo.st_gid) != 0) { LOG_ERR("Failed to stat or chown " << ownerInfo.st_uid << ":" << ownerInfo.st_gid << " " << linkableCopy << ": " << strerror(errno) << " missing cap_chown?, disabling linkable"); unlink(linkableCopy.c_str()); canChown = false; } else if (::link(linkableCopy.c_str(), newPath.c_str()) == 0) return; } } LOG_TRC("link(\"" << linkableCopy << "\", \"" << newPath << "\") failed: " << strerror(errno) << ". Cannot create linkable copy."); } static bool warned = false; if (!warned) { LOG_ERR("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno) << ". Very slow copying path triggered."); warned = true; } else LOG_TRC("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno) << ". Will copy."); if (!FileUtil::copy(fpath, newPath.c_str(), /*log=*/false, /*throw_on_error=*/false)) { LOG_FTL("Failed to copy or link [" << fpath << "] to [" << newPath << "]. Exiting."); Log::shutdown(); std::_Exit(EX_SOFTWARE); } } int linkOrCopyFunction(const char *fpath, const struct stat* sb, int typeflag, struct FTW* /*ftwbuf*/) { if (strcmp(fpath, sourceForLinkOrCopy.c_str()) == 0) { LOG_TRC("nftw: Skipping redundant path: " << fpath); return FTW_CONTINUE; } if (!linkOrCopyVerboseLogging) { const auto durationInSecs = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::steady_clock::now() - linkOrCopyStartTime); if (durationInSecs.count() > SlowLinkOrCopyLimitInSecs) { LOG_WRN("Linking/copying files from " << sourceForLinkOrCopy << " to " << destinationForLinkOrCopy.toString() << " is taking too much time. Enabling verbose link/copy logging."); linkOrCopyVerboseLogging = true; } } assert(fpath[strlen(sourceForLinkOrCopy.c_str())] == '/'); const char *relativeOldPath = fpath + strlen(sourceForLinkOrCopy.c_str()) + 1; const Path newPath(destinationForLinkOrCopy, Path(relativeOldPath)); switch (typeflag) { case FTW_F: case FTW_SLN: File(newPath.parent()).createDirectories(); if (shouldLinkFile(relativeOldPath)) linkOrCopyFile(fpath, newPath.toString()); break; case FTW_D: { struct stat st; if (stat(fpath, &st) == -1) { LOG_SYS("nftw: stat(\"" << fpath << "\") failed"); return FTW_STOP; } if (!shouldCopyDir(relativeOldPath)) { LOG_TRC("nftw: Skipping redundant path: " << relativeOldPath); return FTW_SKIP_SUBTREE; } File(newPath).createDirectories(); struct utimbuf ut; ut.actime = st.st_atime; ut.modtime = st.st_mtime; if (utime(newPath.toString().c_str(), &ut) == -1) { LOG_SYS("nftw: utime(\"" << newPath.toString() << "\") failed"); return FTW_STOP; } } break; case FTW_SL: { const std::size_t size = sb->st_size; char target[size + 1]; const ssize_t written = readlink(fpath, target, size); if (written <= 0 || static_cast<std::size_t>(written) > size) { LOG_SYS("nftw: readlink(\"" << fpath << "\") failed"); Log::shutdown(); std::_Exit(EX_SOFTWARE); } target[written] = '\0'; File(newPath.parent()).createDirectories(); if (symlink(target, newPath.toString().c_str()) == -1) { LOG_SYS("nftw: symlink(\"" << target << "\", \"" << newPath.toString() << "\") failed"); return FTW_STOP; } } break; case FTW_DNR: LOG_ERR("nftw: Cannot read directory '" << fpath << '\''); return FTW_STOP; case FTW_NS: LOG_ERR("nftw: stat failed for '" << fpath << '\''); return FTW_STOP; default: LOG_FTL("nftw: unexpected typeflag: '" << typeflag); assert(!"nftw: unexpected typeflag."); break; } return FTW_CONTINUE; } void linkOrCopy(std::string source, const Path& destination, std::string linkable, LinkOrCopyType type) { std::string resolved = FileUtil::realpath(source); if (resolved != source) { LOG_DBG("linkOrCopy: Using real path [" << resolved << "] instead of original link [" << source << "]."); source = std::move(resolved); } LOG_INF("linkOrCopy " << linkOrCopyTypeString(type) << " from [" << source << "] to [" << destination.toString() << "]."); linkOrCopyType = type; sourceForLinkOrCopy = source; if (sourceForLinkOrCopy.back() == '/') sourceForLinkOrCopy.pop_back(); destinationForLinkOrCopy = destination; linkableForLinkOrCopy = linkable; linkOrCopyFileCount = 0; linkOrCopyStartTime = std::chrono::steady_clock::now(); forceInitialCopy = detectSlowStackingFileSystem(destination.toString()); if (nftw(source.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL|FTW_PHYS) == -1) { LOG_SYS("linkOrCopy: nftw() failed for '" << source << '\''); } if (linkOrCopyVerboseLogging) { linkOrCopyVerboseLogging = false; const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - linkOrCopyStartTime).count(); const double seconds = (ms + 1) / 1000.; // At least 1ms to avoid div-by-zero. const auto rate = linkOrCopyFileCount / seconds; LOG_INF("Linking/Copying of " << linkOrCopyFileCount << " files from " << source << " to " << destinationForLinkOrCopy.toString() << " finished in " << seconds << " seconds, or " << rate << " files / second."); } } #ifndef __FreeBSD__ void dropCapability(cap_value_t capability) { cap_t caps; cap_value_t cap_list[] = { capability }; caps = cap_get_proc(); if (caps == nullptr) { LOG_SFL("cap_get_proc() failed"); Log::shutdown(); std::_Exit(1); } char *capText = cap_to_text(caps, nullptr); LOG_TRC("Capabilities first: " << capText); cap_free(capText); if (cap_set_flag(caps, CAP_EFFECTIVE, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1 || cap_set_flag(caps, CAP_PERMITTED, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1) { LOG_SFL("cap_set_flag() failed"); Log::shutdown(); std::_Exit(1); } if (cap_set_proc(caps) == -1) { LOG_SFL("cap_set_proc() failed"); Log::shutdown(); std::_Exit(1); } capText = cap_to_text(caps, nullptr); LOG_TRC("Capabilities now: " << capText); cap_free(capText); cap_free(caps); } #endif // __FreeBSD__ #endif } #endif /// A document container. /// Owns LOKitDocument instance and connections. /// Manages the lifetime of a document. /// Technically, we can host multiple documents /// per process. But for security reasons don't. /// However, we could have a coolkit instance /// per user or group of users (a trusted circle). class Document final : public DocumentManagerInterface { public: /// We have two types of password protected documents /// 1) Documents which require password to view /// 2) Document which require password to modify enum class PasswordType { ToView, ToModify }; public: Document(const std::shared_ptr<lok::Office>& loKit, const std::string& jailId, const std::string& docKey, const std::string& docId, const std::string& url, std::shared_ptr<TileQueue> tileQueue, const std::shared_ptr<WebSocketHandler>& websocketHandler, unsigned mobileAppDocId) : _loKit(loKit), _jailId(jailId), _docKey(docKey), _docId(docId), _url(url), _obfuscatedFileId(Util::getFilenameFromURL(docKey)), _tileQueue(std::move(tileQueue)), _websocketHandler(websocketHandler), _haveDocPassword(false), _isDocPasswordProtected(false), _docPasswordType(PasswordType::ToView), _stop(false), _editorId(-1), _editorChangeWarning(false), _mobileAppDocId(mobileAppDocId), _inputProcessingEnabled(true) { LOG_INF("Document ctor for [" << _docKey << "] url [" << anonymizeUrl(_url) << "] on child [" << _jailId << "] and id [" << _docId << "]."); assert(_loKit); #if !MOBILEAPP assert(singletonDocument == nullptr); singletonDocument = this; #endif } virtual ~Document() { LOG_INF("~Document dtor for [" << _docKey << "] url [" << anonymizeUrl(_url) << "] on child [" << _jailId << "] and id [" << _docId << "]. There are " << _sessions.size() << " views."); // Wait for the callback worker to finish. _stop = true; _tileQueue->put("eof"); for (const auto& session : _sessions) { session.second->resetDocManager(); } #ifdef IOS DocumentData::deallocate(_mobileAppDocId); #endif } const std::string& getUrl() const { return _url; } /// Post the message - in the unipoll world we're in the right thread anyway bool postMessage(const char* data, int size, const WSOpCode code) const { LOG_TRC("postMessage called with: " << getAbbreviatedMessage(data, size)); if (!_websocketHandler) { LOG_ERR("Child Doc: Bad socket while sending [" << getAbbreviatedMessage(data, size) << "]."); return false; } _websocketHandler->sendMessage(data, size, code); return true; } bool createSession(const std::string& sessionId, int canonicalViewId) { try { if (_sessions.find(sessionId) != _sessions.end()) { LOG_ERR("Session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "] already exists."); return true; } LOG_INF("Creating " << (_sessions.empty() ? "first" : "new") << " session for url: " << anonymizeUrl(_url) << " for sessionId: " << sessionId << " on jailId: " << _jailId); auto session = std::make_shared<ChildSession>( _websocketHandler, sessionId, _jailId, JailRoot, *this); _sessions.emplace(sessionId, session); session->setCanonicalViewId(canonicalViewId); int viewId = session->getViewId(); _lastUpdatedAt[viewId] = std::chrono::steady_clock::now(); _speedCount[viewId] = 0; LOG_DBG("Sessions: " << _sessions.size()); return true; } catch (const std::exception& ex) { LOG_ERR("Exception while creating session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "] - '" << ex.what() << "'."); return false; } } /// Purges dead connections and returns /// the remaining number of clients. /// Returns -1 on failure. std::size_t purgeSessions() { std::vector<std::shared_ptr<ChildSession>> deadSessions; std::size_t num_sessions = 0; { // If there are no live sessions, we don't need to do anything at all and can just // bluntly exit, no need to clean up our own data structures. Also, there is a bug that // causes the deadSessions.clear() call below to crash in some situations when the last // session is being removed. for (auto it = _sessions.cbegin(); it != _sessions.cend(); ) { if (it->second->isCloseFrame()) { deadSessions.push_back(it->second); it = _sessions.erase(it); } else { ++it; } } num_sessions = _sessions.size(); #if !MOBILEAPP if (num_sessions == 0) { LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly."); flushTraceEventRecordings(); Log::shutdown(); std::_Exit(EX_OK); } #endif } deadSessions.clear(); return num_sessions; } /// Set Document password for given URL void setDocumentPassword(int passwordType) { // Log whether the document is password protected and a password is provided LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected << " passwordProvided=" << _haveDocPassword); if (_isDocPasswordProtected && _haveDocPassword) { // it means this is the second attempt with the wrong password; abort the load operation _loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr); return; } // One thing for sure, this is a password protected document _isDocPasswordProtected = true; if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD) _docPasswordType = PasswordType::ToView; else if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY) _docPasswordType = PasswordType::ToModify; LOG_INF("Calling _loKit->setDocumentPassword"); if (_haveDocPassword) _loKit->setDocumentPassword(_jailedUrl.c_str(), _docPassword.c_str()); else _loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr); LOG_INF("setDocumentPassword returned."); } void renderTile(const StringVector& tokens) { TileCombined tileCombined(TileDesc::parse(tokens)); renderTiles(tileCombined, false); } void renderCombinedTiles(const StringVector& tokens) { TileCombined tileCombined = TileCombined::parse(tokens); renderTiles(tileCombined, true); } void renderTiles(TileCombined &tileCombined, bool combined) { // Find a session matching our view / render settings. const auto session = _sessions.findByCanonicalId(tileCombined.getNormalizedViewId()); if (!session) { LOG_ERR("Session is not found. Maybe exited after rendering request."); return; } if (!_loKitDocument) { LOG_ERR("Tile rendering requested before loading document."); return; } if (_loKitDocument->getViewsCount() <= 0) { LOG_ERR("Tile rendering requested without views."); return; } #ifdef FIXME_RENDER_SETTINGS // if necessary select a suitable rendering view eg. with 'show non-printing chars' if (tileCombined.getNormalizedViewId()) _loKitDocument->setView(session->getViewId()); #endif const auto blenderFunc = [&](unsigned char* data, int offsetX, int offsetY, std::size_t pixmapWidth, std::size_t pixmapHeight, int pixelWidth, int pixelHeight, LibreOfficeKitTileMode mode) { if (session->watermark()) session->watermark()->blending(data, offsetX, offsetY, pixmapWidth, pixmapHeight, pixelWidth, pixelHeight, mode); }; const auto postMessageFunc = [&](const char* buffer, std::size_t length) { postMessage(buffer, length, WSOpCode::Binary); }; if (!RenderTiles::doRender(_loKitDocument, tileCombined, _pngCache, _pngPool, combined, blenderFunc, postMessageFunc, _mobileAppDocId)) { LOG_DBG("All tiles skipped, not producing empty tilecombine: message"); return; } } bool sendTextFrame(const std::string& message) { return sendFrame(message.data(), message.size()); } bool sendFrame(const char* buffer, int length, WSOpCode opCode = WSOpCode::Text) override { try { return postMessage(buffer, length, opCode); } catch (const Exception& exc) { LOG_ERR("Document::sendFrame: Exception: " << exc.displayText() << (exc.nested() ? "( " + exc.nested()->displayText() + ')' : "")); } return false; } void alertAllUsers(const std::string& cmd, const std::string& kind) override { alertAllUsers("errortoall: cmd=" + cmd + " kind=" + kind); } unsigned getMobileAppDocId() const override { return _mobileAppDocId; } static void GlobalCallback(const int type, const char* p, void* data) { if (SigUtil::getTerminationFlag()) return; // unusual LOK event from another thread, // pData - is Document with process' lifetime. if (pushToMainThread(GlobalCallback, type, p, data)) return; const std::string payload = p ? p : "(nil)"; Document* self = static_cast<Document*>(data); if (type == LOK_CALLBACK_PROFILE_FRAME) { // We must send the trace data to the WSD process for output LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) << ": " << payload.length() << " bytes."); self->sendTextFrame("traceevent: \n" + payload); return; } LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) << " [" << payload << "]."); if (type == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY || type == LOK_CALLBACK_DOCUMENT_PASSWORD) { // Mark the document password type. self->setDocumentPassword(type); return; } else if (type == LOK_CALLBACK_STATUS_INDICATOR_START || type == LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE || type == LOK_CALLBACK_STATUS_INDICATOR_FINISH) { for (auto& it : self->_sessions) { std::shared_ptr<ChildSession> session = it.second; if (session && !session->isCloseFrame()) { session->loKitCallback(type, payload); } } return; } else if (type == LOK_CALLBACK_JSDIALOG || type == LOK_CALLBACK_HYPERLINK_CLICKED) { if (self->_sessions.size() == 1) { auto it = self->_sessions.begin(); std::shared_ptr<ChildSession> session = it->second; if (session && !session->isCloseFrame()) { session->loKitCallback(type, payload); // TODO. It should filter some messages // before loading the document session->getProtocol()->enableProcessInput(true); } } } // Broadcast leftover status indicator callbacks to all clients self->broadcastCallbackToClients(type, payload); } static void ViewCallback(const int type, const char* p, void* data) { if (SigUtil::getTerminationFlag()) return; // unusual LOK event from another thread. // pData - is CallbackDescriptors which share process' lifetime. if (pushToMainThread(ViewCallback, type, p, data)) return; CallbackDescriptor* descriptor = static_cast<CallbackDescriptor*>(data); assert(descriptor && "Null callback data."); assert(descriptor->getDoc() && "Null Document instance."); std::shared_ptr<TileQueue> tileQueue = descriptor->getDoc()->getTileQueue(); assert(tileQueue && "Null TileQueue."); const std::string payload = p ? p : "(nil)"; LOG_TRC("Document::ViewCallback [" << descriptor->getViewId() << "] [" << lokCallbackTypeToString(type) << "] [" << payload << "]."); // when we examine the content of the JSON std::string targetViewId; if (type == LOK_CALLBACK_CELL_CURSOR) { StringVector tokens(Util::tokenize(payload, ',')); // Payload may be 'EMPTY'. if (tokens.size() == 4) { int cursorX = std::stoi(tokens[0]); int cursorY = std::stoi(tokens[1]); int cursorWidth = std::stoi(tokens[2]); int cursorHeight = std::stoi(tokens[3]); tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight); } } else if (type == LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR) { Poco::JSON::Parser parser; const Poco::Dynamic::Var result = parser.parse(payload); const auto& command = result.extract<Poco::JSON::Object::Ptr>(); std::string rectangle = command->get("rectangle").toString(); StringVector tokens(Util::tokenize(rectangle, ',')); // Payload may be 'EMPTY'. if (tokens.size() == 4) { int cursorX = std::stoi(tokens[0]); int cursorY = std::stoi(tokens[1]); int cursorWidth = std::stoi(tokens[2]); int cursorHeight = std::stoi(tokens[3]); tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight); } } else if (type == LOK_CALLBACK_INVALIDATE_VIEW_CURSOR || type == LOK_CALLBACK_CELL_VIEW_CURSOR) { Poco::JSON::Parser parser; const Poco::Dynamic::Var result = parser.parse(payload); const auto& command = result.extract<Poco::JSON::Object::Ptr>(); targetViewId = command->get("viewId").toString(); std::string part = command->get("part").toString(); std::string text = command->get("rectangle").toString(); StringVector tokens(Util::tokenize(text, ',')); // Payload may be 'EMPTY'. if (tokens.size() == 4) { int cursorX = std::stoi(tokens[0]); int cursorY = std::stoi(tokens[1]); int cursorWidth = std::stoi(tokens[2]); int cursorHeight = std::stoi(tokens[3]); tileQueue->updateCursorPosition(std::stoi(targetViewId), std::stoi(part), cursorX, cursorY, cursorWidth, cursorHeight); } } // merge various callback types together if possible if (type == LOK_CALLBACK_INVALIDATE_TILES || type == LOK_CALLBACK_DOCUMENT_SIZE_CHANGED) { // no point in handling invalidations or page resizes per-view, // all views have to be in sync tileQueue->put("callback all " + std::to_string(type) + ' ' + payload); } else tileQueue->put("callback " + std::to_string(descriptor->getViewId()) + ' ' + std::to_string(type) + ' ' + payload); LOG_TRC("Document::ViewCallback end."); } private: /// Helper method to broadcast callback and its payload to all clients void broadcastCallbackToClients(const int type, const std::string& payload) { _tileQueue->put("callback all " + std::to_string(type) + ' ' + payload); } /// Load a document (or view) and register callbacks. bool onLoad(const std::string& sessionId, const std::string& uriAnonym, const std::string& renderOpts) override { LOG_INF("Loading url [" << uriAnonym << "] for session [" << sessionId << "] which has " << (_sessions.size() - 1) << " sessions."); // This shouldn't happen, but for sanity. const auto it = _sessions.find(sessionId); if (it == _sessions.end() || !it->second) { LOG_ERR("Cannot find session [" << sessionId << "] to load view for."); return false; } std::shared_ptr<ChildSession> session = it->second; try { if (!load(session, renderOpts)) return false; } catch (const std::exception &exc) { LOG_ERR("Exception while loading url [" << uriAnonym << "] for session [" << sessionId << "]: " << exc.what()); return false; } return true; } void onUnload(const ChildSession& session) override { const auto& sessionId = session.getId(); LOG_INF("Unloading session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "]."); const int viewId = session.getViewId(); _tileQueue->removeCursorPosition(viewId); if (_loKitDocument == nullptr) { LOG_ERR("Unloading session [" << sessionId << "] without loKitDocument."); return; } _loKitDocument->setView(viewId); _loKitDocument->registerCallback(nullptr, nullptr); _loKit->registerCallback(nullptr, nullptr); int viewCount = _loKitDocument->getViewsCount(); if (viewCount == 1) { #if !MOBILEAPP if (_sessions.empty()) { LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly."); flushTraceEventRecordings(); Log::shutdown(); std::_Exit(EX_OK); } #endif LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, but has " << _sessions.size() << " sessions still. Destroying the document."); #ifdef __ANDROID__ _loKitDocumentForAndroidOnly.reset(); #endif _loKitDocument.reset(); LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" << sessionId << "] unloaded Document."); return; } else { _loKitDocument->destroyView(viewId); } // Since callback messages are processed on idle-timer, // we could receive callbacks after destroying a view. // Retain the CallbackDescriptor object, which is shared with Core. // Do not: _viewIdToCallbackDescr.erase(viewId); viewCount = _loKitDocument->getViewsCount(); LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" << sessionId << "] unloaded view [" << viewId << "]. Have " << viewCount << " view" << (viewCount != 1 ? "s." : ".")); if (viewCount > 0) { // Broadcast updated view info notifyViewInfo(); } } std::map<int, UserInfo> getViewInfo() override { return _sessionUserInfo; } std::shared_ptr<TileQueue>& getTileQueue() override { return _tileQueue; } int getEditorId() const override { return _editorId; } /// Notify all views with the given message bool notifyAll(const std::string& msg) override { // Broadcast updated viewinfo to all clients. return sendTextFrame("client-all " + msg); } /// Notify all views of viewId and their associated usernames void notifyViewInfo() override { // Get the list of view ids from the core const int viewCount = getLOKitDocument()->getViewsCount(); std::vector<int> viewIds(viewCount); getLOKitDocument()->getViewIds(viewIds.data(), viewCount); const std::map<int, UserInfo> viewInfoMap = getViewInfo(); const std::map<std::string, int> viewColorsMap = getViewColors(); // Double check if list of viewids from core and our list matches, // and create an array of JSON objects containing id and username std::ostringstream oss; oss << "viewinfo: ["; for (const auto& viewId : viewIds) { oss << "{\"id\":" << viewId << ','; int color = 0; const auto itView = viewInfoMap.find(viewId); if (itView == viewInfoMap.end()) { LOG_ERR("No username found for viewId [" << viewId << "]."); oss << "\"username\":\"Unknown\","; } else { oss << "\"userid\":\"" << JsonUtil::escapeJSONValue(itView->second.getUserId()) << "\","; const std::string username = itView->second.getUserName(); oss << "\"username\":\"" << JsonUtil::escapeJSONValue(username) << "\","; if (!itView->second.getUserExtraInfo().empty()) oss << "\"userextrainfo\":" << itView->second.getUserExtraInfo() << ','; const bool readonly = itView->second.isReadOnly(); oss << "\"readonly\":\"" << readonly << "\","; const auto it = viewColorsMap.find(username); if (it != viewColorsMap.end()) { color = it->second; } } oss << "\"color\":" << color << "},"; } if (viewCount > 0) oss.seekp(-1, std::ios_base::cur); // Remove last comma. oss << ']'; // Broadcast updated viewinfo to all clients. notifyAll(oss.str()); } void updateEditorSpeeds(int id, int speed) override { int maxSpeed = -1, fastestUser = -1; auto now = std::chrono::steady_clock::now(); _lastUpdatedAt[id] = now; _speedCount[id] = speed; for (const auto& it : _sessions) { const std::shared_ptr<ChildSession> session = it.second; int sessionId = session->getViewId(); auto duration = (_lastUpdatedAt[id] - now); std::chrono::milliseconds::rep durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); if (_speedCount[sessionId] != 0 && durationInMs > 5000) { _speedCount[sessionId] = session->getSpeed(); _lastUpdatedAt[sessionId] = now; } if (_speedCount[sessionId] > maxSpeed) { maxSpeed = _speedCount[sessionId]; fastestUser = sessionId; } } // 0 for preventing selection of the first always // 1 for preventing new users from directly becoming editors if (_editorId != fastestUser && (maxSpeed != 0 && maxSpeed != 1)) { if (!_editorChangeWarning && _editorId != -1) { _editorChangeWarning = true; } else { _editorChangeWarning = false; _editorId = fastestUser; for (const auto& it : _sessions) it.second->sendTextFrame("editor: " + std::to_string(_editorId)); } } else _editorChangeWarning = false; } private: // Get the color value for all author names from the core std::map<std::string, int> getViewColors() { char* values = _loKitDocument->getCommandValues(".uno:TrackedChangeAuthors"); const std::string colorValues = std::string(values == nullptr ? "" : values); std::free(values); std::map<std::string, int> viewColors; try { if (!colorValues.empty()) { Poco::JSON::Parser parser; Poco::JSON::Object::Ptr root = parser.parse(colorValues).extract<Poco::JSON::Object::Ptr>(); if (root->get("authors").type() == typeid(Poco::JSON::Array::Ptr)) { Poco::JSON::Array::Ptr authorsArray = root->get("authors").extract<Poco::JSON::Array::Ptr>(); for (auto& authorVar: *authorsArray) { Poco::JSON::Object::Ptr authorObj = authorVar.extract<Poco::JSON::Object::Ptr>(); std::string authorName = authorObj->get("name").convert<std::string>(); int colorValue = authorObj->get("color").convert<int>(); viewColors[authorName] = colorValue; } } } } catch(const Exception& exc) { LOG_ERR("Poco Exception: " << exc.displayText() << (exc.nested() ? " (" + exc.nested()->displayText() + ')' : "")); } return viewColors; } std::shared_ptr<lok::Document> load(const std::shared_ptr<ChildSession>& session, const std::string& renderOpts) { const std::string sessionId = session->getId(); const std::string& uri = session->getJailedFilePath(); const std::string& uriAnonym = session->getJailedFilePathAnonym(); const std::string& userName = session->getUserName(); const std::string& userNameAnonym = session->getUserNameAnonym(); const std::string& docPassword = session->getDocPassword(); const bool haveDocPassword = session->getHaveDocPassword(); const std::string& lang = session->getLang(); const std::string& deviceFormFactor = session->getDeviceFormFactor(); const std::string& batchMode = session->getBatchMode(); const std::string& enableMacrosExecution = session->getEnableMacrosExecution(); const std::string& macroSecurityLevel = session->getMacroSecurityLevel(); std::string spellOnline; std::string options; if (!lang.empty()) options = "Language=" + lang; if (!deviceFormFactor.empty()) options += ",DeviceFormFactor=" + deviceFormFactor; if (!batchMode.empty()) options += ",Batch=" + batchMode; if (!enableMacrosExecution.empty()) options += ",EnableMacrosExecution=" + enableMacrosExecution; if (!macroSecurityLevel.empty()) options += ",MacroSecurityLevel=" + macroSecurityLevel; if (!_loKitDocument) { // This is the first time we are loading the document LOG_INF("Loading new document from URI: [" << uriAnonym << "] for session [" << sessionId << "]."); _loKit->registerCallback(GlobalCallback, this); const int flags = LOK_FEATURE_DOCUMENT_PASSWORD | LOK_FEATURE_DOCUMENT_PASSWORD_TO_MODIFY | LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK | LOK_FEATURE_NO_TILED_ANNOTATIONS | LOK_FEATURE_RANGE_HEADERS | LOK_FEATURE_VIEWID_IN_VISCURSOR_INVALIDATION_CALLBACK; _loKit->setOptionalFeatures(flags); // Save the provided password with us and the jailed url _haveDocPassword = haveDocPassword; _docPassword = docPassword; _jailedUrl = uri; _isDocPasswordProtected = false; const char *pURL = uri.c_str(); LOG_DBG("Calling lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ", \"" << options << "\")."); const auto start = std::chrono::steady_clock::now(); _loKitDocument.reset(_loKit->documentLoad(pURL, options.c_str())); #ifdef __ANDROID__ _loKitDocumentForAndroidOnly = _loKitDocument; #endif const auto duration = std::chrono::steady_clock::now() - start; const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(duration); LOG_DBG("Returned lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ") in " << elapsed); #ifdef IOS DocumentData::get(_mobileAppDocId).loKitDocument = _loKitDocument.get(); #endif if (!_loKitDocument || !_loKitDocument->get()) { LOG_ERR("Failed to load: " << uriAnonym << ", error: " << _loKit->getError()); // Checking if wrong password or no password was reason for failure. if (_isDocPasswordProtected) { LOG_INF("Document [" << uriAnonym << "] is password protected."); if (!_haveDocPassword) { LOG_INF("No password provided for password-protected document [" << uriAnonym << "]."); std::string passwordFrame = "passwordrequired:"; if (_docPasswordType == PasswordType::ToView) passwordFrame += "to-view"; else if (_docPasswordType == PasswordType::ToModify) passwordFrame += "to-modify"; session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame); } else { LOG_INF("Wrong password for password-protected document [" << uriAnonym << "]."); session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword"); } return nullptr; } session->sendTextFrameAndLogError("error: cmd=load kind=faileddocloading"); return nullptr; } // Only save the options on opening the document. // No support for changing them after opening a document. _renderOpts = renderOpts; spellOnline = session->getSpellOnline(); } else { LOG_INF("Document with url [" << uriAnonym << "] already loaded. Need to create new view for session [" << sessionId << "]."); // Check if this document requires password if (_isDocPasswordProtected) { if (!haveDocPassword) { std::string passwordFrame = "passwordrequired:"; if (_docPasswordType == PasswordType::ToView) passwordFrame += "to-view"; else if (_docPasswordType == PasswordType::ToModify) passwordFrame += "to-modify"; session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame); return nullptr; } else if (docPassword != _docPassword) { session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword"); return nullptr; } } LOG_INF("Creating view to url [" << uriAnonym << "] for session [" << sessionId << "] with " << options << '.'); _loKitDocument->createView(options.c_str()); LOG_TRC("View to url [" << uriAnonym << "] created."); } LOG_INF("Initializing for rendering session [" << sessionId << "] on document url [" << anonymizeUrl(_url) << "] with: [" << makeRenderParams(_renderOpts, userNameAnonym, spellOnline) << "]."); // initializeForRendering() should be called before // registerCallback(), as the previous creates a new view in Impress. const std::string renderParams = makeRenderParams(_renderOpts, userName, spellOnline); _loKitDocument->initializeForRendering(renderParams.c_str()); const int viewId = _loKitDocument->getView(); session->setViewId(viewId); _sessionUserInfo[viewId] = UserInfo(session->getViewUserId(), session->getViewUserName(), session->getViewUserExtraInfo(), session->isReadOnly()); _loKitDocument->setViewLanguage(viewId, lang.c_str()); // viewId's monotonically increase, and CallbackDescriptors are never freed. _viewIdToCallbackDescr.emplace(viewId, std::unique_ptr<CallbackDescriptor>(new CallbackDescriptor({ this, viewId }))); _loKitDocument->registerCallback(ViewCallback, _viewIdToCallbackDescr[viewId].get()); const int viewCount = _loKitDocument->getViewsCount(); LOG_INF("Document url [" << anonymizeUrl(_url) << "] for session [" << sessionId << "] loaded view [" << viewId << "]. Have " << viewCount << " view" << (viewCount != 1 ? "s." : ".")); session->initWatermark(); return _loKitDocument; } bool forwardToChild(const std::string& prefix, const std::vector<char>& payload) { assert(payload.size() > prefix.size()); // Remove the prefix and trim. std::size_t index = prefix.size(); for ( ; index < payload.size(); ++index) { if (payload[index] != ' ') { break; } } const char* data = payload.data() + index; std::size_t size = payload.size() - index; std::string name; std::string sessionId; if (COOLProtocol::parseNameValuePair(prefix, name, sessionId, '-') && name == "child") { const auto it = _sessions.find(sessionId); if (it != _sessions.end()) { std::shared_ptr<ChildSession> session = it->second; static const std::string disconnect("disconnect"); if (size == disconnect.size() && strncmp(data, disconnect.data(), disconnect.size()) == 0) { if(session->getViewId() == _editorId) { _editorId = -1; } LOG_DBG("Removing ChildSession [" << sessionId << "]."); // Tell them we're going quietly. session->sendTextFrame("disconnected:"); _sessions.erase(it); const std::size_t count = _sessions.size(); LOG_DBG("Have " << count << " child" << (count == 1 ? "" : "ren") << " after removing ChildSession [" << sessionId << "]."); // No longer needed, and allow session dtor to take it. session.reset(); return true; } // No longer needed, and allow the handler to take it. if (session) { std::vector<char> vect(size); vect.assign(data, data + size); // TODO this is probably wrong... session->handleMessage(vect); return true; } } const std::string abbrMessage = getAbbreviatedMessage(data, size); LOG_ERR("Child session [" << sessionId << "] not found to forward message: " << abbrMessage); } else { LOG_ERR("Failed to parse prefix of forward-to-child message: " << prefix); } return false; } template <typename T> static Object::Ptr makePropertyValue(const std::string& type, const T& val) { Object::Ptr obj = new Object(); obj->set("type", type); obj->set("value", val); return obj; } static std::string makeRenderParams(const std::string& renderOpts, const std::string& userName, const std::string& spellOnline) { Object::Ptr renderOptsObj; // Fill the object with renderoptions, if any if (!renderOpts.empty()) { Parser parser; Poco::Dynamic::Var var = parser.parse(renderOpts); renderOptsObj = var.extract<Object::Ptr>(); } else { renderOptsObj = new Object(); } // Append name of the user, if any, who opened the document to rendering options if (!userName.empty()) { // userName must be decoded already. renderOptsObj->set(".uno:Author", makePropertyValue("string", userName)); } // By default we enable spell-checking, unless it's disabled explicitly. const bool bSet = (spellOnline != "false"); renderOptsObj->set(".uno:SpellOnline", makePropertyValue("boolean", bSet)); if (renderOptsObj) { std::ostringstream ossRenderOpts; renderOptsObj->stringify(ossRenderOpts); return ossRenderOpts.str(); } return std::string(); } public: void enableProcessInput(bool enable = true){ _inputProcessingEnabled = enable; } bool processInputEnabled() const { return _inputProcessingEnabled; } bool hasQueueItems() const { return _tileQueue && !_tileQueue->isEmpty(); } // poll is idle, are we ? void checkIdle() { if (!processInputEnabled() || hasQueueItems()) { LOG_TRC("Nearly idle - but have more queued items to process"); return; // more to do } sendTextFrame("idle"); // get rid of idle check for now. ProcessToIdleDeadline = std::chrono::steady_clock::now() - std::chrono::milliseconds(10); } void drainQueue() { try { while (processInputEnabled() && hasQueueItems()) { if (_stop || SigUtil::getTerminationFlag()) { LOG_INF("_stop or TerminationFlag is set, breaking Document::drainQueue of loop"); break; } const TileQueue::Payload input = _tileQueue->pop(); LOG_TRC("Kit handling queue message: " << COOLProtocol::getAbbreviatedMessage(input)); const StringVector tokens = Util::tokenize(input.data(), input.size()); if (tokens.equals(0, "eof")) { LOG_INF("Received EOF. Finishing."); break; } if (tokens.equals(0, "tile")) { renderTile(tokens); } else if (tokens.equals(0, "tilecombine")) { renderCombinedTiles(tokens); } else if (tokens.startsWith(0, "child-")) { forwardToChild(tokens[0], input); } else if (tokens.equals(0, "processtoidle")) { ProcessToIdleDeadline = std::chrono::steady_clock::now(); uint32_t timeoutUs = 0; if (tokens.getUInt32(1, "timeout", timeoutUs)) ProcessToIdleDeadline += std::chrono::microseconds(timeoutUs); } else if (tokens.equals(0, "callback")) { if (tokens.size() >= 3) { bool broadcast = false; int viewId = -1; int exceptViewId = -1; const std::string& target = tokens[1]; if (target == "all") { broadcast = true; } else if (COOLProtocol::matchPrefix("except-", target)) { exceptViewId = std::stoi(target.substr(7)); broadcast = true; } else { viewId = std::stoi(target); } const int type = std::stoi(tokens[2]); // payload is the rest of the message const std::size_t offset = tokens[0].length() + tokens[1].length() + tokens[2].length() + 3; // + delims const std::string payload(input.data() + offset, input.size() - offset); // Forward the callback to the same view, demultiplexing is done by the LibreOffice core. bool isFound = false; for (const auto& it : _sessions) { if (!it.second) continue; ChildSession& session = *it.second; if ((broadcast && (session.getViewId() != exceptViewId)) || (!broadcast && (session.getViewId() == viewId))) { if (!session.isCloseFrame()) { isFound = true; session.loKitCallback(type, payload); } else { LOG_ERR("Session-thread of session [" << session.getId() << "] for view [" << viewId << "] is not running. Dropping [" << lokCallbackTypeToString(type) << "] payload [" << payload << ']'); } if (!broadcast) { break; } } } if (!isFound) { LOG_ERR("Document::ViewCallback. Session [" << viewId << "] is no longer active to process [" << lokCallbackTypeToString(type) << "] [" << payload << "] message to Master Session."); } } else { LOG_ERR("Invalid callback message: [" << COOLProtocol::getAbbreviatedMessage(input) << "]."); } } else { LOG_ERR("Unexpected request: [" << COOLProtocol::getAbbreviatedMessage(input) << "]."); } } } catch (const std::exception& exc) { LOG_FTL("drainQueue: Exception: " << exc.what()); #if !MOBILEAPP flushTraceEventRecordings(); Log::shutdown(); std::_Exit(EX_SOFTWARE); #endif } catch (...) { LOG_FTL("drainQueue: Unknown exception"); #if !MOBILEAPP flushTraceEventRecordings(); Log::shutdown(); std::_Exit(EX_SOFTWARE); #endif } } private: /// Return access to the lok::Office instance. std::shared_ptr<lok::Office> getLOKit() override { return _loKit; } /// Return access to the lok::Document instance. std::shared_ptr<lok::Document> getLOKitDocument() override { if (!_loKitDocument) { LOG_ERR("Document [" << _docKey << "] is not loaded."); throw std::runtime_error("Document " + _docKey + " is not loaded."); } return _loKitDocument; } std::string getObfuscatedFileId() override { return _obfuscatedFileId; } void alertAllUsers(const std::string& msg) { sendTextFrame(msg); } public: void dumpState(std::ostream& oss) { oss << "Kit Document:\n" << "\n\tstop: " << _stop << "\n\tjailId: " << _jailId << "\n\tdocKey: " << _docKey << "\n\tdocId: " << _docId << "\n\turl: " << _url << "\n\tobfuscatedFileId: " << _obfuscatedFileId << "\n\tjailedUrl: " << _jailedUrl << "\n\trenderOpts: " << _renderOpts << "\n\thaveDocPassword: " << _haveDocPassword // not the pwd itself << "\n\tisDocPasswordProtected: " << _isDocPasswordProtected << "\n\tdocPasswordType: " << (int)_docPasswordType << "\n\teditorId: " << _editorId << "\n\teditorChangeWarning: " << _editorChangeWarning << "\n\tmobileAppDocId: " << _mobileAppDocId << "\n\tinputProcessingEnabled: " << _inputProcessingEnabled << "\n"; // dumpState: // TODO: _websocketHandler - but this is an odd one. _tileQueue->dumpState(oss); _pngCache.dumpState(oss); oss << "\tviewIdToCallbackDescr:"; for (const auto &it : _viewIdToCallbackDescr) { oss << "\n\t\tviewId: " << it.first << " editorId: " << it.second->getDoc()->getEditorId() << " mobileAppDocId: " << it.second->getDoc()->getMobileAppDocId(); } oss << "\n"; _pngPool.dumpState(oss); _sessions.dumpState(oss); oss << "\tlastUpdatedAt:"; for (const auto &it : _lastUpdatedAt) { auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( it.second.time_since_epoch()).count(); oss << "\n\t\tviewId: " << it.first << " last update time(ms): " << ms; } oss << "\n"; oss << "\tspeedCount:"; for (const auto &it : _speedCount) { oss << "\n\t\tviewId: " << it.first << " speed: " << it.second; } oss << "\n"; /// For showing disconnected user info in the doc repair dialog. oss << "\tsessionUserInfo:"; for (const auto &it : _sessionUserInfo) { oss << "\n\t\tviewId: " << it.first << " userId: " << it.second.getUserId() << " userName: " << it.second.getUserName() << " userExtraInfo: " << it.second.getUserExtraInfo() << " readOnly: " << it.second.isReadOnly(); } oss << "\n"; } private: std::shared_ptr<lok::Office> _loKit; const std::string _jailId; /// URL-based key. May be repeated during the lifetime of WSD. const std::string _docKey; /// Short numerical ID. Unique during the lifetime of WSD. const std::string _docId; const std::string _url; const std::string _obfuscatedFileId; std::string _jailedUrl; std::string _renderOpts; std::shared_ptr<lok::Document> _loKitDocument; #ifdef __ANDROID__ static std::shared_ptr<lok::Document> _loKitDocumentForAndroidOnly; #endif std::shared_ptr<TileQueue> _tileQueue; std::shared_ptr<WebSocketHandler> _websocketHandler; PngCache _pngCache; // Document password provided std::string _docPassword; // Whether password was provided or not bool _haveDocPassword; // Whether document is password protected bool _isDocPasswordProtected; // Whether password is required to view the document, or modify it PasswordType _docPasswordType; std::atomic<bool> _stop; ThreadPool _pngPool; std::condition_variable _cvLoading; int _editorId; bool _editorChangeWarning; std::map<int, std::unique_ptr<CallbackDescriptor>> _viewIdToCallbackDescr; SessionMap<ChildSession> _sessions; std::map<int, std::chrono::steady_clock::time_point> _lastUpdatedAt; std::map<int, int> _speedCount; /// For showing disconnected user info in the doc repair dialog. std::map<int, UserInfo> _sessionUserInfo; #ifdef __ANDROID__ friend std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly(); #endif const unsigned _mobileAppDocId; bool _inputProcessingEnabled; }; #if !defined FUZZER && !defined BUILDING_TESTS && !MOBILEAPP // When building the fuzzer we link COOLWSD.cpp into the same executable so the // Protected::emitOneRecording() there gets used. When building the unit tests the one in // TraceEvent.cpp gets used. static constexpr int traceEventRecordingsCapacity = 100; static std::vector<std::string> traceEventRecordings; static void flushTraceEventRecordings() { if (traceEventRecordings.size() == 0) return; std::size_t totalLength = 0; for (const auto& i: traceEventRecordings) totalLength += i.length(); std::string recordings; recordings.reserve(totalLength); for (const auto& i: traceEventRecordings) recordings += i; singletonDocument->sendTextFrame("traceevent: \n" + recordings); traceEventRecordings.clear(); } // The checks for singletonDocument below are to catch if this gets called in the ForKit process. void TraceEvent::emitOneRecordingIfEnabled(const std::string &recording) { // This can be called before the config system is initialized. Guard against that, as calling // config::getBool() would cause an assertion failure. static bool configChecked = false; static bool traceEventsEnabled; if (!configChecked && config::isInitialized()) { traceEventsEnabled = config::getBool("trace_event[@enable]", false); configChecked = true; } if (configChecked && !traceEventsEnabled) return; if (singletonDocument == nullptr) return; singletonDocument->sendTextFrame("forcedtraceevent: \n" + recording); } void TraceEvent::emitOneRecording(const std::string &recording) { static const bool traceEventsEnabled = config::getBool("trace_event[@enable]", false); if (!traceEventsEnabled) return; if (!TraceEvent::isRecordingOn()) return; if (singletonDocument == nullptr) return; if (traceEventRecordings.size() >= traceEventRecordingsCapacity) flushTraceEventRecordings(); else if (traceEventRecordings.size() == 0 && traceEventRecordings.capacity() < traceEventRecordingsCapacity) traceEventRecordings.reserve(traceEventRecordingsCapacity); traceEventRecordings.emplace_back(recording + "\n"); } #elif !MOBILEAPP static void flushTraceEventRecordings() { } #endif #ifdef __ANDROID__ std::shared_ptr<lok::Document> Document::_loKitDocumentForAndroidOnly = std::shared_ptr<lok::Document>(); std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly() { return Document::_loKitDocumentForAndroidOnly; } #endif class KitSocketPoll final : public SocketPoll { std::chrono::steady_clock::time_point _pollEnd; std::shared_ptr<Document> _document; static KitSocketPoll *mainPoll; KitSocketPoll() : SocketPoll("kit") { #ifdef IOS terminationFlag = false; #endif mainPoll = this; } public: ~KitSocketPoll() { // Just to make it easier to set a breakpoint mainPoll = nullptr; } static void dumpGlobalState(std::ostream &oss) { if (mainPoll) { if (!mainPoll->_document) oss << "KitSocketPoll: no doc\n"; else { mainPoll->_document->dumpState(oss); mainPoll->dumpState(oss); } } else oss << "KitSocketPoll: none\n"; } static std::shared_ptr<KitSocketPoll> create() { KitSocketPoll *p = new KitSocketPoll(); auto result = std::shared_ptr<KitSocketPoll>(p); #ifdef IOS std::unique_lock<std::mutex> lock(KSPollsMutex); KSPolls.push_back(result); #endif return result; } // process pending message-queue events. void drainQueue() { SigUtil::checkDumpGlobalState(dump_kit_state); if (_document) _document->drainQueue(); } // called from inside poll, inside a wakeup void wakeupHook() { _pollEnd = std::chrono::steady_clock::now(); } // a LOK compatible poll function merging the functions. // returns the number of events signalled int kitPoll(int timeoutMicroS) { ProfileZone profileZone("KitSocketPoll::kitPoll"); if (SigUtil::getTerminationFlag()) { LOG_TRC("Termination of unipoll mainloop flagged"); return -1; } // The maximum number of extra events to process beyond the first. int maxExtraEvents = 15; int eventsSignalled = 0; auto startTime = std::chrono::steady_clock::now(); // handle processtoidle waiting optimization bool checkForIdle = ProcessToIdleDeadline >= startTime; if (timeoutMicroS < 0) { // Flush at most 1 + maxExtraEvents, or return when nothing left. while (poll(std::chrono::microseconds::zero()) > 0 && maxExtraEvents-- > 0) ++eventsSignalled; } else { if (checkForIdle) timeoutMicroS = 0; // Flush at most maxEvents+1, or return when nothing left. _pollEnd = startTime + std::chrono::microseconds(timeoutMicroS); do { int realTimeout = timeoutMicroS; if (_document && _document->hasQueueItems()) realTimeout = 0; if (poll(std::chrono::microseconds(realTimeout)) <= 0) break; const auto now = std::chrono::steady_clock::now(); drainQueue(); timeoutMicroS = std::chrono::duration_cast<std::chrono::microseconds>(_pollEnd - now).count(); ++eventsSignalled; } while (timeoutMicroS > 0 && !SigUtil::getTerminationFlag() && maxExtraEvents-- > 0); } if (_document && checkForIdle && eventsSignalled == 0 && timeoutMicroS > 0 && !hasCallbacks() && !hasBuffered()) { auto remainingTime = ProcessToIdleDeadline - startTime; LOG_TRC("Poll of " << timeoutMicroS << " vs. remaining time of: " << std::chrono::duration_cast<std::chrono::microseconds>(remainingTime).count()); // would we poll until then if we could ? if (remainingTime < std::chrono::microseconds(timeoutMicroS)) _document->checkIdle(); else LOG_TRC("Poll of woudl not close gap - continuing"); } drainQueue(); #if !MOBILEAPP if (_document && _document->purgeSessions() == 0) { LOG_INF("Last session discarded. Setting TerminationFlag"); SigUtil::setTerminationFlag(); return -1; } #endif // Report the number of events we processed. return eventsSignalled; } void setDocument(std::shared_ptr<Document> document) { _document = std::move(document); } // unusual LOK event from another thread, push into our loop to process. static bool pushToMainThread(LibreOfficeKitCallback callback, int type, const char *p, void *data) { if (mainPoll && mainPoll->getThreadOwner() != std::this_thread::get_id()) { LOG_TRC("Unusual push callback to main thread"); std::shared_ptr<std::string> pCopy; if (p) pCopy = std::make_shared<std::string>(p, strlen(p)); mainPoll->addCallback([=]{ LOG_TRC("Unusual process callback in main thread"); callback(type, pCopy ? pCopy->c_str() : nullptr, data); }); return true; } return false; } #ifdef IOS static std::mutex KSPollsMutex; // static std::condition_variable KSPollsCV; static std::vector<std::weak_ptr<KitSocketPoll>> KSPolls; std::mutex terminationMutex; std::condition_variable terminationCV; bool terminationFlag; #endif }; KitSocketPoll *KitSocketPoll::mainPoll = nullptr; bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data) { return KitSocketPoll::pushToMainThread(cb, type, p, data); } #ifdef IOS std::mutex KitSocketPoll::KSPollsMutex; // std::condition_variable KitSocketPoll::KSPollsCV; std::vector<std::weak_ptr<KitSocketPoll>> KitSocketPoll::KSPolls; #endif class KitWebSocketHandler final : public WebSocketHandler { std::shared_ptr<TileQueue> _queue; std::string _socketName; std::shared_ptr<lok::Office> _loKit; std::string _jailId; std::shared_ptr<Document> _document; std::shared_ptr<KitSocketPoll> _ksPoll; const unsigned _mobileAppDocId; public: KitWebSocketHandler(const std::string& socketName, const std::shared_ptr<lok::Office>& loKit, const std::string& jailId, std::shared_ptr<KitSocketPoll> ksPoll, unsigned mobileAppDocId) : WebSocketHandler(/* isClient = */ true, /* isMasking */ false), _queue(std::make_shared<TileQueue>()), _socketName(socketName), _loKit(loKit), _jailId(jailId), _ksPoll(ksPoll), _mobileAppDocId(mobileAppDocId) { } ~KitWebSocketHandler() { // Just to make it easier to set a breakpoint } protected: void handleMessage(const std::vector<char>& data) override { // To get A LOT of Trace Events, to exercide their handling, uncomment this: // ProfileZone profileZone("KitWebSocketHandler::handleMessage"); std::string message(data.data(), data.size()); #if !MOBILEAPP if (UnitKit::get().filterKitMessage(this, message)) return; #endif StringVector tokens = Util::tokenize(message); Log::StreamLogger logger = Log::debug(); if (logger.enabled()) { logger << _socketName << ": recv ["; for (const auto& token : tokens) { // Don't log user-data, there are anonymized versions that get logged instead. if (tokens.startsWith(token, "jail") || tokens.startsWith(token, "author") || tokens.startsWith(token, "name") || tokens.startsWith(token, "url")) continue; logger << tokens.getParam(token) << ' '; } LOG_END(logger, true); } // Note: Syntax or parsing errors here are unexpected and fatal. if (SigUtil::getTerminationFlag()) { LOG_DBG("Too late, TerminationFlag is set, we're going down"); } else if (tokens.equals(0, "session")) { const std::string& sessionId = tokens[1]; const std::string& docKey = tokens[2]; const std::string& docId = tokens[3]; const int canonicalViewId = std::stoi(tokens[4]); const std::string fileId = Util::getFilenameFromURL(docKey); Util::mapAnonymized(fileId, fileId); // Identity mapping, since fileId is already obfuscated std::string url; URI::decode(docKey, url); LOG_INF("New session [" << sessionId << "] request on url [" << url << "] with viewId " << canonicalViewId); #ifndef IOS Util::setThreadName("kit" SHARED_DOC_THREADNAME_SUFFIX + docId); #endif if (!_document) { _document = std::make_shared<Document>( _loKit, _jailId, docKey, docId, url, _queue, std::static_pointer_cast<WebSocketHandler>(shared_from_this()), _mobileAppDocId); _ksPoll->setDocument(_document); // We need to send the process name information to WSD if Trace Event recording is enabled (but // not turned on) because it might be turned on later. // We can do this only after creating the Document object. TraceEvent::emitOneRecordingIfEnabled(std::string("{\"name\":\"process_name\",\"ph\":\"M\",\"args\":{\"name\":\"") + "Kit-" + docId + "\"},\"pid\":" + std::to_string(getpid()) + ",\"tid\":" + std::to_string(Util::getThreadId()) + "},\n"); } // Validate and create session. if (!(url == _document->getUrl() && _document->createSession(sessionId, canonicalViewId))) { LOG_DBG("CreateSession failed."); } } else if (tokens.equals(0, "exit")) { #if !MOBILEAPP LOG_INF("Terminating immediately due to parent 'exit' command."); flushTraceEventRecordings(); Log::shutdown(); std::_Exit(EX_SOFTWARE); #else #ifdef IOS LOG_INF("Setting our KitSocketPoll's termination flag due to 'exit' command."); std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex); _ksPoll->terminationFlag = true; _ksPoll->terminationCV.notify_all(); #else LOG_INF("Setting TerminationFlag due to 'exit' command."); SigUtil::setTerminationFlag(); #endif _document.reset(); #endif } else if (tokens.equals(0, "tile") || tokens.equals(0, "tilecombine") || tokens.equals(0, "canceltiles") || tokens.equals(0, "paintwindow") || tokens.equals(0, "resizewindow") || COOLProtocol::getFirstToken(tokens[0], '-') == "child") { if (_document) { _queue->put(message); } else { LOG_WRN("No document while processing " << tokens[0] << " request."); } } else if (tokens.size() == 3 && tokens.equals(0, "setconfig")) { #if !MOBILEAPP // Currently only rlimit entries are supported. if (!Rlimit::handleSetrlimitCommand(tokens)) { LOG_ERR("Unknown setconfig command: " << message); } #endif } else if (tokens.equals(0, "setloglevel")) { Log::logger().setLevel(tokens[1]); } else { LOG_ERR("Bad or unknown token [" << tokens[0] << ']'); } } virtual void enableProcessInput(bool enable = true) override { WebSocketHandler::enableProcessInput(enable); if (_document) _document->enableProcessInput(enable); // Wake up poll to process data from socket input buffer if (enable && _ksPoll) { _ksPoll->wakeup(); } } void onDisconnect() override { #if !MOBILEAPP LOG_ERR("Kit connection lost without exit arriving from wsd. Setting TerminationFlag"); SigUtil::setTerminationFlag(); #endif #ifdef IOS { std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex); _ksPoll->terminationFlag = true; _ksPoll->terminationCV.notify_all(); } #endif _ksPoll.reset(); } }; void documentViewCallback(const int type, const char* payload, void* data) { Document::ViewCallback(type, payload, data); } /// Called by LOK main-loop the central location for data processing. int pollCallback(void* pData, int timeoutUs) { #ifndef IOS if (!pData) return 0; else return reinterpret_cast<KitSocketPoll*>(pData)->kitPoll(timeoutUs); #else std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex); std::vector<std::shared_ptr<KitSocketPoll>> v; for (const auto &i : KitSocketPoll::KSPolls) { auto p = i.lock(); if (p) v.push_back(p); } lock.unlock(); if (v.size() == 0) { std::this_thread::sleep_for(std::chrono::microseconds(timeoutUs)); } else { for (const auto &p : v) p->kitPoll(timeoutUs); } // We never want to exit the main loop return 0; #endif } /// Called by LOK main-loop void wakeCallback(void* pData) { #ifndef IOS if (!pData) return; else return reinterpret_cast<KitSocketPoll*>(pData)->wakeup(); #else std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex); if (KitSocketPoll::KSPolls.size() == 0) return; std::vector<std::shared_ptr<KitSocketPoll>> v; for (const auto &i : KitSocketPoll::KSPolls) { auto p = i.lock(); if (p) v.push_back(p); } lock.unlock(); for (const auto &p : v) p->wakeup(); #endif } #ifndef BUILDING_TESTS void lokit_main( #if !MOBILEAPP const std::string& childRoot, const std::string& jailId, const std::string& sysTemplate, const std::string& loTemplate, const std::string& loSubPath, bool noCapabilities, bool noSeccomp, bool queryVersion, bool displayVersion, #else int docBrokerSocket, const std::string& userInterface, #endif std::size_t numericIdentifier ) { #if !MOBILEAPP #ifndef FUZZER SigUtil::setFatalSignals("kit startup of " COOLWSD_VERSION " " COOLWSD_VERSION_HASH); SigUtil::setTerminationSignals(); #endif Util::setThreadName("kit_spare_" + Util::encodeId(numericIdentifier, 3)); // Reinitialize logging when forked. const bool logToFile = std::getenv("COOL_LOGFILE"); const char* logFilename = std::getenv("COOL_LOGFILENAME"); const char* logLevel = std::getenv("COOL_LOGLEVEL"); const bool logColor = config::getBool("logging.color", true) && isatty(fileno(stderr)); std::map<std::string, std::string> logProperties; if (logToFile && logFilename) { logProperties["path"] = std::string(logFilename); } Util::rng::reseed(); const std::string LogLevel = logLevel ? logLevel : "trace"; const bool bTraceStartup = (std::getenv("COOL_TRACE_STARTUP") != nullptr); Log::initialize("kit", bTraceStartup ? "trace" : logLevel, logColor, logToFile, logProperties); if (bTraceStartup && LogLevel != "trace") { LOG_INF("Setting log-level to [trace] and delaying setting to configured [" << LogLevel << "] until after Kit initialization."); } const char* pAnonymizationSalt = std::getenv("COOL_ANONYMIZATION_SALT"); if (pAnonymizationSalt) { AnonymizationSalt = std::stoull(std::string(pAnonymizationSalt)); AnonymizeUserData = true; } LOG_INF("User-data anonymization is " << (AnonymizeUserData ? "enabled." : "disabled.")); assert(!childRoot.empty()); assert(!sysTemplate.empty()); assert(!loTemplate.empty()); assert(!loSubPath.empty()); LOG_INF("Kit process for Jail [" << jailId << "] started."); std::string userdir_url; std::string instdir_path; int ProcSMapsFile = -1; // lokit's destroy typically throws from // framework/source/services/modulemanager.cxx:198 // So we insure it lives until std::_Exit is called. std::shared_ptr<lok::Office> loKit; ChildSession::NoCapsForKit = noCapabilities; #endif // MOBILEAPP try { #if !MOBILEAPP const Path jailPath = Path::forDirectory(childRoot + '/' + jailId); const std::string jailPathStr = jailPath.toString(); LOG_INF("Jail path: " << jailPathStr); File(jailPath).createDirectories(); chmod(jailPathStr.c_str(), S_IXUSR | S_IWUSR | S_IRUSR); if (!ChildSession::NoCapsForKit) { std::chrono::time_point<std::chrono::steady_clock> jailSetupStartTime = std::chrono::steady_clock::now(); userdir_url = "file:///tmp/user"; instdir_path = '/' + loSubPath + "/program"; Poco::Path jailLOInstallation(jailPath, loSubPath); jailLOInstallation.makeDirectory(); const std::string loJailDestPath = jailLOInstallation.toString(); // The bind-mount implementation: inlined here to mirror // the fallback link/copy version bellow. const auto mountJail = [&]() -> bool { // Mount sysTemplate for the jail directory. LOG_INF("Mounting " << sysTemplate << " -> " << jailPathStr); if (!JailUtil::bind(sysTemplate, jailPathStr) || !JailUtil::remountReadonly(sysTemplate, jailPathStr)) { LOG_ERR("Failed to mount [" << sysTemplate << "] -> [" << jailPathStr << "], will link/copy contents."); return false; } // Mount loTemplate inside it. LOG_INF("Mounting " << loTemplate << " -> " << loJailDestPath); Poco::File(loJailDestPath).createDirectories(); if (!JailUtil::bind(loTemplate, loJailDestPath) || !JailUtil::remountReadonly(loTemplate, loJailDestPath)) { LOG_WRN("Failed to mount [" << loTemplate << "] -> [" << loJailDestPath << "], will link/copy contents."); return false; } // tmpdir inside the jail for added sercurity. const std::string tempRoot = Poco::Path(childRoot, "tmp").toString(); const std::string tmpSubDir = Poco::Path(tempRoot, "cool-" + jailId).toString(); Poco::File(tmpSubDir).createDirectories(); const std::string jailTmpDir = Poco::Path(jailPath, "tmp").toString(); LOG_INF("Mounting random temp dir " << tmpSubDir << " -> " << jailTmpDir); if (!JailUtil::bind(tmpSubDir, jailTmpDir)) { LOG_ERR("Failed to mount [" << tmpSubDir << "] -> [" << jailTmpDir << "], will link/copy contents."); return false; } return true; }; // Copy (link) LO installation and other necessary files into it from the template. bool bindMount = JailUtil::isBindMountingEnabled(); if (bindMount) { if (!mountJail()) { LOG_INF("Cleaning up jail before linking/copying."); JailUtil::removeJail(jailPathStr); bindMount = false; JailUtil::disableBindMounting(); } } if (!bindMount) { LOG_INF("Mounting is disabled, will link/copy " << sysTemplate << " -> " << jailPathStr); const std::string linkablePath = childRoot + "/linkable"; linkOrCopy(sysTemplate, jailPath, linkablePath, LinkOrCopyType::All); linkOrCopy(loTemplate, loJailDestPath, linkablePath, LinkOrCopyType::LO); // Update the dynamic files inside the jail. if (!JailUtil::SysTemplate::updateDynamicFiles(jailPathStr)) { LOG_ERR( "Failed to update the dynamic files in the jail [" << jailPathStr << "]. If the systemplate directory is owned by a superuser or is " "read-only, running the installation scripts with the owner's account " "should update these files. Some functionality may be missing."); } // Create a file to mark this a copied jail. JailUtil::markJailCopied(jailPathStr); } // Setup the devices inside /tmp and set TMPDIR. JailUtil::setupJailDevNodes(Poco::Path(jailPath, "/tmp").toString()); ::setenv("TMPDIR", "/tmp", 1); // HOME must be writable, so create it in /tmp. constexpr const char* HomePathInJail = "/tmp/home"; Poco::File(Poco::Path(jailPath, HomePathInJail)).createDirectories(); ::setenv("HOME", HomePathInJail, 1); const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - jailSetupStartTime); LOG_DBG("Initialized jail files in " << ms); ProcSMapsFile = open("/proc/self/smaps", O_RDONLY); if (ProcSMapsFile < 0) LOG_SYS("Failed to open /proc/self/smaps. Memory stats will be missing."); LOG_INF("chroot(\"" << jailPathStr << "\")"); if (chroot(jailPathStr.c_str()) == -1) { LOG_SFL("chroot(\"" << jailPathStr << "\") failed"); Log::shutdown(); std::_Exit(EX_SOFTWARE); } if (chdir("/") == -1) { LOG_SFL("chdir(\"/\") in jail failed"); Log::shutdown(); std::_Exit(EX_SOFTWARE); } #ifndef __FreeBSD__ dropCapability(CAP_SYS_CHROOT); dropCapability(CAP_MKNOD); dropCapability(CAP_FOWNER); dropCapability(CAP_CHOWN); #else cap_enter(); #endif LOG_DBG("Initialized jail nodes, dropped caps."); } else // noCapabilities set { LOG_WRN("Security warning: running without chroot jails is insecure."); LOG_INF("Using template [" << loTemplate << "] as install subpath directly, without chroot jail setup."); userdir_url = "file:///" + jailPathStr + "/tmp/user"; instdir_path = '/' + loTemplate + "/program"; JailRoot = jailPathStr; } LOG_DBG("Initializing LOK with instdir [" << instdir_path << "] and userdir [" << userdir_url << "]."); LibreOfficeKit *kit; { const char *instdir = instdir_path.c_str(); const char *userdir = userdir_url.c_str(); #ifndef KIT_IN_PROCESS kit = UnitKit::get().lok_init(instdir, userdir); #else kit = nullptr; #ifdef FUZZER if (COOLWSD::DummyLOK) kit = dummy_lok_init_2(instdir, userdir); #endif #endif if (!kit) { kit = (initFunction ? initFunction(instdir, userdir) : lok_init_2(instdir, userdir)); } loKit = std::make_shared<lok::Office>(kit); if (!loKit) { LOG_FTL("LibreOfficeKit initialization failed. Exiting."); Log::shutdown(); std::_Exit(EX_SOFTWARE); } } // Lock down the syscalls that can be used if (!Seccomp::lockdown(Seccomp::Type::KIT)) { if (!noSeccomp) { LOG_FTL("LibreOfficeKit seccomp security lockdown failed. Exiting."); Log::shutdown(); std::_Exit(EX_SOFTWARE); } LOG_ERR("LibreOfficeKit seccomp security lockdown failed, but configured to continue. " "You are running in a significantly less secure mode."); } rlimit rlim = { 0, 0 }; if (getrlimit(RLIMIT_AS, &rlim) == 0) LOG_INF("RLIMIT_AS is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)"); else LOG_SYS("Failed to get RLIMIT_AS"); if (getrlimit(RLIMIT_STACK, &rlim) == 0) LOG_INF("RLIMIT_STACK is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)"); else LOG_SYS("Failed to get RLIMIT_STACK"); if (getrlimit(RLIMIT_FSIZE, &rlim) == 0) LOG_INF("RLIMIT_FSIZE is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)"); else LOG_SYS("Failed to get RLIMIT_FSIZE"); if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) LOG_INF("RLIMIT_NOFILE is " << rlim.rlim_max << " files."); else LOG_SYS("Failed to get RLIMIT_NOFILE"); LOG_INF("Kit process for Jail [" << jailId << "] is ready."); std::string pathAndQuery(NEW_CHILD_URI); pathAndQuery.append("?jailid="); pathAndQuery.append(jailId); if (queryVersion) { char* versionInfo = loKit->getVersionInfo(); std::string versionString(versionInfo); if (displayVersion) std::cout << "office version details: " << versionString << std::endl; SigUtil::setVersionInfo(versionString); // Add some parameters we want to pass to the client. Could not figure out how to get // the configuration parameters from COOLWSD.cpp's initialize() or coolwsd.xml here, so // oh well, just have the value hardcoded in KitHelper.hpp. It isn't really useful to // "tune" it at end-user installations anyway, I think. auto versionJSON = Poco::JSON::Parser().parse(versionString).extract<Poco::JSON::Object::Ptr>(); versionJSON->set("tunnelled_dialog_image_cache_size", std::to_string(LOKitHelper::tunnelledDialogImageCacheSize)); std::stringstream ss; versionJSON->stringify(ss); versionString = ss.str(); std::string encodedVersion; Poco::URI::encode(versionString, "?#/", encodedVersion); pathAndQuery.append("&version="); pathAndQuery.append(encodedVersion); free(versionInfo); } #else // MOBILEAPP #ifndef IOS // Was not done by the preload. // For iOS we call it in -[AppDelegate application: didFinishLaunchingWithOptions:] setupKitEnvironment(userInterface); #endif #if (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__) Poco::URI userInstallationURI("file", LO_PATH); LibreOfficeKit *kit = lok_init_2(LO_PATH "/program", userInstallationURI.toString().c_str()); #else #ifdef IOS // In the iOS app we call lok_init_2() just once, when the app starts static LibreOfficeKit *kit = lo_kit; #else static LibreOfficeKit *kit = lok_init_2(nullptr, nullptr); #endif #endif assert(kit); static std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(kit); assert(loKit); COOLWSD::LOKitVersion = loKit->getVersionInfo(); // Dummies const std::string jailId = "jailid"; #endif // MOBILEAPP auto mainKit = KitSocketPoll::create(); mainKit->runOnClientThread(); // We will do the polling on this thread. std::shared_ptr<KitWebSocketHandler> websocketHandler = std::make_shared<KitWebSocketHandler>("child_ws", loKit, jailId, mainKit, numericIdentifier); #if !MOBILEAPP mainKit->insertNewUnixSocket(MasterLocation, pathAndQuery, websocketHandler, ProcSMapsFile); #else mainKit->insertNewFakeSocket(docBrokerSocket, websocketHandler); #endif LOG_INF("New kit client websocket inserted."); #if !MOBILEAPP if (bTraceStartup && LogLevel != "trace") { LOG_INF("Kit initialization complete: setting log-level to [" << LogLevel << "] as configured."); Log::logger().setLevel(LogLevel); } #endif #ifndef IOS if (!LIBREOFFICEKIT_HAS(kit, runLoop)) { LOG_FTL("Kit is missing Unipoll API"); std::cout << "Fatal: out of date LibreOfficeKit - no Unipoll API\n"; std::_Exit(EX_SOFTWARE); } LOG_INF("Kit unipoll loop run"); loKit->runLoop(pollCallback, wakeCallback, mainKit.get()); LOG_INF("Kit unipoll loop run terminated."); #if MOBILEAPP SocketPoll::wakeupWorld(); #else // Trap the signal handler, if invoked, // to prevent exiting. LOG_INF("Kit process for Jail [" << jailId << "] finished."); Log::shutdown(); // Let forkit handle the jail cleanup. #endif #else // IOS std::unique_lock<std::mutex> lock(mainKit->terminationMutex); mainKit->terminationCV.wait(lock,[&]{ return mainKit->terminationFlag; } ); #endif // !IOS } catch (const Exception& exc) { LOG_ERR("Poco Exception: " << exc.displayText() << (exc.nested() ? " (" + exc.nested()->displayText() + ')' : "")); } catch (const std::exception& exc) { LOG_ERR("Exception: " << exc.what()); } #if !MOBILEAPP LOG_INF("Kit process for Jail [" << jailId << "] finished."); flushTraceEventRecordings(); Log::shutdown(); // Wait for the signal handler, if invoked, to prevent exiting until done. SigUtil::waitSigHandlerTrap(); std::_Exit(EX_OK); #endif } #ifdef IOS // In the iOS app we can have several documents open in the app process at the same time, thus // several lokit_main() functions running at the same time. We want just one LO main loop, though, // so we start it separately in its own thread. void runKitLoopInAThread() { std::thread([&] { Util::setThreadName("lokit_runloop"); std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(lo_kit); int dummy; loKit->runLoop(pollCallback, wakeCallback, &dummy); // Should never return assert(false); NSLog(@"loKit->runLoop() unexpectedly returned"); std::abort(); }).detach(); } #endif // IOS #endif // !BUILDING_TESTS std::string anonymizeUrl(const std::string& url) { #ifndef BUILDING_TESTS return AnonymizeUserData ? Util::anonymizeUrl(url, AnonymizationSalt) : url; #else return url; #endif } #if !MOBILEAPP /// Initializes LibreOfficeKit for cross-fork re-use. bool globalPreinit(const std::string &loTemplate) { #ifdef FUZZER if (COOLWSD::DummyLOK) return true; #endif const std::string libSofficeapp = loTemplate + "/program/" LIB_SOFFICEAPP; const std::string libMerged = loTemplate + "/program/" LIB_MERGED; std::string loadedLibrary; void *handle; if (File(libMerged).exists()) { LOG_TRC("dlopen(" << libMerged << ", RTLD_GLOBAL|RTLD_NOW)"); handle = dlopen(libMerged.c_str(), RTLD_GLOBAL|RTLD_NOW); if (!handle) { LOG_FTL("Failed to load " << libMerged << ": " << dlerror()); return false; } loadedLibrary = libMerged; } else { if (File(libSofficeapp).exists()) { LOG_TRC("dlopen(" << libSofficeapp << ", RTLD_GLOBAL|RTLD_NOW)"); handle = dlopen(libSofficeapp.c_str(), RTLD_GLOBAL|RTLD_NOW); if (!handle) { LOG_FTL("Failed to load " << libSofficeapp << ": " << dlerror()); return false; } loadedLibrary = libSofficeapp; } else { LOG_FTL("Neither " << libSofficeapp << " or " << libMerged << " exist."); return false; } } LokHookPreInit* preInit = reinterpret_cast<LokHookPreInit *>(dlsym(handle, "lok_preinit")); if (!preInit) { LOG_FTL("No lok_preinit symbol in " << loadedLibrary << ": " << dlerror()); return false; } initFunction = reinterpret_cast<LokHookFunction2 *>(dlsym(handle, "libreofficekit_hook_2")); if (!initFunction) { LOG_FTL("No libreofficekit_hook_2 symbol in " << loadedLibrary << ": " << dlerror()); } // Disable problematic components that may be present from a // desktop or developer's install if env. var not set. ::setenv("UNODISABLELIBRARY", "abp avmediagst avmediavlc cmdmail losessioninstall OGLTrans PresenterScreen " "syssh ucpftp1 ucpgio1 ucphier1 ucpimage updatecheckui updatefeed updchk" // Database "dbaxml dbmm dbp dbu deployment firebird_sdbc mork " "mysql mysqlc odbc postgresql-sdbc postgresql-sdbc-impl sdbc2 sdbt" // Java "javaloader javavm jdbc rpt rptui rptxml ", 0 /* no overwrite */); LOG_TRC("Invoking lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\")"); const auto start = std::chrono::steady_clock::now(); if (preInit((loTemplate + "/program").c_str(), "file:///tmp/user") != 0) { LOG_FTL("lok_preinit() in " << loadedLibrary << " failed"); return false; } LOG_TRC("Finished lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\") in " << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start)); return true; } /// Anonymize usernames. std::string anonymizeUsername(const std::string& username) { #ifndef BUILDING_TESTS return AnonymizeUserData ? Util::anonymize(username, AnonymizationSalt) : username; #else return username; #endif } #endif // !MOBILEAPP void dump_kit_state() { std::ostringstream oss; KitSocketPoll::dumpGlobalState(oss); const std::string msg = oss.str(); fprintf(stderr, "%s", msg.c_str()); LOG_TRC(msg); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
35.465657
190
0.547075
CaptainVal