hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cad7f2a0ac111b3395b0f1c260f39d5cb17ae61a
18,486
cpp
C++
istool/source/ISTool.cpp
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
3
2020-04-24T23:21:48.000Z
2020-04-30T10:52:33.000Z
istool/source/ISTool.cpp
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
null
null
null
istool/source/ISTool.cpp
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
1
2021-09-02T03:29:47.000Z
2021-09-02T03:29:47.000Z
// ISTool.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "ISTool.h" #include "MainFrm.h" #include "MyDoc.h" #include "Registry.h" CMyApp theApp; CImageList CMyApp::m_imageList; int CMyApp::m_nExitCode; CUpdate* CUpdate::m_pFirst; CMyApp* AfxGetApp() { return &theApp; } CAppModule _Module; void Run(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow = SW_SHOWDEFAULT) { if(!theApp.InitInstance()) return; CMessageLoop theLoop; _Module.AddMessageLoop(&theLoop); CMainFrame wndMain; CRect rc = CRect(0,0,800,560); bool bCenterIt = false; #if 1 if(true) { // Load window settings CMyApp* app = AfxGetApp(); int s, t, b, r, l; // only restore if there is a previously saved position if ( -1 != (s = app->GetProfileInt(_T("Settings"),_T("FrameStatus"), -1)) && -1 != (t = app->GetProfileInt(_T("Settings"),_T("FrameTop"), -1)) && -1 != (l = app->GetProfileInt(_T("Settings"),_T("FrameLeft"), -1)) && -1 != (b = app->GetProfileInt(_T("Settings"),_T("FrameBottom"), -1)) && -1 != (r = app->GetProfileInt(_T("Settings"),_T("FrameRight"), -1)) ) { // restore the window's status nCmdShow = s; // restore the window's width and height int cx = r - l; int cy = b - t; // the following correction is needed when the taskbar is // at the left or top and it is not "auto-hidden" RECT workArea; SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0); l += workArea.left; t += workArea.top; // make sure the window is not completely out of sight int max_x = GetSystemMetrics(SM_CXSCREEN) - GetSystemMetrics(SM_CXICON); int max_y = GetSystemMetrics(SM_CYSCREEN) - GetSystemMetrics(SM_CYICON); rc.left = min(l, max_x); rc.top = min(t, max_y); rc.right = rc.left + cx; rc.bottom = rc.top + cy; } else bCenterIt = true; } #endif if(wndMain.CreateEx(NULL,rc) == NULL) { ATLTRACE(_L("Main window creation failed!\n")); return; } if(bCenterIt) wndMain.CenterWindow(); wndMain.ShowWindow(nCmdShow); theLoop.Run(); _Module.RemoveMessageLoop(); theApp.ExitInstance(); } int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) { // HRESULT hRes = ::CoInitialize(NULL); HRESULT hRes = ::OleInitialize(NULL); // If you are running on NT 4.0 or higher you can use the following call instead to // make the EXE free threaded. This means that calls come in on a random RPC thread. // HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); ATLASSERT(SUCCEEDED(hRes)); // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used ::DefWindowProc(NULL, 0, 0, 0L); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); // add flags to support other controls hRes = _Module.Init(NULL, hInstance); ATLASSERT(SUCCEEDED(hRes)); Run(lpstrCmdLine, nCmdShow); _Module.Term(); //::CoUninitialize(); ::OleUninitialize(); return CMyApp::m_nExitCode; } ///////////////////////////////////////////////////////////////////////////// // CMyApp construction const LPCTSTR CMyApp::m_pszKeyIS = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Inno Setup 5_is1"; CMyApp::CMyApp() : m_mutex(FALSE,"ISTool") {} ///////////////////////////////////////////////////////////////////////////// // The one and only CMyApp object CMyPrefs CMyApp::m_prefs("Prefs"); CMyPrefs::CMyPrefs(LPCTSTR pszSubKey) : m_strSubKey(pszSubKey) {} bool CMyPrefs::SavePrefs() { CMyApp& app = *AfxGetApp(); app.WriteProfileString(m_strSubKey,"FontName",m_strFontName); app.WriteProfileInt(m_strSubKey,"FontHeight",m_nFontHeight); app.WriteProfileInt(m_strSubKey,"TabStopValue",m_nTabStopValue); app.WriteProfileInt(m_strSubKey,"ShowVerticalTabLines",m_bShowVerticalTabLines ? 1 : 0); app.WriteProfileInt(m_strSubKey,"AutoIndent",m_bAutoIndent ? 1 : 0); app.WriteProfileInt(m_strSubKey,"ShowLineNumbers",m_bShowLineNumbers ? 1 : 0); app.WriteProfileInt(m_strSubKey,"ReplaceCopy",m_bReplaceCopy ? 1 : 0); app.WriteProfileInt(m_strSubKey,"AutoComponentSelect",m_bAutoComponentSelect ? 1 : 0); app.WriteProfileInt(m_strSubKey,"TestCompiledSetup",m_bTestCompiledSetup ? 1 : 0); app.WriteProfileInt(m_strSubKey,"FilesAsList",m_bFilesList ? 1 : 0); app.WriteProfileInt(m_strSubKey,"IconsAsList",m_bIconsList ? 1 : 0); app.WriteProfileInt(m_strSubKey,"RegistryAsList",m_bRegistryList ? 1 : 0); app.WriteProfileInt(m_strSubKey,"IgnoreDefaults",m_bIgnoreDefaults ? 1 : 0); app.WriteProfileInt(m_strSubKey,"OverwriteMessages",m_bOverwriteMessages ? 1 : 0); app.WriteProfileString(m_strSubKey,"InnoFolder",m_strInnoFolder); app.WriteProfileString(m_strSubKey,"ScriptFolder",m_strScriptFolder); app.WriteProfileInt(m_strSubKey,"ToolBar",m_bToolBar ? 1 : 0); app.WriteProfileInt(m_strSubKey,"StatusBar",m_bStatusBar ? 1 : 0); app.WriteProfileInt(m_strSubKey,"SectionPanel",m_bSectionPanel ? 1 : 0); app.WriteProfileInt(m_strSubKey,"OpenLastProject",m_bOpenLastProject ? 1 : 0); app.WriteProfileInt(m_strSubKey,"ShowNewWizard",m_bShowNewWizard ? 1 : 0); app.WriteProfileInt(m_strSubKey,"StartupSection",m_uStartupSection); app.WriteProfileString(m_strSubKey,"LanguageFile",m_strLanguageFile); app.WriteProfileInt(m_strSubKey,"SplitterPos",m_nSplitterPos); app.WriteProfileInt(m_strSubKey,"PreProcess",m_bPreProcess ? 1 : 0); app.WriteProfileInt(m_strSubKey,"NoOutputExeFilename",m_bNoOutputExeFilename ? 1 : 0); app.WriteProfileInt(m_strSubKey,"LanguageDirCount",m_languageDirs.GetCount()); for(UINT i=0;i<m_languageDirs.GetCount();i++) { CString tmp; tmp.Format("LanguageDir%02X",i); app.WriteProfileString(m_strSubKey,tmp,m_languageDirs[i]); } CScintillaPrefs::SavePrefs(app); return true; } bool CMyPrefs::LoadPrefs() { CMyApp& app = *AfxGetApp(); m_strFontName = app.GetProfileString(m_strSubKey,"FontName","Courier New"); m_nFontHeight = app.GetProfileInt(m_strSubKey,"FontHeight",10); m_nTabStopValue = app.GetProfileInt(m_strSubKey,"TabStopValue",4); m_bShowVerticalTabLines = app.GetProfileInt(m_strSubKey,"ShowVerticalTabLines",1)!=0; m_bAutoIndent = app.GetProfileInt(m_strSubKey,"AutoIndent",1)!=0; m_bShowLineNumbers = app.GetProfileInt(m_strSubKey,"ShowLineNumbers",1)!=0; m_bReplaceCopy = app.GetProfileInt(m_strSubKey,"ReplaceCopy",1) ? true : false; m_bAutoComponentSelect = app.GetProfileInt(m_strSubKey,"AutoComponentSelect",0) ? true : false; m_bTestCompiledSetup = app.GetProfileInt(m_strSubKey,"TestCompiledSetup",1) ? true : false; m_bFilesList = app.GetProfileInt(m_strSubKey,"FilesAsList",1) ? true : false; m_bIconsList = app.GetProfileInt(m_strSubKey,"IconsAsList",1) ? true : false; m_bRegistryList = app.GetProfileInt(m_strSubKey,"RegistryAsList",1) ? true : false; m_bIgnoreDefaults = app.GetProfileInt(m_strSubKey,"IgnoreDefaults",0) ? true : false; m_bOverwriteMessages = app.GetProfileInt(m_strSubKey,"OverwriteMessages",0) ? true : false; m_strInnoFolder = app.GetProfileString(m_strSubKey,"InnoFolder"); m_strScriptFolder = app.GetProfileString(m_strSubKey,"ScriptFolder"); m_bToolBar = app.GetProfileInt(m_strSubKey,"ToolBar",1) ? true : false; m_bStatusBar = app.GetProfileInt(m_strSubKey,"StatusBar",1) ? true : false; m_bSectionPanel = app.GetProfileInt(m_strSubKey,"SectionPanel",1) ? true : false; m_bOpenLastProject = app.GetProfileInt(m_strSubKey,"OpenLastProject",0) ? true : false; m_bShowNewWizard = app.GetProfileInt(m_strSubKey,"ShowNewWizard",1) ? true : false; m_uStartupSection = app.GetProfileInt(m_strSubKey,"StartupSection",ID_VIEW_SCRIPT); m_strLanguageFile = app.GetProfileString(m_strSubKey,"LanguageFile"); m_nSplitterPos = app.GetProfileInt(m_strSubKey,"SplitterPos",164); m_bPreProcess = app.GetProfileInt(m_strSubKey,"PreProcess",0) ? true : false; m_bNoOutputExeFilename = app.GetProfileInt(m_strSubKey,"NoOutputExeFilename",1) ? true : false; UINT iCount = app.GetProfileInt(m_strSubKey,"LanguageDirCount",0); while(iCount--) { CString tmp; tmp.Format("LanguageDir%02X",iCount); CString str = app.GetProfileString(m_strSubKey,tmp,""); if(!str.IsEmpty()) m_languageDirs.InsertAt(0,str); } if(m_strInnoFolder.IsEmpty()) { CRegKey rk; LONG lRet = rk.Create(HKEY_LOCAL_MACHINE, CMyApp::m_pszKeyIS); if(lRet!=ERROR_SUCCESS) rk.Create(HKEY_CURRENT_USER, CMyApp::m_pszKeyIS); if(lRet==ERROR_SUCCESS) { ULONG nChars = MAX_PATH; rk.QueryStringValue("Inno Setup: App Path",m_strInnoFolder.GetBuffer(nChars),&nChars); } } if(::GetModuleFileName(_Module.GetModuleInstance(), m_strAppDir.GetBuffer(_MAX_PATH), _MAX_PATH)) { int nPos = m_strAppDir.ReverseFind('\\'); if(nPos>=0) m_strAppDir.ReleaseBuffer(nPos); } if(m_languageDirs.GetCount()==0 && !m_strInnoFolder.IsEmpty()) { m_languageDirs.Add(m_strInnoFolder); m_languageDirs.Add(m_strInnoFolder + _T("\\Languages")); } CScintillaPrefs::LoadPrefs(app); return true; } ///////////////////////////////////////////////////////////////////////////// // CMyApp initialization BOOL CMyApp::InitInstance() { m_prefs.LoadPrefs(); // Locate help files #ifdef NDEBUG SetHtmlHelpFile("ISTool.chm"); m_strCallTipsFile = "calltips.txt"; CString strHelp; if(::GetModuleFileName(_Module.GetModuleInstance(), strHelp.GetBuffer(_MAX_PATH), _MAX_PATH)) { int nPos = strHelp.ReverseFind('\\'); if(nPos<0) nPos = strHelp.ReverseFind('/'); if(nPos>=0) { strHelp.ReleaseBuffer(nPos+1); SetHtmlHelpFile(strHelp + "ISTool.chm"); m_strCallTipsFile = strHelp + "calltips.txt"; m_strProgramPath = strHelp; //CTransDialog::SetIndexFile(strHelp + "ISTool.idx"); } } CTranslate::AddFile(CMyApp::m_prefs.m_strLanguageFile); #else SetHtmlHelpFile("U:\\ISTool\\help\\html\\ISTool.chm"); m_strCallTipsFile = "U:\\istool\\calltips.txt"; //CTransDialog::SetIndexFile("U:\\ISTool\\distribution\\ISTool.idx"); //CTransDialog::SetLanguageFile("F:\\Utvk\\ISTool\\distribution\\German.lng"); CTranslate::AddFile(CMyApp::m_prefs.m_strLanguageFile); #endif m_imageList.Create(16,16,ILC_MASK|ILC_COLOR16,8,1); CBitmap bm; bm.LoadBitmap(IDB_IMAGELIST); m_imageList.Add(bm,RGB(255,0,255)); bm.Detach(); // Make sure our registry key is there CRegistryEx reg; if(!reg.VerifyKey(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool")) reg.CreateKey(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool"); if(!reg.VerifyKey(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool\\command")) reg.CreateKey(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool\\command"); reg.Open(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool"); if(!reg.VerifyValue("")) reg.Write("",_L("Open with &ISTool")); reg.Close(); reg.Open(HKEY_CLASSES_ROOT,"InnoSetupScriptFile\\shell\\OpenWithISTool\\command"); if(!reg.VerifyValue("")) { CString str; str.Format("\"%s\" \"%%1\"",__argv[0]); if(reg.Write("",str)) SHChangeNotify(SHCNE_ASSOCCHANGED, 0, NULL, NULL); } reg.Close(); if(CMyUtils::IsAdminLoggedOn()) { /* ** Check if Inno Setup 2 is installed, and the user ** if he wants to open Inno Setup's web page. */ CRegistryEx reg; if( !reg.Open(HKEY_LOCAL_MACHINE,m_pszKeyIS) && !reg.Open(HKEY_CURRENT_USER,m_pszKeyIS)) { CString txt = _L("NeedIS5","You don't seem to have Inno Setup 5 installed. This is\nrequired to compile the scripts you create with ISTool.\n\nDo you want to go to http://www.innosetup.com/ and download it now?"); if(AtlMessageBox(AfxGetMainHWnd(),(LPCTSTR)txt,IDR_MAINFRAME,MB_YESNO|MB_ICONQUESTION)==IDYES) { CWaitCursor wait; ShellExecute(AfxGetMainHWnd(),"open","http://www.innosetup.com/",NULL,NULL,SW_SHOWDEFAULT); } } } if(FILE* fp = fopen(m_strCallTipsFile,"rb")) { CString strLine; long nSection = -1; while(fgets(strLine.GetBuffer(1000),1000,fp)) { strLine.ReleaseBuffer(); strLine.Trim(); if(strLine.IsEmpty() || strLine[0]==';') continue; if(!strLine.CompareNoCase("[functions]")) nSection = 1; else if(!strLine.CompareNoCase("[constants]")) nSection = 2; else if(!strLine.CompareNoCase("[calltips]")) nSection = 3; else if(nSection>0) { CString strName, strDescription; long pos = strLine.Find('='); if(pos>0) { strName = strLine.Left(pos).Trim(); strDescription = strLine.Mid(pos+1).Trim(); } else strName = strLine; CallTipInfo* p = new CallTipInfo; p->m_strName = strName; p->m_strDescription = strDescription; switch(nSection) { case 1: m_functions.Add(p); break; case 2: m_constants.Add(p); break; case 3: m_calltips.Add(p); break; } } } fclose(fp); } return TRUE; } CSimpleArray<CallTipInfo*> CMyApp::m_functions; CSimpleArray<CallTipInfo*> CMyApp::m_constants; CSimpleArray<CallTipInfo*> CMyApp::m_calltips; void CMyApp::ExitInstance() { for(long i=0;i<m_functions.GetSize();i++) delete m_functions[i]; for(long i=0;i<m_constants.GetSize();i++) delete m_constants[i]; for(long i=0;i<m_calltips.GetSize();i++) delete m_calltips[i]; m_prefs.SavePrefs(); } void CMyApp::OpenHtmlHelp(UINT nCmd,DWORD dwData) { static const struct { UINT m_nID; LPCTSTR m_pszTopic; } m_topics[] = { IDD_CUSTOMIZE, "/customizevisiblecolumns.html", IDD_PREFS_GENERAL, "/generalpreferences.html", IDD_PREFS_EDITOR, "/editorpreferenes.html", IDD_COMMON_LANGUAGES, "/common_languages.html" }; if(nCmd==HH_DISPLAY_TOPIC) { for(int n=0;n<sizeof(m_topics)/sizeof(m_topics[0]);n++) { if(m_topics[n].m_nID == (dwData & 0x7FFF)) { CString strTmp; strTmp.Format("%s::%s",GetHtmlHelpFile(),m_topics[n].m_pszTopic); ::HtmlHelp(AfxGetMainWnd(), strTmp, HH_DISPLAY_TOPIC, NULL); return; } } // No context found, open contents ::HtmlHelp(AfxGetMainWnd(), GetHtmlHelpFile(), HH_DISPLAY_TOC, NULL); return; } else if(nCmd==HH_DISPLAY_SEARCH) { HH_FTS_QUERY q = { sizeof HH_FTS_QUERY }; ::HtmlHelp(AfxGetMainWnd(), AfxGetApp()->GetHtmlHelpFile(), nCmd, (DWORD)&q); } else { ::HtmlHelp(AfxGetMainWnd(), GetHtmlHelpFile(), nCmd, NULL); } } ///////////////////////////////////////////////////////////////////////////// // CMyApp message handlers int myFind(const CString& ref,TCHAR ch,int startPos/*=0*/) { int pos = startPos; int len = ref.GetLength(); int nInConstant = 0; while(pos<len) { if(ref[pos]=='{') { nInConstant++; } else if(ref[pos]=='}') { nInConstant--; } else if(!nInConstant && ref[pos]==ch) { return pos; } pos++; } return -1; } int myReverseFind(const CString& ref,TCHAR ch) { int pos = myFind(ref,ch); if(pos<0) return pos; int result; do { result = pos; pos = myFind(ref,ch,pos+1); } while(pos>=0); return result; } HTREEITEM CMyApp::FindParentItem(CTreeViewCtrl& ctrl,LPCTSTR lpszFolder,bool bSystem/*=false*/) { CString str(lpszFolder); CString sub; HTREEITEM hRoot = TVI_ROOT; do { int pos = myFind(str,'\\'); if(pos>=0) { sub = str.Left(pos); str = str.Mid(pos+1); } else { sub = str; str.Empty(); } if(sub.IsEmpty()) break; HTREEITEM hChild = ctrl.GetChildItem(hRoot); while(hChild) { CString txt; ctrl.GetItemText(hChild,txt); if(!txt.CompareNoCase(sub)) break; //if(txt==sub) break; hChild = ctrl.GetNextSiblingItem(hChild); } if(!hChild) { HTREEITEM hSave = hRoot; if(bSystem) hRoot = ctrl.InsertItem(sub,3,3,hRoot,TVI_SORT); else { if(!CInnoScriptEx::IsFolderConstant(sub)) hRoot = ctrl.InsertItem(sub,8,9,hRoot,TVI_SORT); else hRoot = ctrl.InsertItem(sub,12,13,hRoot,TVI_SORT); } #if 1 // Don't expand everything HTREEITEM hParent = ctrl.GetParentItem(hRoot); if(hParent) { CScriptLine* pParent = (CScriptLine*)ctrl.GetItemData(hParent); if(!pParent || pParent->m_dwUserFlags & 1) ctrl.Expand(hParent,TVE_EXPAND); } #else ctrl.Expand(hSave,TVE_EXPAND); #endif } else hRoot = hChild; } while(!sub.IsEmpty()); return hRoot; } void CMyApp::MyExpand(CTreeViewCtrl& ctrl,HTREEITEM hItem) { #if 1 if(!hItem) return; if(hItem==TVI_ROOT) { ctrl.Expand(hItem,TVE_EXPAND); } else { CScriptLine* pLine = (CScriptLine*)ctrl.GetItemData(hItem); if(!pLine || pLine->m_dwUserFlags & 1) ctrl.Expand(hItem,TVE_EXPAND); } #else ctrl.Expand(hItem,TVE_EXPAND); #endif } DWORD CMyApp::MyExec(LPCTSTR pszFilename,LPCTSTR pszParams,LPCTSTR pszWorkingDir/*=NULL*/, bool bWaitUntilTerminated/*=true*/, bool bRunMinimized/*=false*/, bool bWaitForIdle/*=false*/) { CString strCmdLine; STARTUPINFO si; PROCESS_INFORMATION pi; DWORD dwResult = -1; #if NDEBUG strCmdLine.Format("\"%s\" %s",pszFilename,pszParams ? pszParams : ""); #else strCmdLine.Format("\"%s\" %s /DEBUGWND=%d",pszFilename,pszParams ? pszParams : "",AfxGetMainHWnd()); #endif memset(&si,0,sizeof si); si.cb = sizeof si; if(bRunMinimized) { si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOWMINIMIZED; } if(!CreateProcess(NULL,strCmdLine.GetBuffer(MAX_PATH),NULL,NULL,FALSE,0,NULL,pszWorkingDir,&si,&pi)) { return dwResult; } CloseHandle(pi.hThread); if(bWaitForIdle) WaitForInputIdle(pi.hProcess,INFINITE); if(bWaitUntilTerminated) { #if 1 WaitForSingleObject(pi.hProcess,INFINITE); #else do { Sleep(0); //if Assigned(ProcessMessagesProc) then // ProcessMessagesProc; } while(MsgWaitForMultipleObjects(1, &pi.hProcess, FALSE, INFINITE, QS_ALLINPUT) == WAIT_OBJECT_0+1); #endif GetExitCodeProcess(pi.hProcess,&dwResult); } CloseHandle(pi.hProcess); return dwResult; } bool CMyApp::IsBooleanExp(LPCTSTR pszArg) { CString str; str.Format(" %s ",pszArg); str.MakeLower(); if(str.FindOneOf("()")>=0) return true; if(str.Find(" or ")>=0) return true; if(str.Find(" and ")>=0) return true; return false; } CMainFrame& AfxGetMainWnd() { ATLASSERT(CMainFrame::m_pMainWnd); return *CMainFrame::m_pMainWnd; } HWND AfxGetMainHWnd() { if(CMainFrame::m_pMainWnd) return CMainFrame::m_pMainWnd->m_hWnd; else return ::GetActiveWindow(); } CMyDoc* AfxGetDocument() { return CMainFrame::m_pDoc; } void AfxGetFileTitle(LPCTSTR pszPathName, LPSTR pszBuffer, UINT nLength) { CString str(pszPathName); int nPos1 = str.ReverseFind('\\'); int nPos2 = str.ReverseFind('/'); if(nPos2>nPos1) str = str.Mid(nPos2+1); else str = str.Mid(nPos1+1); nPos1 = str.ReverseFind('.'); if(nPos1>=0) str.ReleaseBuffer(nPos1); _tcscpy(pszBuffer,str); }
31.173693
216
0.701504
YURSHAT
cad83db2b33b563bad85a671daeeb45d56a6a8d3
9,802
cpp
C++
test/parser/parsing_table_test.cpp
TheSYNcoder/JuCC
4765f9dd93349de93c09d53594721af0fea0acc0
[ "Apache-2.0" ]
31
2021-05-03T11:49:32.000Z
2022-03-03T03:07:57.000Z
test/parser/parsing_table_test.cpp
TheSYNcoder/JuCC
4765f9dd93349de93c09d53594721af0fea0acc0
[ "Apache-2.0" ]
45
2021-04-24T13:36:13.000Z
2021-05-27T05:51:42.000Z
test/parser/parsing_table_test.cpp
TheSYNcoder/JuCC
4765f9dd93349de93c09d53594721af0fea0acc0
[ "Apache-2.0" ]
1
2021-04-25T12:35:55.000Z
2021-04-25T12:35:55.000Z
#include "parser/parsing_table.h" #include "grammar/grammar.h" #include "gtest/gtest.h" using jucc::parser::ParsingTable; namespace grammar = jucc::grammar; namespace utils = jucc::utils; TEST(parser, ParsingTable1) { /** * Test: Context Free Grammar * S : a A B b * A : c | EPSILON * B : d | EPSILON * * */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"a", "A", "B", "b"})}); grammar::Production p2; p2.SetParent("A"); p2.SetRules({grammar::Rule({"c"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p3; p3.SetParent("B"); p3.SetRules({grammar::Rule({"d"}), grammar::Rule({grammar::EPSILON})}); grammar::Productions grammar = {p1, p2, p3}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b", "c", "d"}; std::vector<std::string> non_terminals = {"A", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 0); std::pair<int, int> p; p = table.GetEntry("S", "a"); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("A", "b"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("A", "c"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 0); p = table.GetEntry("A", "d"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("B", "b"); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 1); p = table.GetEntry("B", "d"); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 0); } TEST(parser, ParsingTable2) { /** * Test: Context Free Grammar * S : a B | EPSILON * B : b C | EPSILON * C : c S | EPSILON * * */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"a", "B"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p2; p2.SetParent("B"); p2.SetRules({grammar::Rule({"b", "C"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p3; p3.SetParent("C"); p3.SetRules({grammar::Rule({"c", "S"}), grammar::Rule({grammar::EPSILON})}); grammar::Productions grammar = {p1, p2, p3}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b", "c"}; std::vector<std::string> non_terminals = {"C", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 0); std::pair<int, int> p; p = table.GetEntry("S", "a"); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("B", "b"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 0); p = table.GetEntry("C", "c"); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 0); p = table.GetEntry("S", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 1); p = table.GetEntry("B", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("C", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 1); } TEST(parser, ParsingTable3) { /** * Test: Context Free Grammar * S : a B | EPSILON * B : b C | EPSILON * C : c S | EPSILON * * */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"a", "B"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p2; p2.SetParent("B"); p2.SetRules({grammar::Rule({"b", "C"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p3; p3.SetParent("C"); p3.SetRules({grammar::Rule({"c", "S"}), grammar::Rule({grammar::EPSILON})}); grammar::Productions grammar = {p1, p2, p3}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b", "c"}; std::vector<std::string> non_terminals = {"C", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 0); std::pair<int, int> p; p = table.GetEntry("S", "a"); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("B", "b"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 0); p = table.GetEntry("C", "c"); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 0); p = table.GetEntry("S", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 1); p = table.GetEntry("B", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("C", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 1); } TEST(parser, ParsingTable4) { /** * Test: Context Free Grammar * S : A B * A : a | EPSILON * B : b | EPSILON * * */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"A", "B"})}); grammar::Production p2; p2.SetParent("A"); p2.SetRules({grammar::Rule({"a"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p3; p3.SetParent("B"); p3.SetRules({grammar::Rule({"b"}), grammar::Rule({grammar::EPSILON})}); grammar::Productions grammar = {p1, p2, p3}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b"}; std::vector<std::string> non_terminals = {"A", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 0); std::pair<int, int> p; p = table.GetEntry("S", "a"); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("S", "b"); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("A", "a"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 0); p = table.GetEntry("B", "b"); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 0); p = table.GetEntry("S", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 0); ASSERT_EQ(p.second, 0); p = table.GetEntry("A", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("A", "b"); ASSERT_EQ(p.first, 1); ASSERT_EQ(p.second, 1); p = table.GetEntry("B", utils::STRING_ENDMARKER); ASSERT_EQ(p.first, 2); ASSERT_EQ(p.second, 1); } TEST(parser, ParsingTable5) { /** * Test: Context Free Grammar * S : i E t S S' | a * S': e S | EPSILON * E : b * * Not LL1 grammar */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"i", "E", "t", "S", "S'"}), grammar::Rule({"a"})}); grammar::Production p2; p2.SetParent("S'"); p2.SetRules({grammar::Rule({"e", "S"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p3; p3.SetParent("E"); p3.SetRules({grammar::Rule({"b"})}); grammar::Productions grammar = {p1, p2, p3}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b"}; std::vector<std::string> non_terminals = {"A", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 4); } TEST(parser, ParsingTable6) { /** * Test: Context Free Grammar * S : a A a | EPSILON * A : a b S | EPSILON * * Not LL1 grammar */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"a", "A", "a"}), grammar::Rule({grammar::EPSILON})}); grammar::Production p2; p2.SetParent("A"); p2.SetRules({grammar::Rule({"a", "b", "S"}), grammar::Rule({grammar::EPSILON})}); grammar::Productions grammar = {p1, p2}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a", "b"}; std::vector<std::string> non_terminals = {"A", "S", "B"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 2); } TEST(parser, ParsingTable7) { /** * Test: Context Free Grammar * S : A | A * A : a * * Not LL1 grammar */ grammar::Production p1; p1.SetParent("S"); p1.SetRules({grammar::Rule({"A"}), grammar::Rule({"A"})}); grammar::Production p2; p2.SetParent("A"); p2.SetRules({grammar::Rule({"a"})}); grammar::Productions grammar = {p1, p2}; auto nullables = utils::CalcNullables(grammar); auto firsts = utils::CalcFirsts(grammar, nullables); auto follows = utils::CalcFollows(grammar, firsts, nullables, "S"); std::vector<std::string> terminals = {"a"}; std::vector<std::string> non_terminals = {"A", "S"}; ParsingTable table = ParsingTable(terminals, non_terminals); table.SetFirsts(firsts); table.SetFollows(follows); table.SetProductions(grammar); table.BuildTable(); ASSERT_EQ(table.GetErrors().size(), 1); }
27.002755
83
0.635176
TheSYNcoder
cada7ca3d1731cb01842392711de65000fc9c191
1,000
cc
C++
src/swngramppl.cc
aalto-speech/morphological-classes
a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3
[ "BSD-2-Clause" ]
null
null
null
src/swngramppl.cc
aalto-speech/morphological-classes
a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3
[ "BSD-2-Clause" ]
null
null
null
src/swngramppl.cc
aalto-speech/morphological-classes
a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3
[ "BSD-2-Clause" ]
null
null
null
#include "conf.hh" #include "ModelWrappers.hh" using namespace std; int main(int argc, char* argv[]) { conf::Config config; config("usage: swngramppl [OPTION...] ARPAFILE WORD_SEGMENTATIONS INPUT\n") ('f', "prob-file", "arg", "", "Write log likelihoods (ln) to a file") ('h', "help", "", "", "display help"); config.default_parse(argc, argv); if (config.arguments.size()!=3) config.print_help(stderr, 1); string arpa_fname = config.arguments[0]; string word_segs_fname = config.arguments[1]; string infname = config.arguments[2]; try { SubwordNgram lm(arpa_fname, word_segs_fname); string prob_file = config["prob-file"].specified ? config["prob-file"].get_str() : ""; lm.evaluate( infname, config["prob-file"].specified ? &prob_file : nullptr, nullptr); } catch (string e) { cerr << e << endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
30.30303
94
0.592
aalto-speech
cadd3bc78e317fd2615017ad3748a250b31bd26c
118,461
cpp
C++
3rd/snap7-1.4.2/src/core/s7_micro_client.cpp
xeniumlee/edge.skynet
011b227e67663f298d6dd02b82eb41d30c6924f1
[ "MIT" ]
133
2015-02-19T04:49:23.000Z
2022-02-23T22:15:53.000Z
3rd/snap7-1.4.2/src/core/s7_micro_client.cpp
xeniumlee/edge.skynet
011b227e67663f298d6dd02b82eb41d30c6924f1
[ "MIT" ]
76
2015-02-21T09:41:56.000Z
2022-03-03T11:59:15.000Z
3rd/snap7-1.4.2/src/core/s7_micro_client.cpp
xeniumlee/edge.skynet
011b227e67663f298d6dd02b82eb41d30c6924f1
[ "MIT" ]
51
2015-03-02T21:48:09.000Z
2022-03-17T12:10:36.000Z
/*=============================================================================| | PROJECT SNAP7 1.3.0 | |==============================================================================| | Copyright (C) 2013, 2015 Davide Nardella | | All rights reserved. | |==============================================================================| | SNAP7 is free software: you can redistribute it and/or modify | | it under the terms of the Lesser GNU General Public License as published by | | the Free Software Foundation, either version 3 of the License, or | | (at your option) any later version. | | | | It means that you can distribute your commercial software linked with | | SNAP7 without the requirement to distribute the source code of your | | application and without the requirement that your application be itself | | distributed under LGPL. | | | | SNAP7 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 | | Lesser GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License and a | | copy of Lesser GNU General Public License along with Snap7. | | If not, see http://www.gnu.org/licenses/ | |=============================================================================*/ #include "s7_micro_client.h" //--------------------------------------------------------------------------- TSnap7MicroClient::TSnap7MicroClient() { SrcRef =0x0100; // RFC0983 states that SrcRef and DetRef should be 0 // and, in any case, they are ignored. // S7 instead requires a number != 0 // Libnodave uses 0x0100 // S7Manager uses 0x0D00 // TIA Portal V12 uses 0x1D00 // WinCC uses 0x0300 // Seems that every non zero value is good enough... DstRef =0x0000; SrcTSap =0x0100; DstTSap =0x0000; // It's filled by connection functions ConnectionType = CONNTYPE_PG; // Default connection type memset(&Job,0,sizeof(TSnap7Job)); } //--------------------------------------------------------------------------- TSnap7MicroClient::~TSnap7MicroClient() { Destroying = true; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opReadArea() { PReqFunReadParams ReqParams; PResFunReadParams ResParams; PS7ResHeader23 Answer; PResFunReadItem ResData; word RPSize; // ReqParams size int WordSize; uintptr_t Offset; pbyte Target; int Address; int IsoSize; int Start; int MaxElements; // Max elements that we can transfer in a PDU word NumElements; // Num of elements that we are asking for this telegram int TotElements; // Total elements requested int Size; int Result; WordSize=DataSizeByte(Job.WordLen); // The size in bytes of an element that we are asking for if (WordSize==0) return errCliInvalidWordLen; // First check : params bounds if ((Job.Number<0) || (Job.Number>65535) || (Job.Start<0) || (Job.Amount<1)) return errCliInvalidParams; // Second check : transport size if ((Job.WordLen==S7WLBit) && (Job.Amount>1)) return errCliInvalidTransportSize; // Request Params size RPSize =sizeof(TReqFunReadItem)+2; // 1 item + FunRead + ItemsCount // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams =PReqFunReadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams =PResFunReadParams(pbyte(Answer)+ResHeaderSize23); ResData =PResFunReadItem(pbyte(ResParams)+sizeof(TResFunReadParams)); // Each packet cannot exceed the PDU length (in bytes) negotiated, and moreover // we must ensure to transfer a "finite" number of item per PDU MaxElements=(PDULength-sizeof(TS7ResHeader23)-sizeof(TResFunReadParams)-4) / WordSize; TotElements=Job.Amount; Start =Job.Start; Offset =0; Result =0; while ((TotElements>0) && (Result==0)) { NumElements=TotElements; if (NumElements>MaxElements) NumElements=MaxElements; Target=pbyte(Job.pData)+Offset; //----------------------------------------------- Read next slice----- PDUH_out->P = 0x32; // Always 0x32 PDUH_out->PDUType = PduType_request; // 0x01 PDUH_out->AB_EX = 0x0000; // Always 0x0000 PDUH_out->Sequence = GetNextWord(); // AutoInc PDUH_out->ParLen = SwapWord(RPSize); // 14 bytes params PDUH_out->DataLen = 0x0000; // No data ReqParams->FunRead = pduFuncRead; // 0x04 ReqParams->ItemsCount = 1; ReqParams->Items[0].ItemHead[0] = 0x12; ReqParams->Items[0].ItemHead[1] = 0x0A; ReqParams->Items[0].ItemHead[2] = 0x10; ReqParams->Items[0].TransportSize = Job.WordLen; ReqParams->Items[0].Length = SwapWord(NumElements); ReqParams->Items[0].Area = Job.Area; if (Job.Area==S7AreaDB) ReqParams->Items[0].DBNumber = SwapWord(Job.Number); else ReqParams->Items[0].DBNumber = 0x0000; // Adjusts the offset if ((Job.WordLen==S7WLBit) || (Job.WordLen==S7WLCounter) || (Job.WordLen==S7WLTimer)) Address = Start; else Address = Start*8; ReqParams->Items[0].Address[2] = Address & 0x000000FF; Address = Address >> 8; ReqParams->Items[0].Address[1] = Address & 0x000000FF; Address = Address >> 8; ReqParams->Items[0].Address[0] = Address & 0x000000FF; IsoSize = sizeof(TS7ReqHeader)+RPSize; Result = isoExchangeBuffer(0,IsoSize); // Get Data if (Result==0) // 1St level Iso { Size = 0; // Item level error if (ResData->ReturnCode==0xFF) // <-- 0xFF means Result OK { // Calcs data size in bytes Size = SwapWord(ResData->DataLength); // Adjust Size in accord of TransportSize if ((ResData->TransportSize != TS_ResOctet) && (ResData->TransportSize != TS_ResReal) && (ResData->TransportSize != TS_ResBit)) Size = Size >> 3; memcpy(Target, &ResData->Data[0], Size); } else Result = CpuError(ResData->ReturnCode); Offset+=Size; }; //-------------------------------------------------------------------- TotElements -= NumElements; Start += NumElements*WordSize; } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opWriteArea() { PReqFunWriteParams ReqParams; PReqFunWriteDataItem ReqData; // only 1 item for WriteArea Function PResFunWrite ResParams; PS7ResHeader23 Answer; word RPSize; // ReqParams size word RHSize; // Request headers size bool First = true; pbyte Source; pbyte Target; int Address; int IsoSize; int WordSize; word Size; uintptr_t Offset = 0; int Start; // where we are starting from for this telegram int MaxElements; // Max elements that we can transfer in a PDU word NumElements; // Num of elements that we are asking for this telegram int TotElements; // Total elements requested int Result = 0; WordSize=DataSizeByte(Job.WordLen); // The size in bytes of an element that we are pushing if (WordSize==0) return errCliInvalidWordLen; // First check : params bounds if ((Job.Number<0) || (Job.Number>65535) || (Job.Start<0) || (Job.Amount<1)) return errCliInvalidParams; // Second check : transport size if ((Job.WordLen==S7WLBit) && (Job.Amount>1)) return errCliInvalidTransportSize; RHSize =sizeof(TS7ReqHeader)+ // Request header 2+ // FunWrite+ItemCount (of TReqFunWriteParams) sizeof(TReqFunWriteItem)+// 1 item reference 4; // ReturnCode+TransportSize+DataLength RPSize =sizeof(TReqFunWriteItem)+2; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunWriteParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqFunWriteDataItem(pbyte(ReqParams)+sizeof(TReqFunWriteItem)+2); // 2 = FunWrite+ItemsCount Target =pbyte(ReqData)+4; // 4 = ReturnCode+TransportSize+DataLength Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunWrite(pbyte(Answer)+ResHeaderSize23); // Each packet cannot exceed the PDU length (in bytes) negotiated, and moreover // we must ensure to transfer a "finite" number of item per PDU MaxElements=(PDULength-RHSize) / WordSize; TotElements=Job.Amount; Start =Job.Start; while ((TotElements>0) && (Result==0)) { NumElements=TotElements; if (NumElements>MaxElements) NumElements=MaxElements; Source=pbyte(Job.pData)+Offset; Size=NumElements * WordSize; PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen =SwapWord(RPSize); // 14 bytes params PDUH_out->DataLen =SwapWord(Size+4); ReqParams->FunWrite=pduFuncWrite; // 0x05 ReqParams->ItemsCount=1; ReqParams->Items[0].ItemHead[0]=0x12; ReqParams->Items[0].ItemHead[1]=0x0A; ReqParams->Items[0].ItemHead[2]=0x10; ReqParams->Items[0].TransportSize=Job.WordLen; ReqParams->Items[0].Length=SwapWord(NumElements); ReqParams->Items[0].Area=Job.Area; if (Job.Area==S7AreaDB) ReqParams->Items[0].DBNumber=SwapWord(Job.Number); else ReqParams->Items[0].DBNumber=0x0000; // Adjusts the offset if ((Job.WordLen==S7WLBit) || (Job.WordLen==S7WLCounter) || (Job.WordLen==S7WLTimer)) Address=Start; else Address=Start*8; ReqParams->Items[0].Address[2]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[0].Address[1]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[0].Address[0]=Address & 0x000000FF; ReqData->ReturnCode=0x00; switch(Job.WordLen) { case S7WLBit: ReqData->TransportSize=TS_ResBit; break; case S7WLInt: case S7WLDInt: ReqData->TransportSize=TS_ResInt; break; case S7WLReal: ReqData->TransportSize=TS_ResReal; break; case S7WLChar : case S7WLCounter: case S7WLTimer: ReqData->TransportSize=TS_ResOctet; break; default: ReqData->TransportSize=TS_ResByte; break; }; if ((ReqData->TransportSize!=TS_ResOctet) && (ReqData->TransportSize!=TS_ResReal) && (ReqData->TransportSize!=TS_ResBit)) ReqData->DataLength=SwapWord(Size*8); else ReqData->DataLength=SwapWord(Size); memcpy(Target, Source, Size); IsoSize=RHSize + Size; Result=isoExchangeBuffer(0,IsoSize); if (Result==0) // 1St check : Iso result { Result=CpuError(SwapWord(Answer->Error)); // 2nd level global error if (Result==0) { // 2th check : item error if (ResParams->Data[0] == 0xFF) // <-- 0xFF means Result OK Result=0; else // Now we check the error : if it's the first part we report the cpu error // otherwise we warn that the function failed but some data were written if (First) Result=CpuError(ResParams->Data[0]); else Result=errCliPartialDataWritten; }; Offset+=Size; }; First=false; TotElements-=NumElements; Start+=(NumElements*WordSize); } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opReadMultiVars() { PS7DataItem Item; PReqFunReadParams ReqParams; PS7ResHeader23 Answer; PResFunReadParams ResParams; TResFunReadData ResData; word RPSize; // ReqParams size uintptr_t Offset =0 ; word Slice; longword Address; int IsoSize; pbyte P; int ItemsCount, c, Result; Item = PS7DataItem(Job.pData); ItemsCount = Job.Amount; // Some useful initial check to detail the errors (Since S7 CPU always answers // with $05 if (something is wrong in params) if (ItemsCount>MaxVars) return errCliTooManyItems; // Adjusts Word Length in case of timers and counters and clears results for (c = 0; c < ItemsCount; c++) { Item->Result=0; if (Item->Area==S7AreaCT) Item->WordLen=S7WLCounter; if (Item->Area==S7AreaTM) Item->WordLen=S7WLTimer; Item++; }; // Let's build the PDU RPSize = word(2 + ItemsCount * sizeof(TReqFunReadItem)); ReqParams = PReqFunReadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer = PS7ResHeader23(&PDU.Payload); ResParams = PResFunReadParams(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(RPSize); // Request params size PDUH_out->DataLen=0x0000; // No data in output // Fill Params ReqParams->FunRead=pduFuncRead; // 0x04 ReqParams->ItemsCount=ItemsCount; Item = PS7DataItem(Job.pData); for (c = 0; c < ItemsCount; c++) { ReqParams->Items[c].ItemHead[0]=0x12; ReqParams->Items[c].ItemHead[1]=0x0A; ReqParams->Items[c].ItemHead[2]=0x10; ReqParams->Items[c].TransportSize=Item->WordLen; ReqParams->Items[c].Length=SwapWord(Item->Amount); ReqParams->Items[c].Area=Item->Area; // Automatically drops DBNumber if (Area is not DB if (Item->Area==S7AreaDB) ReqParams->Items[c].DBNumber=SwapWord(Item->DBNumber); else ReqParams->Items[c].DBNumber=0x0000; // Adjusts the offset if ((Item->WordLen==S7WLBit) || (Item->WordLen==S7WLCounter) || (Item->WordLen==S7WLTimer)) Address=Item->Start; else Address=Item->Start*8; // Builds the offset ReqParams->Items[c].Address[2]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[c].Address[1]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[c].Address[0]=Address & 0x000000FF; Item++; }; IsoSize=RPSize+sizeof(TS7ReqHeader); if (IsoSize>PDULength) return errCliSizeOverPDU; Result=isoExchangeBuffer(0,IsoSize); if (Result!=0) return Result; // Function level error if (Answer->Error!=0) return CpuError(SwapWord(Answer->Error)); if (ResParams->ItemCount!=ItemsCount) return errCliInvalidPlcAnswer; P=pbyte(ResParams)+sizeof(TResFunReadParams); Item = PS7DataItem(Job.pData); for (c = 0; c < ItemsCount; c++) { ResData[c] =PResFunReadItem(pbyte(P)+Offset); Slice=0; // Item level error if (ResData[c]->ReturnCode==0xFF) // <-- 0xFF means Result OK { // Calcs data size in bytes Slice=SwapWord(ResData[c]->DataLength); // Adjust Size in accord of TransportSize if ((ResData[c]->TransportSize != TS_ResOctet) && (ResData[c]->TransportSize != TS_ResReal) && (ResData[c]->TransportSize != TS_ResBit)) Slice=Slice >> 3; memcpy(Item->pdata, ResData[c]->Data, Slice); Item->Result=0; } else Item->Result=CpuError(ResData[c]->ReturnCode); if ((Slice % 2)!=0) Slice++; // Skip fill byte for Odd frame Offset+=(4+Slice); Item++; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opWriteMultiVars() { PS7DataItem Item; PReqFunWriteParams ReqParams; PResFunWrite ResParams; TReqFunWriteData ReqData; PS7ResHeader23 Answer; pbyte P; uintptr_t Offset; longword Address; int ItemsCount, c, IsoSize; word RPSize; // ReqParams size word Size; // Write data size int WordSize, Result; Item = PS7DataItem(Job.pData); ItemsCount = Job.Amount; // Some useful initial check to detail the errors (Since S7 CPU always answers // with $05 if (something is wrong in params) if (ItemsCount>MaxVars) return errCliTooManyItems; // Adjusts Word Length in case of timers and counters and clears results for (c = 0; c < ItemsCount; c++) { Item->Result=0; if (Item->Area==S7AreaCT) Item->WordLen=S7WLCounter; if (Item->Area==S7AreaTM) Item->WordLen=S7WLTimer; Item++; }; // Let's build the PDU : setup pointers RPSize = word(2 + ItemsCount * sizeof(TReqFunWriteItem)); ReqParams = PReqFunWriteParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer = PS7ResHeader23(&PDU.Payload); ResParams = PResFunWrite(pbyte(Answer)+ResHeaderSize23); P=pbyte(ReqParams)+RPSize; // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(RPSize); // Request params size // Fill Params ReqParams->FunWrite=pduFuncWrite; // 0x05 ReqParams->ItemsCount=ItemsCount; Offset=0; Item = PS7DataItem(Job.pData); for (c = 0; c < ItemsCount; c++) { // Items Params ReqParams->Items[c].ItemHead[0]=0x12; ReqParams->Items[c].ItemHead[1]=0x0A; ReqParams->Items[c].ItemHead[2]=0x10; ReqParams->Items[c].TransportSize=Item->WordLen; ReqParams->Items[c].Length=SwapWord(Item->Amount); ReqParams->Items[c].Area=Item->Area; if (Item->Area==S7AreaDB) ReqParams->Items[c].DBNumber=SwapWord(Item->DBNumber); else ReqParams->Items[c].DBNumber=0x0000; // Adjusts the offset if ((Item->WordLen==S7WLBit) || (Item->WordLen==S7WLCounter) || (Item->WordLen==S7WLTimer)) Address=Item->Start; else Address=Item->Start*8; // Builds the offset ReqParams->Items[c].Address[2]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[c].Address[1]=Address & 0x000000FF; Address=Address >> 8; ReqParams->Items[c].Address[0]=Address & 0x000000FF; // Items Data ReqData[c]=PReqFunWriteDataItem(pbyte(P)+Offset); ReqData[c]->ReturnCode=0x00; switch (Item->WordLen) { case S7WLBit : ReqData[c]->TransportSize=TS_ResBit; break; case S7WLInt : case S7WLDInt : ReqData[c]->TransportSize=TS_ResInt; break; case S7WLReal : ReqData[c]->TransportSize=TS_ResReal; break; case S7WLChar : case S7WLCounter : case S7WLTimer : ReqData[c]->TransportSize=TS_ResOctet; break; default : ReqData[c]->TransportSize=TS_ResByte; // byte/word/dword etc. break; }; WordSize=DataSizeByte(Item->WordLen); Size=Item->Amount * WordSize; if ((ReqData[c]->TransportSize!=TS_ResOctet) && (ReqData[c]->TransportSize!=TS_ResReal) && (ReqData[c]->TransportSize!=TS_ResBit)) ReqData[c]->DataLength=SwapWord(Size*8); else ReqData[c]->DataLength=SwapWord(Size); memcpy(ReqData[c]->Data, Item->pdata, Size); if ((Size % 2) != 0 && (ItemsCount - c != 1)) Size++; // Skip fill byte for Odd frame (except for the last one) Offset+=(4+Size); // next item Item++; }; PDUH_out->DataLen=SwapWord(word(Offset)); IsoSize=RPSize+sizeof(TS7ReqHeader)+int(Offset); if (IsoSize>PDULength) return errCliSizeOverPDU; Result=isoExchangeBuffer(0,IsoSize); if (Result!=0) return Result; // Function level error if (Answer->Error!=0) return CpuError(SwapWord(Answer->Error)); if (ResParams->ItemCount!=ItemsCount) return errCliInvalidPlcAnswer; Item = PS7DataItem(Job.pData); for (c = 0; c < ItemsCount; c++) { // Item level error if (ResParams->Data[c]==0xFF) // <-- 0xFF means Result OK Item->Result=0; else Item->Result=CpuError(ResParams->Data[c]); Item++; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opListBlocks() { PReqFunGetBlockInfo ReqParams; PReqDataFunBlocks ReqData; PResFunGetBlockInfo ResParams; PDataFunListAll ResData; PS7ResHeader17 Answer; PS7BlocksList List; int IsoSize, Result; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunGetBlockInfo(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataFunBlocks(pbyte(ReqParams)+sizeof(TReqFunGetBlockInfo)); Answer =PS7ResHeader17(&PDU.Payload); ResParams=PResFunGetBlockInfo(pbyte(Answer)+ResHeaderSize17); ResData =PDataFunListAll(pbyte(ResParams)+sizeof(TResFunGetBlockInfo)); List =PS7BlocksList(Job.pData); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunGetBlockInfo)); // 8 bytes params PDUH_out->DataLen=SwapWord(sizeof(TReqDataFunBlocks)); // 4 bytes data // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grBlocksInfo; ReqParams->SubFun =SFun_ListAll; ReqParams->Seq =0x00; // Fill data ReqData[0] =0x0A; ReqData[1] =0x00; ReqData[2] =0x00; ReqData[3] =0x00; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunGetBlockInfo)+sizeof(TReqDataFunBlocks); Result=isoExchangeBuffer(0,IsoSize); // Get Data if (Result==0) { if (ResParams->ErrNo==0) { if (SwapWord(ResData->Length)!=28) return errCliInvalidPlcAnswer; for (int c = 0; c < 7; c++) { switch (ResData->Blocks[c].BType) { case Block_OB: List->OBCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_DB: List->DBCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_SDB: List->SDBCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_FC: List->FCCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_SFC: List->SFCCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_FB: List->FBCount=SwapWord(ResData->Blocks[c].BCount); break; case Block_SFB: List->SFBCount=SwapWord(ResData->Blocks[c].BCount); break; } } } else Result=CpuError(SwapWord(ResParams->ErrNo)); } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opListBlocksOfType() { PReqFunGetBlockInfo ReqParams; PReqDataBlockOfType ReqData; PS7ResHeader17 Answer; PResFunGetBlockInfo ResParams; PDataFunGetBot ResData; longword *PadData; word *List; bool First; bool Done = false; byte BlockType, In_Seq; int Count, Last, IsoSize, Result; int c, CThis; word DataLength; bool RoomError = false; BlockType=Job.Area; List=(word*)(&opData); // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunGetBlockInfo(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader17(&PDU.Payload); ResParams=PResFunGetBlockInfo(pbyte(Answer)+ResHeaderSize17); ResData =PDataFunGetBot(pbyte(ResParams)+sizeof(TResFunGetBlockInfo)); // Get Data First =true; In_Seq=0x00; // first group sequence, next will come from PLC Count =0; Last =0; do { //<--------------------------------------------------------- Get next slice // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc if (First) { PDUH_out->ParLen=SwapWord(8); // 8 bytes params PDUH_out->DataLen=SwapWord(6); // 6 bytes data DataLength=14; } else { PDUH_out->ParLen=SwapWord(12); // 12 bytes params PDUH_out->DataLen=SwapWord(4); // 4 bytes data DataLength=16; } // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; if (First) ReqParams->Plen =0x04; else ReqParams->Plen =0x08; if (First) ReqParams->Uk = 0x11; else ReqParams->Uk = 0x12; ReqParams->Tg =grBlocksInfo; ReqParams->SubFun =SFun_ListBoT; ReqParams->Seq =In_Seq; // Fill data if (First) { // overlap resvd and error to avoid another struct... ReqData =PReqDataBlockOfType(pbyte(ReqParams)+sizeof(TReqFunGetBlockInfo)); ReqData->RetVal =0xFF; ReqData->TSize =TS_ResOctet; ReqData->Length =SwapWord(0x0002); ReqData->Zero =0x30; // zero ascii '0' ReqData->BlkType =BlockType; } else { PadData =(longword*)(pbyte(ReqParams)+sizeof(TReqFunGetBlockInfo)); ReqData =PReqDataBlockOfType(pbyte(ReqParams)+sizeof(TReqFunGetBlockInfo)+4); *PadData =0x00000000; ReqData->RetVal =0x0A; ReqData->TSize =0x00; ReqData->Length =0x0000; ReqData->Zero =0x00; ReqData->BlkType =0x00; }; IsoSize=sizeof(TS7ReqHeader)+DataLength; Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if (ResParams->ErrNo==0) { if (ResData->RetVal==0xFF) { Done=((ResParams->Rsvd & 0xFF00) == 0); // Low order byte = 0x00 => the sequence is done In_Seq=ResParams->Seq; // every next telegram must have this number CThis=((SwapWord(ResData->DataLen) - 4 ) / 4) + 1; // Partial counter for (c=0; c < CThis+1; c++) { *List=SwapWord(ResData->Items[c].BlockNum); Last++; List++; if (Last==0x8000) { Done=true; break; }; }; Count+=CThis; // Total counter List--; } else Result=errCliItemNotAvailable; } else Result=errCliItemNotAvailable; }; First=false; //---------------------------------------------------------> Get next slice } while ((!Done) && (Result==0)); *Job.pAmount=0; if (Result==0) { if (Count>Job.Amount) { Count=Job.Amount; RoomError=true; } memcpy(Job.pData, &opData, Count*2); *Job.pAmount=Count; if (RoomError) // Result==0 -> override if romerror Result=errCliPartialDataRead; }; return Result; } //--------------------------------------------------------------------------- void TSnap7MicroClient::FillTime(word SiemensTime, char *PTime) { // SiemensTime -> number of seconds after 1/1/1984 // This is not S7 date and time but is used only internally for block info time_t TheDate = (SiemensTime * 86400)+ DeltaSecs; struct tm * timeinfo = localtime (&TheDate); if (timeinfo!=NULL) { strftime(PTime,11,"%Y/%m/%d",timeinfo); } else *PTime='\0'; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opAgBlockInfo() { PS7BlockInfo BlockInfo; PReqFunGetBlockInfo ReqParams; PReqDataBlockInfo ReqData; PS7ResHeader17 Answer; PResFunGetBlockInfo ResParams; PResDataBlockInfo ResData; byte BlockType; int BlockNum, IsoSize, Result; BlockType=Job.Area; BlockNum =Job.Number; BlockInfo=PS7BlockInfo(Job.pData); memset(BlockInfo,0,sizeof(TS7BlockInfo)); // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunGetBlockInfo(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataBlockInfo(pbyte(ReqParams)+sizeof(TReqFunGetBlockInfo)); Answer =PS7ResHeader17(&PDU.Payload); ResParams=PResFunGetBlockInfo(pbyte(Answer)+ResHeaderSize17); ResData =PResDataBlockInfo(pbyte(ResParams)+sizeof(TResFunGetBlockInfo)); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunGetBlockInfo)); // 8 bytes params PDUH_out->DataLen=SwapWord(sizeof(TReqDataBlockInfo)); // 4 bytes data // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grBlocksInfo; ReqParams->SubFun =SFun_BlkInfo; ReqParams->Seq =0x00; // Fill data ReqData->RetVal =0xFF; ReqData->TSize =TS_ResOctet; ReqData->DataLen =SwapWord(0x0008); ReqData->BlkPrfx =0x30; ReqData->BlkType =BlockType; ReqData->A =0x41; ReqData->AsciiBlk[0]=(BlockNum / 10000)+0x30; BlockNum=BlockNum % 10000; ReqData->AsciiBlk[1]=(BlockNum / 1000)+0x30; BlockNum=BlockNum % 1000; ReqData->AsciiBlk[2]=(BlockNum / 100)+0x30; BlockNum=BlockNum % 100; ReqData->AsciiBlk[3]=(BlockNum / 10)+0x30; BlockNum=BlockNum % 10; ReqData->AsciiBlk[4]=(BlockNum / 1)+0x30; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunGetBlockInfo)+sizeof(TReqDataBlockInfo); Result=isoExchangeBuffer(0,IsoSize); // Get Data if (Result==0) { if (ResParams->ErrNo==0) { if (SwapWord(ResData->Length)<40) // 78 return errCliInvalidPlcAnswer; if (ResData->RetVal==0xFF) // <-- 0xFF means Result OK { //<----------------------------------------------Fill block info BlockInfo->BlkType=ResData->SubBlkType; BlockInfo->BlkNumber=SwapWord(ResData->BlkNumber); BlockInfo->BlkLang=ResData->BlkLang; BlockInfo->BlkFlags=ResData->BlkFlags; BlockInfo->MC7Size=SwapWord(ResData->MC7Len); BlockInfo->LoadSize=SwapDWord(ResData->LenLoadMem); BlockInfo->LocalData=SwapWord(ResData->LocDataLen); BlockInfo->SBBLength=SwapWord(ResData->SbbLen); BlockInfo->CheckSum=SwapWord(ResData->BlkChksum); BlockInfo->Version=ResData->Version; memcpy(BlockInfo->Author, ResData->Author, 8); memcpy(BlockInfo->Family,ResData->Family,8); memcpy(BlockInfo->Header,ResData->Header,8); FillTime(SwapWord(ResData->CodeTime_dy),BlockInfo->CodeDate); FillTime(SwapWord(ResData->IntfTime_dy),BlockInfo->IntfDate); //---------------------------------------------->Fill block info } else Result=CpuError(ResData->RetVal); } else Result=CpuError(SwapWord(ResParams->ErrNo)); }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opDBGet() { TS7BlockInfo BI; void * usrPData; int * usrPSize; int Result, Room; bool RoomError = false; // Stores user pointer usrPData=Job.pData; usrPSize=Job.pAmount; Room =Job.Amount; // 1 Pass : Get block info Job.Area=Block_DB; Job.pData=&BI; Result=opAgBlockInfo(); // 2 Pass : Read the whole (MC7Size bytes) DB. if (Result==0) { // Check user space if (BI.MC7Size>Room) { Job.Amount=Room; RoomError=true; } else Job.Amount =BI.MC7Size; // The data is read even if the buffer is small (the error is reported). // Imagine that we want to read only a small amount of data at the // beginning of a DB regardless it's size.... Job.Area =S7AreaDB; Job.WordLen=S7WLByte; Job.Start =0; Job.pData =usrPData; Result =opReadArea(); if (Result==0) *usrPSize=Job.Amount; } if ((Result==0) && RoomError) return errCliBufferTooSmall; else return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opDBFill() { TS7BlockInfo BI; int Result; // new op : get block info Job.Op =s7opAgBlockInfo; Job.Area =Block_DB; Job.pData=&BI; Result =opAgBlockInfo(); // Restore original op Job.Op =s7opDBFill; // Fill internal buffer then write it if (Result==0) { Job.Amount =BI.MC7Size; Job.Area =S7AreaDB; Job.WordLen=S7WLByte; Job.Start =0; memset(&opData, byte(Job.IParam), Job.Amount); Job.pData =&opData; Result =opWriteArea(); } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opUpload() { PS7ResHeader23 Answer; int IsoSize; byte Upload_ID = 0; // not strictly needed, only to avoid warning byte BlockType; int BlockNum, BlockLength, Result; bool Done, Full; // if full==true, the data will be compatible to full download function uintptr_t Offset; bool RoomError = false; BlockType=Job.Area; BlockNum =Job.Number; Full =Job.IParam==1; // Setup Answer (is the same for all Upload pdus) Answer= PS7ResHeader23(&PDU.Payload); // Init sequence Done =false; Offset=0; //<-------------------------------------------------------------StartUpload PReqFunStartUploadParams ReqParams; PResFunStartUploadParams ResParams; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunStartUploadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ResParams=PResFunStartUploadParams(pbyte(Answer)+ResHeaderSize23); // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunStartUploadParams));// params size PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->FunSUpld=pduStartUpload; ReqParams->Uk6[0]=0x00; ReqParams->Uk6[1]=0x00; ReqParams->Uk6[2]=0x00; ReqParams->Uk6[3]=0x00; ReqParams->Uk6[4]=0x00; ReqParams->Uk6[5]=0x00; ReqParams->Upload_ID=Upload_ID; // At begining is 0) we will put upload id incoming from plc ReqParams->Len_1 =0x09; // 9 bytes from here ReqParams->Prefix=0x5F; ReqParams->BlkPrfx=0x30; // '0' ReqParams->BlkType=BlockType; // Block number ReqParams->AsciiBlk[0]=(BlockNum / 10000)+0x30; BlockNum=BlockNum % 10000; ReqParams->AsciiBlk[1]=(BlockNum / 1000)+0x30; BlockNum=BlockNum % 1000; ReqParams->AsciiBlk[2]=(BlockNum / 100)+0x30; BlockNum=BlockNum % 100; ReqParams->AsciiBlk[3]=(BlockNum / 10)+0x30; BlockNum=BlockNum % 10; ReqParams->AsciiBlk[4]=(BlockNum / 1)+0x30; ReqParams->A=0x41; // 'A' IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunStartUploadParams); Result=isoExchangeBuffer(0,IsoSize); // Get Upload Infos (only ID now) if (Result==0) { if (Answer->Error==0) Upload_ID=ResParams->Upload_ID; else Result=CpuError(SwapWord(Answer->Error)); }; //------------------------------------------------------------->StartUpload if (Result==0) { //<--------------------------------------------------------FirstUpload PReqFunUploadParams ReqParams; PResFunUploadParams ResParams; PResFunUploadDataHeaderFirst ResDataHeader; pbyte Source; pbyte Target; int Size; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunUploadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); // First upload pdu consists of params, block info header, data. ResParams=PResFunUploadParams(pbyte(Answer)+ResHeaderSize23); ResDataHeader=PResFunUploadDataHeaderFirst(pbyte(ResParams)+sizeof(TResFunUploadParams)); if (Full) Source=pbyte(ResDataHeader)+4; // skip only the mini header else Source=pbyte(ResDataHeader)+sizeof(TResFunUploadDataHeaderFirst); // not full : skip the data header // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunUploadParams));// params size PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->FunUpld=pduUpload; ReqParams->Uk6[0]=0x00; ReqParams->Uk6[1]=0x00; ReqParams->Uk6[2]=0x00; ReqParams->Uk6[3]=0x00; ReqParams->Uk6[4]=0x00; ReqParams->Uk6[5]=0x00; ReqParams->Upload_ID=Upload_ID; // At begining is 0) we will put upload id incoming from plc IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunUploadParams); Result=isoExchangeBuffer(0,IsoSize); // Get Upload Infos (only ID now) if (Result==0) { if (Answer->Error==0) { Done=ResParams->EoU==0; if (Full) Size=SwapWord(Answer->DataLen)-4; // Full data Size else Size=SwapWord(Answer->DataLen)-sizeof(TResFunUploadDataHeaderFirst); // Size of this data slice BlockLength=SwapWord(ResDataHeader->MC7Len); // Full block size in byte Target=pbyte(&opData)+Offset; memcpy(Target, Source, Size); Offset+=Size; } else Result=errCliUploadSequenceFailed; }; //-------------------------------------------------------->FirstUpload while (!Done && (Result==0)) { //<----------------------------------------------------NextUpload PReqFunUploadParams ReqParams; PResFunUploadParams ResParams; PResFunUploadDataHeaderNext ResDataHeader; pbyte Source; pbyte Target; int Size; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunUploadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); // Next upload pdu consists of params, small info header, data. ResParams=PResFunUploadParams(pbyte(Answer)+ResHeaderSize23); ResDataHeader=PResFunUploadDataHeaderNext(pbyte(ResParams)+sizeof(TResFunUploadParams)); Source=pbyte(ResDataHeader)+sizeof(TResFunUploadDataHeaderNext); // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunUploadParams));// params size PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->FunUpld=pduUpload; ReqParams->Uk6[0]=0x00; ReqParams->Uk6[1]=0x00; ReqParams->Uk6[2]=0x00; ReqParams->Uk6[3]=0x00; ReqParams->Uk6[4]=0x00; ReqParams->Uk6[5]=0x00; ReqParams->Upload_ID=Upload_ID; // At begining is 0) we will put upload id incoming from plc IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunUploadParams); Result=isoExchangeBuffer(0,IsoSize); // Get Upload Infos (only ID now) if (Result==0) { if (Answer->Error==0) { Done=ResParams->EoU==0; Size=SwapWord(Answer->DataLen)-sizeof(TResFunUploadDataHeaderNext); // Size of this data slice Target=pbyte(&opData)+Offset; memcpy(Target, Source, Size); Offset+=Size; } else Result=errCliUploadSequenceFailed; }; //---------------------------------------------------->NextUpload } if (Result==0) { //<----------------------------------------------------EndUpload; PReqFunEndUploadParams ReqParams; PResFunEndUploadParams ResParams; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunEndUploadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ResParams=PResFunEndUploadParams(pbyte(Answer)+ResHeaderSize23); // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunEndUploadParams));// params size PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->FunEUpld=pduEndUpload; ReqParams->Uk6[0]=0x00; ReqParams->Uk6[1]=0x00; ReqParams->Uk6[2]=0x00; ReqParams->Uk6[3]=0x00; ReqParams->Uk6[4]=0x00; ReqParams->Uk6[5]=0x00; ReqParams->Upload_ID=Upload_ID; // At begining is 0) we will put upload id incoming from plc IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunEndUploadParams); Result=isoExchangeBuffer(0,IsoSize); // Get EndUpload Result if (Result==0) { if ((Answer->Error!=0) || (ResParams->FunEUpld!=pduEndUpload)) Result=errCliUploadSequenceFailed; }; //---------------------------------------------------->EndUpload; } }; *Job.pAmount=0; if (Result==0) { if (Full) { opSize=int(Offset); if (opSize<78) Result=errCliInvalidDataSizeRecvd; } else { opSize=BlockLength; if (opSize<1) Result=errCliInvalidDataSizeRecvd; }; if (Result==0) { // Checks user space if (Job.Amount<opSize) { opSize=Job.Amount; RoomError = true; }; memcpy(Job.pData, &opData, opSize); *Job.pAmount=opSize; if (RoomError) // Result==0 -> override if romerror Result=errCliPartialDataRead; }; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opDownload() { PS7CompactBlockInfo Info; PS7BlockFooter Footer; int BlockNum, StoreBlockNum, BlockAmount; int BlockSize, BlockSizeLd; int BlockType, Remainder; int Result, IsoSize; bool Done = false; uintptr_t Offset; BlockAmount=Job.Amount; BlockNum =Job.Number; Result=CheckBlock(-1,-1,&opData,BlockAmount); if (Result==0) { Info=PS7CompactBlockInfo(&opData); // Gets blocktype BlockType=SubBlockToBlock(Info->SubBlkType); if (BlockNum>=0) Info->BlkNum=SwapWord(BlockNum); // change the number else BlockNum=SwapWord(Info->BlkNum); // use the header's number BlockSizeLd=BlockAmount; // load mem needed for this block BlockSize =SwapWord(Info->MC7Len); // net size Footer=PS7BlockFooter(pbyte(&opData)+BlockSizeLd-sizeof(TS7BlockFooter)); Footer->Chksum=0x0000; Offset=0; Remainder=BlockAmount; //<---------------------------------------------- Start Download request PReqStartDownloadParams ReqParams; PResStartDownloadParams ResParams; PS7ResHeader23 Answer; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqStartDownloadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResStartDownloadParams(pbyte(Answer)+ResHeaderSize23); // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqStartDownloadParams)); PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->FunSDwnld = pduReqDownload; ReqParams->Uk6[0]=0x00; ReqParams->Uk6[1]=0x01; ReqParams->Uk6[2]=0x00; ReqParams->Uk6[3]=0x00; ReqParams->Uk6[4]=0x00; ReqParams->Uk6[5]=0x00; ReqParams->Dwnld_ID=0x00; ReqParams->Len_1 =0x09; ReqParams->Prefix=0x5F; ReqParams->BlkPrfx=0x30; ReqParams->BlkType=BlockType; StoreBlockNum=BlockNum; ReqParams->AsciiBlk[0]=(BlockNum / 10000)+0x30; BlockNum=BlockNum % 10000; ReqParams->AsciiBlk[1]=(BlockNum / 1000)+0x30; BlockNum=BlockNum % 1000; ReqParams->AsciiBlk[2]=(BlockNum / 100)+0x30; BlockNum=BlockNum % 100; ReqParams->AsciiBlk[3]=(BlockNum / 10)+0x30; BlockNum=BlockNum % 10; ReqParams->AsciiBlk[4]=(BlockNum / 1)+0x30; ReqParams->P =0x50; ReqParams->Len_2=0x0D; ReqParams->Uk1 =0x31; // '1' BlockNum=StoreBlockNum; // Load memory ReqParams->AsciiLoad[0]=(BlockSizeLd / 100000)+0x30; BlockSizeLd=BlockSizeLd % 100000; ReqParams->AsciiLoad[1]=(BlockSizeLd / 10000)+0x30; BlockSizeLd=BlockSizeLd % 10000; ReqParams->AsciiLoad[2]=(BlockSizeLd / 1000)+0x30; BlockSizeLd=BlockSizeLd % 1000; ReqParams->AsciiLoad[3]=(BlockSizeLd / 100)+0x30; BlockSizeLd=BlockSizeLd % 100; ReqParams->AsciiLoad[4]=(BlockSizeLd / 10)+0x30; BlockSizeLd=BlockSizeLd % 10; ReqParams->AsciiLoad[5]=(BlockSizeLd / 1)+0x30; // MC7 memory ReqParams->AsciiMC7[0]=(BlockSize / 100000)+0x30; BlockSize=BlockSize % 100000; ReqParams->AsciiMC7[1]=(BlockSize / 10000)+0x30; BlockSize=BlockSize % 10000; ReqParams->AsciiMC7[2]=(BlockSize / 1000)+0x30; BlockSize=BlockSize % 1000; ReqParams->AsciiMC7[3]=(BlockSize / 100)+0x30; BlockSize=BlockSize % 100; ReqParams->AsciiMC7[4]=(BlockSize / 10)+0x30; BlockSize=BlockSize % 10; ReqParams->AsciiMC7[5]=(BlockSize / 1)+0x30; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqStartDownloadParams); Result=isoExchangeBuffer(0,IsoSize); // Get Result if (Result==0) { if (SwapWord(Answer->Error)!=Code7NeedPassword) { if ((Answer->Error!=0) || (*ResParams!=pduReqDownload)) Result=errCliDownloadSequenceFailed; } else Result=errCliNeedPassword; } //----------------------------------------------> Start Download request if (Result==0) { do { //<-------------------------------- Download sequence (PLC requests) PReqDownloadParams ReqParams; PS7ResHeader23 Answer; PResDownloadParams ResParams; PResDownloadDataHeader ResData; int Slice, Size, MaxSlice; word Sequence; pbyte Source; pbyte Target; ReqParams=PReqDownloadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResDownloadParams(pbyte(Answer)+ResHeaderSize23); ResData =PResDownloadDataHeader(pbyte(ResParams)+sizeof(TResDownloadParams)); Target =pbyte(ResData)+sizeof(TResDownloadDataHeader); Source =pbyte(&opData)+Offset; Result=isoRecvBuffer(0,Size); if (Result==0) { if ((u_int(Size)>sizeof(TS7ReqHeader)) && (ReqParams->Fun==pduDownload)) { Sequence=PDUH_out->Sequence; // Max data slice that we can fit in this pdu MaxSlice=PDULength-ResHeaderSize23-sizeof(TResDownloadParams)-sizeof(TResDownloadDataHeader); Slice=Remainder; if (Slice>MaxSlice) Slice=MaxSlice; Remainder-=Slice; Offset+=Slice; Done=Remainder<=0; // Init Answer Answer->P=0x32; Answer->PDUType=PduType_response; Answer->AB_EX=0x0000; Answer->Sequence=Sequence; Answer->ParLen =SwapWord(sizeof(TResDownloadParams)); Answer->DataLen=SwapWord(word(sizeof(TResDownloadDataHeader))+Slice); Answer->Error =0x0000; // Init Params ResParams->FunDwnld=pduDownload; if (Remainder>0) ResParams->EoS=0x01; else ResParams->EoS=0x00; // Init Data ResData->DataLen=SwapWord(Slice); ResData->FB_00=0xFB00; memcpy(Target, Source, Slice); // Send the slice IsoSize=ResHeaderSize23+sizeof(TResDownloadParams)+sizeof(TResDownloadDataHeader)+Slice; Result=isoSendBuffer(0,IsoSize); } else Result=errCliDownloadSequenceFailed; }; //--------------------------------> Download sequence (PLC requests) } while (!Done && (Result==0)); if (Result==0) { //<-------------------------------------------Perform Download Ended PReqDownloadParams ReqParams; PS7ResHeader23 Answer; PResEndDownloadParams ResParams; int Size; word Sequence; ReqParams=PReqDownloadParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResEndDownloadParams(pbyte(Answer)+ResHeaderSize23); Result=isoRecvBuffer(0,Size); if (Result==0) { if ((u_int(Size)>sizeof(TS7ReqHeader)) && (ReqParams->Fun==pduDownloadEnded)) { Sequence=PDUH_out->Sequence; // Init Answer Answer->P=0x32; Answer->PDUType=PduType_response; Answer->AB_EX=0x0000; Answer->Sequence=Sequence; Answer->ParLen =SwapWord(sizeof(TResEndDownloadParams)); Answer->DataLen=0x0000; Answer->Error =0x0000; // Init Params *ResParams=pduDownloadEnded; IsoSize=ResHeaderSize23+sizeof(TResEndDownloadParams); Result=isoSendBuffer(0,IsoSize); } else Result=errCliDownloadSequenceFailed; }; //------------------------------------------->Perform Download Ended if (Result==0) { //<----------------------------------- Insert block into the unit PReqControlBlockParams ReqParams; PS7ResHeader23 Answer; pbyte ResParams; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqControlBlockParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer=PS7ResHeader23(&PDU.Payload); ResParams=pbyte(Answer)+ResHeaderSize23; // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqControlBlockParams)); PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->Fun = pduControl; ReqParams->Uk7[0]=0x00; ReqParams->Uk7[1]=0x00; ReqParams->Uk7[2]=0x00; ReqParams->Uk7[3]=0x00; ReqParams->Uk7[4]=0x00; ReqParams->Uk7[5]=0x00; ReqParams->Uk7[6]=0xFD; ReqParams->Len_1 =SwapWord(0x0A); ReqParams->NumOfBlocks=0x01; ReqParams->ByteZero =0x00; ReqParams->AsciiZero =0x30; ReqParams->BlkType=BlockType; ReqParams->AsciiBlk[0]=(BlockNum / 10000)+0x30; BlockNum=BlockNum % 10000; ReqParams->AsciiBlk[1]=(BlockNum / 1000)+0x30; BlockNum=BlockNum % 1000; ReqParams->AsciiBlk[2]=(BlockNum / 100)+0x30; BlockNum=BlockNum % 100; ReqParams->AsciiBlk[3]=(BlockNum / 10)+0x30; BlockNum=BlockNum % 10; ReqParams->AsciiBlk[4]=(BlockNum / 1)+0x30; ReqParams->SFun =SFun_Insert; ReqParams->Len_2=0x05; ReqParams->Cmd[0]='_'; ReqParams->Cmd[1]='I'; ReqParams->Cmd[2]='N'; ReqParams->Cmd[3]='S'; ReqParams->Cmd[4]='E'; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqControlBlockParams); Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if ((Answer->Error!=0) || (*ResParams!=pduControl)) Result=errCliInsertRefused; }; //-----------------------------------> Insert block into the unit } }; }; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opDelete() { PReqControlBlockParams ReqParams; PS7ResHeader23 Answer; pbyte ResParams; int IsoSize, BlockType, BlockNum, Result; BlockType=Job.Area; BlockNum =Job.Number; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqControlBlockParams(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=pbyte(Answer)+ResHeaderSize23; // Init Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqControlBlockParams)); PDUH_out->DataLen=0x0000; // No data // Init Params ReqParams->Fun = pduControl; ReqParams->Uk7[0]=0x00; ReqParams->Uk7[1]=0x00; ReqParams->Uk7[2]=0x00; ReqParams->Uk7[3]=0x00; ReqParams->Uk7[4]=0x00; ReqParams->Uk7[5]=0x00; ReqParams->Uk7[6]=0xFD; ReqParams->Len_1 =SwapWord(0x0A); ReqParams->NumOfBlocks=0x01; ReqParams->ByteZero =0x00; ReqParams->AsciiZero =0x30; ReqParams->BlkType=BlockType; ReqParams->AsciiBlk[0]=(BlockNum / 10000)+0x30; BlockNum=BlockNum % 10000; ReqParams->AsciiBlk[1]=(BlockNum / 1000)+0x30; BlockNum=BlockNum % 1000; ReqParams->AsciiBlk[2]=(BlockNum / 100)+0x30; BlockNum=BlockNum % 100; ReqParams->AsciiBlk[3]=(BlockNum / 10)+0x30; BlockNum=BlockNum % 10; ReqParams->AsciiBlk[4]=(BlockNum / 1)+0x30; ReqParams->SFun =SFun_Delete; ReqParams->Len_2=0x05; ReqParams->Cmd[0]='_'; ReqParams->Cmd[1]='D'; ReqParams->Cmd[2]='E'; ReqParams->Cmd[3]='L'; ReqParams->Cmd[4]='E'; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqControlBlockParams); Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if (SwapWord(Answer->Error)!=Code7NeedPassword) { if ((Answer->Error!=0) || (*ResParams!=pduControl)) Result=errCliDeleteRefused; } else Result=errCliNeedPassword; } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opReadSZL() { PS7Answer17 Answer; PReqFunReadSZLFirst ReqParamsFirst; PReqFunReadSZLNext ReqParamsNext; PS7ReqSZLData ReqDataFirst; PS7ReqSZLData ReqDataNext; PS7ResParams7 ResParams; PS7ResSZLDataFirst ResDataFirst; PS7ResSZLDataNext ResDataNext; PSZL_HEADER Header; PS7SZLList Target; pbyte PDataFirst; pbyte PDataNext; word ID, Index; int IsoSize, DataSize, DataSZL, Result; bool First, Done; bool NoRoom = false; uintptr_t Offset =0; byte Seq_in =0x00; ID=Job.ID; Index=Job.Index; opSize=0; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParamsFirst=PReqFunReadSZLFirst(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqParamsNext =PReqFunReadSZLNext(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqDataFirst =PS7ReqSZLData(pbyte(ReqParamsFirst)+sizeof(TReqFunReadSZLFirst)); ReqDataNext =PS7ReqSZLData(pbyte(ReqParamsNext)+sizeof(TReqFunReadSZLNext)); Answer =PS7Answer17(&PDU.Payload); ResParams =PS7ResParams7(pbyte(Answer)+ResHeaderSize17); ResDataFirst =PS7ResSZLDataFirst(pbyte(ResParams)+sizeof(TS7Params7)); ResDataNext =PS7ResSZLDataNext(pbyte(ResParams)+sizeof(TS7Params7)); PDataFirst =pbyte(ResDataFirst)+8; // skip header PDataNext =pbyte(ResDataNext)+4; // skip header Header =PSZL_HEADER(&opData); First=true; Done =false; do { //<------------------------------------------------------- read slices if (First) { //<-------------------------------------------------- prepare first DataSize=sizeof(TS7ReqSZLData); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunReadSZLFirst)); // 8 bytes params PDUH_out->DataLen=SwapWord(DataSize); // 8/4 bytes data // Fill Params ReqParamsFirst->Head[0]=0x00; ReqParamsFirst->Head[1]=0x01; ReqParamsFirst->Head[2]=0x12; ReqParamsFirst->Plen =0x04; ReqParamsFirst->Uk =0x11; ReqParamsFirst->Tg =grSZL; ReqParamsFirst->SubFun =SFun_ReadSZL; //0x03 ReqParamsFirst->Seq =Seq_in; // Fill Data ReqDataFirst->Ret =0xFF; ReqDataFirst->TS =TS_ResOctet; ReqDataFirst->DLen =SwapWord(0x0004); ReqDataFirst->ID =SwapWord(ID); ReqDataFirst->Index =SwapWord(Index); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunReadSZLFirst)+DataSize; //--------------------------------------------------> prepare first } else { //<-------------------------------------------------- prepare next DataSize=sizeof(TS7ReqSZLData)-4; // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunReadSZLNext)); // 8 bytes params PDUH_out->DataLen=SwapWord(DataSize);// 8/4 bytes data // Fill Params ReqParamsNext->Head[0]=0x00; ReqParamsNext->Head[1]=0x01; ReqParamsNext->Head[2]=0x12; ReqParamsNext->Plen =0x08; ReqParamsNext->Uk =0x12; ReqParamsNext->Tg =grSZL; ReqParamsNext->SubFun =SFun_ReadSZL; ReqParamsNext->Seq =Seq_in; ReqParamsNext->Rsvd =0x0000; ReqParamsNext->ErrNo =0x0000; // Fill Data ReqDataNext->Ret =0x0A; ReqDataNext->TS =0x00; ReqDataNext->DLen =0x0000; ReqDataNext->ID =0x0000; ReqDataNext->Index =0x0000; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunReadSZLNext)+DataSize; //--------------------------------------------------> prepare next } Result=isoExchangeBuffer(0,IsoSize); // Get Data if (Result==0) { if (First) { //<------------------------------------------ get data first if (ResParams->Err==0) { if (ResDataFirst->Ret==0xFF) // <-- 0xFF means Result OK { // Gets Amount of this slice DataSZL=SwapWord(ResDataFirst->DLen)-4;// Skips extra params (ID, Index ...) // Gets end of Sequence Flag Done=(ResParams->resvd & 0xFF00) == 0; // Low order byte = 0x00 => the sequence is done // Gets Unit's function sequence Seq_in=ResParams->Seq; Target=PS7SZLList(pbyte(&opData)+Offset); memcpy(Target, PDataFirst, DataSZL); Offset+=DataSZL; } else Result=CpuError(ResDataFirst->Ret); } else Result=CpuError(ResDataFirst->Ret); //------------------------------------------> get data first } else { //<------------------------------------------ get data next if (ResParams->Err==0) { if (ResDataNext->Ret==0xFF) // <-- 0xFF means Result OK { // Gets Amount of this slice DataSZL=SwapWord(ResDataNext->DLen); // Gets end of Sequence Flag Done=(ResParams->resvd & 0xFF00) == 0; // Low order byte = 0x00 => the sequence is done // Gets Unit's function sequence Seq_in=ResParams->Seq; Target=PS7SZLList(pbyte(&opData)+Offset); memcpy(Target, PDataNext, DataSZL); Offset+=DataSZL; } else Result=CpuError(ResDataNext->Ret); } else Result=CpuError(ResDataNext->Ret); //------------------------------------------> get data next } First=false; } //-------------------------------------------------------> read slices } while ((!Done) && (Result==0)); // Check errors and adjust header if (Result==0) { // Adjust big endian header Header->LENTHDR=SwapWord(Header->LENTHDR); Header->N_DR =SwapWord(Header->N_DR); opSize=int(Offset); if (Job.IParam==1) // if 1 data has to be copied into user buffer { // Check buffer size if (opSize>Job.Amount) { opSize=Job.Amount; NoRoom=true; } memcpy(Job.pData, &opData, opSize); *Job.pAmount=opSize; }; }; if ((Result==0)&& NoRoom) Result=errCliBufferTooSmall; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opReadSZLList() { PS7SZLList usrSZLList, opDataList; int ItemsCount, ItemsCount_in, c, Result; bool NoRoom = false; Job.ID =0x0000; Job.Index =0x0000; Job.IParam =0; ItemsCount_in=Job.Amount; // stores the room Job.Amount =sizeof(opData); // read into the internal buffer Result =opReadSZL(); if (Result==0) { opDataList=PS7SZLList(&opData); // Source usrSZLList=PS7SZLList(Job.pData); // Target ItemsCount=(opSize-sizeof(SZL_HEADER)) / 2; // Check input size if (ItemsCount>ItemsCount_in) { ItemsCount=ItemsCount_in; // Trim itemscount NoRoom=true; } for (c = 0; c < ItemsCount; c++) usrSZLList->List[c]=SwapWord(opDataList->List[c]); *Job.pAmount=ItemsCount; } else *Job.pAmount=0; if ((Result==0) && NoRoom) Result=errCliBufferTooSmall; return Result; } //--------------------------------------------------------------------------- byte TSnap7MicroClient::BCDtoByte(byte B) { return ((B >> 4) * 10) + (B & 0x0F); } //--------------------------------------------------------------------------- byte TSnap7MicroClient::WordToBCD(word Value) { return ((Value / 10) << 4) | (Value % 10); } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetDateTime() { PTimeStruct DateTime; PReqFunDateTime ReqParams; PReqDataGetDateTime ReqData; PS7ResParams7 ResParams; PResDataGetTime ResData; PS7ResHeader17 Answer; int IsoSize, Result; word AYear; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunDateTime(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataGetDateTime(pbyte(ReqParams)+sizeof(TReqFunDateTime)); Answer =PS7ResHeader17(&PDU.Payload); ResParams=PS7ResParams7(pbyte(Answer)+ResHeaderSize17); ResData =PResDataGetTime(pbyte(ResParams)+sizeof(TS7Params7)); DateTime =PTimeStruct(Job.pData); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunDateTime)); // 8 bytes params PDUH_out->DataLen=SwapWord(sizeof(TReqDataGetDateTime)); // 4 bytes data // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grClock; ReqParams->SubFun =SFun_ReadClock; ReqParams->Seq =0x00; // Fill Data *ReqData =0x0000000A; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunDateTime)+sizeof(TReqDataGetDateTime); Result=isoExchangeBuffer(0,IsoSize); // Get Data if (Result==0) { if (ResParams->Err==0) { if (ResData->RetVal==0xFF) // <-- 0xFF means Result OK { // Decode Plc Date and Time AYear=BCDtoByte(ResData->Time[0]); if (AYear<90) AYear=AYear+100; DateTime->tm_year=AYear; DateTime->tm_mon =BCDtoByte(ResData->Time[1])-1; DateTime->tm_mday=BCDtoByte(ResData->Time[2]); DateTime->tm_hour=BCDtoByte(ResData->Time[3]); DateTime->tm_min =BCDtoByte(ResData->Time[4]); DateTime->tm_sec =BCDtoByte(ResData->Time[5]); DateTime->tm_wday=(ResData->Time[7] & 0x0F)-1; } else Result=CpuError(ResData->RetVal); } else Result=CpuError(ResData->RetVal); } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opSetDateTime() { PTimeStruct DateTime; PReqFunDateTime ReqParams; PReqDataSetTime ReqData; PS7ResParams7 ResParams; PS7ResHeader17 Answer; word AYear; int IsoSize, Result; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunDateTime(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataSetTime(pbyte(ReqParams)+sizeof(TReqFunDateTime)); Answer =PS7ResHeader17(&PDU.Payload); ResParams=PS7ResParams7(pbyte(Answer)+ResHeaderSize17); DateTime =PTimeStruct(Job.pData); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunDateTime)); // 8 bytes params PDUH_out->DataLen=SwapWord(sizeof(TReqDataSetTime)); // 4 bytes data // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grClock; ReqParams->SubFun =SFun_SetClock; ReqParams->Seq =0x00; // EncodeSiemensDateTime; if (DateTime->tm_year<100) AYear=DateTime->tm_year; else AYear=DateTime->tm_year-100; ReqData->RetVal=0xFF; ReqData->TSize =TS_ResOctet; ReqData->Length=SwapWord(0x000A); ReqData->Rsvd =0x00; ReqData->HiYear=0x19; // *must* be 19 tough it's not the Hi part of the year... ReqData->Time[0]=WordToBCD(AYear); ReqData->Time[1]=WordToBCD(DateTime->tm_mon+1); ReqData->Time[2]=WordToBCD(DateTime->tm_mday); ReqData->Time[3]=WordToBCD(DateTime->tm_hour); ReqData->Time[4]=WordToBCD(DateTime->tm_min); ReqData->Time[5]=WordToBCD(DateTime->tm_sec); ReqData->Time[6]=0; ReqData->Time[7]=DateTime->tm_wday+1; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunDateTime)+sizeof(TReqDataSetTime); Result=isoExchangeBuffer(0,IsoSize); // Get Result if (Result==0) { if (ResParams->Err!=0) Result=CpuError(SwapWord(ResParams->Err)); }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetOrderCode() { PS7OrderCode OC; int Result; Job.ID =0x0011; Job.Index =0x0000; Job.IParam =0; Result =opReadSZL(); if (Result==0) { OC=PS7OrderCode(Job.pData); memset(OC,0,sizeof(TS7OrderCode)); memcpy(OC->Code,&opData[6],20); OC->V1=opData[opSize-3]; OC->V2=opData[opSize-2]; OC->V3=opData[opSize-1]; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetCpuInfo() { PS7CpuInfo Info; int Result; // Store Pointer Info=PS7CpuInfo(Job.pData); // Clear data in order to have the end of strings (\0) correctly setted memset(Info, 0, sizeof(TS7CpuInfo)); Job.ID =0x001C; Job.Index =0x0000; Job.IParam=0; Result =opReadSZL(); if (Result==0) { memcpy(Info->ModuleTypeName,&opData[176],32); memcpy(Info->SerialNumber,&opData[142],24); memcpy(Info->ASName,&opData[6],24); memcpy(Info->Copyright,&opData[108],26); memcpy(Info->ModuleName,&opData[40],24); } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetCpInfo() { PS7CpInfo Info; int Result; // Store Pointer Info=PS7CpInfo(Job.pData); memset(Info,0,sizeof(TS7CpInfo)); Job.ID =0x0131; Job.Index =0x0001; Job.IParam=0; Result =opReadSZL(); if (Result==0) { Info->MaxPduLengt=opData[6]*256+opData[7]; Info->MaxConnections=opData[8]*256+opData[9]; Info->MaxMpiRate=DWordAt(&opData[10]); Info->MaxBusRate=DWordAt(&opData[14]); }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetPlcStatus() { int *Status; int Result; Status =(int*)Job.pData; Job.ID =0x0424; Job.Index =0x0000; Job.IParam =0; Result =opReadSZL(); if (Result==0) { switch (opData[7]) { case S7CpuStatusUnknown : case S7CpuStatusRun : case S7CpuStatusStop : *Status=opData[7]; break; default : // Since RUN status is always $08 for all CPUs and CPs, STOP status // sometime can be coded as $03 (especially for old cpu...) *Status=S7CpuStatusStop; } } else *Status=0; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opPlcStop() { PReqFunPlcStop ReqParams; PResFunCtrl ResParams; PS7ResHeader23 Answer; int IsoSize, Result; char p_program[] = {'P','_','P','R','O','G','R','A','M'}; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunPlcStop(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunCtrl(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunPlcStop)); PDUH_out->DataLen=0x0000; // No Data // Fill Params ReqParams->Fun=pduStop; memset(ReqParams->Uk_5,0,5); ReqParams->Len_2=0x09; memcpy(ReqParams->Cmd,&p_program,9); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunPlcStop); Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if (Answer->Error!=0) { if (ResParams->ResFun!=pduStop) Result=errCliCannotStopPLC; else if (ResParams->para ==0x07) Result=errCliAlreadyStop; else Result=errCliCannotStopPLC; }; }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opPlcHotStart() { PReqFunPlcHotStart ReqParams; PResFunCtrl ResParams; PS7ResHeader23 Answer; int IsoSize, Result; char p_program[] = {'P','_','P','R','O','G','R','A','M'}; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunPlcHotStart(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunCtrl(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunPlcHotStart)); // 16 bytes params PDUH_out->DataLen=0x0000; // No Data // Fill Params ReqParams->Fun=pduStart; ReqParams->Uk_7[0]=0x00; ReqParams->Uk_7[1]=0x00; ReqParams->Uk_7[2]=0x00; ReqParams->Uk_7[3]=0x00; ReqParams->Uk_7[4]=0x00; ReqParams->Uk_7[5]=0x00; ReqParams->Uk_7[6]=0xFD; ReqParams->Len_1=0x0000; ReqParams->Len_2=0x09; memcpy(ReqParams->Cmd,&p_program,9); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunPlcHotStart); Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if ((Answer->Error!=0)) { if ((ResParams->ResFun!=pduStart)) Result=errCliCannotStartPLC; else { if (ResParams->para==0x03) Result=errCliAlreadyRun; else if (ResParams->para==0x02) Result=errCliCannotStartPLC; else Result=errCliCannotStartPLC; } } }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opPlcColdStart() { PReqFunPlcColdStart ReqParams; PResFunCtrl ResParams; PS7ResHeader23 Answer; int IsoSize, Result; char p_program[] = {'P','_','P','R','O','G','R','A','M'}; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunPlcColdStart(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunCtrl(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunPlcColdStart)); // 22 bytes params PDUH_out->DataLen=0x0000; // No Data // Fill Params ReqParams->Fun=pduStart; ReqParams->Uk_7[0]=0x00; ReqParams->Uk_7[1]=0x00; ReqParams->Uk_7[2]=0x00; ReqParams->Uk_7[3]=0x00; ReqParams->Uk_7[4]=0x00; ReqParams->Uk_7[5]=0x00; ReqParams->Uk_7[6]=0xFD; ReqParams->Len_1=SwapWord(0x0002); ReqParams->SFun =SwapWord(0x4320); // Cold start ReqParams->Len_2=0x09; memcpy(ReqParams->Cmd,&p_program,9); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunPlcColdStart); Result=isoExchangeBuffer(0,IsoSize); if (Result==0) { if ((Answer->Error!=0)) { if ((ResParams->ResFun!=pduStart)) Result=errCliCannotStartPLC; else { if (ResParams->para==0x03) Result=errCliAlreadyRun; else if (ResParams->para==0x02) Result=errCliCannotStartPLC; else Result=errCliCannotStartPLC; } } }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opCopyRamToRom() { PReqFunCopyRamToRom ReqParams; PResFunCtrl ResParams; PS7ResHeader23 Answer; int IsoSize, CurTimeout, Result; char _modu[] = {'_','M','O','D','U'}; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunCopyRamToRom(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunCtrl(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunCopyRamToRom)); PDUH_out->DataLen=0x0000; // No Data // Fill Params ReqParams->Fun=pduControl; ReqParams->Uk_7[0]=0x00; ReqParams->Uk_7[1]=0x00; ReqParams->Uk_7[2]=0x00; ReqParams->Uk_7[3]=0x00; ReqParams->Uk_7[4]=0x00; ReqParams->Uk_7[5]=0x00; ReqParams->Uk_7[6]=0xFD; ReqParams->Len_1=SwapWord(0x0002); ReqParams->SFun =SwapWord(0x4550); ReqParams->Len_2=0x05; memcpy(ReqParams->Cmd,&_modu,5); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunCopyRamToRom); // Changes the timeout CurTimeout=RecvTimeout; RecvTimeout=Job.IParam; Result=isoExchangeBuffer(0,IsoSize); // Restores the timeout RecvTimeout=CurTimeout; if (Result==0) { if ((Answer->Error!=0) || (ResParams->ResFun!=pduControl)) Result=errCliCannotCopyRamToRom; } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opCompress() { PReqFunCompress ReqParams; PResFunCtrl ResParams; PS7ResHeader23 Answer; int IsoSize, CurTimeout, Result; char _garb[] = {'_','G','A','R','B'}; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunCompress(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResFunCtrl(pbyte(Answer)+ResHeaderSize23); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_request; // 0x01 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen=SwapWord(sizeof(TReqFunCompress)); PDUH_out->DataLen=0x0000; // No Data // Fill Params ReqParams->Fun=pduControl; ReqParams->Uk_7[0]=0x00; ReqParams->Uk_7[1]=0x00; ReqParams->Uk_7[2]=0x00; ReqParams->Uk_7[3]=0x00; ReqParams->Uk_7[4]=0x00; ReqParams->Uk_7[5]=0x00; ReqParams->Uk_7[6]=0xFD; ReqParams->Len_1=0x0000; ReqParams->Len_2=0x05; memcpy(ReqParams->Cmd,&_garb,5); IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunCompress); // Changes the timeout CurTimeout=RecvTimeout; RecvTimeout=Job.IParam; Result=isoExchangeBuffer(0,IsoSize); // Restores the timeout RecvTimeout=CurTimeout; if (Result==0) { if (((Answer->Error!=0) || (ResParams->ResFun!=pduControl))) Result=errCliCannotCompress; } return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opGetProtection() { PS7Protection Info, usrInfo; int Result; // Store Pointer usrInfo=PS7Protection(Job.pData); memset(usrInfo, 0, sizeof(TS7Protection)); Job.ID =0x0232; Job.Index =0x0004; Job.IParam=0; // No copy in Usr Data pointed by Job.pData Result =opReadSZL(); if (Result==0) { Info=PS7Protection(pbyte(&opData)+6); usrInfo->sch_schal=SwapWord(Info->sch_schal); usrInfo->sch_par =SwapWord(Info->sch_par); usrInfo->sch_rel =SwapWord(Info->sch_rel); usrInfo->bart_sch =SwapWord(Info->bart_sch); usrInfo->anl_sch =SwapWord(Info->anl_sch); } return Result; } //****************************************************************************** // NOTE // PASSWORD HACKING IS VERY FAR FROM THE AIM OF THIS PROJECT // NEXT FUNCTION ONLY ENCODES THE ASCII PASSWORD TO BE DOWNLOADED IN THE PLC. // // MOREOVER **YOU NEED TO KNOW** THE CORRECT PASSWORD TO MEET THE CPU // SECURITY LEVEL //****************************************************************************** int TSnap7MicroClient::opSetPassword() { PReqFunSecurity ReqParams; PReqDataSecurity ReqData; PResParamsSecurity ResParams; PS7ResHeader23 Answer; int c, IsoSize, Result; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunSecurity(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataSecurity(pbyte(ReqParams)+sizeof(TReqFunSecurity)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResParamsSecurity(pbyte(Answer)+ResHeaderSize17); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen =SwapWord(sizeof(TReqFunSecurity)); PDUH_out->DataLen=SwapWord(sizeof(TReqDataSecurity)); // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grSecurity; ReqParams->SubFun =SFun_EnterPwd; ReqParams->Seq =0x00; // Fill Data ReqData->Ret =0xFF; ReqData->TS =TS_ResOctet; ReqData->DLen =SwapWord(0x0008); // 8 bytes data : password // Encode the password ReqData->Pwd[0]=opData[0] ^ 0x55; ReqData->Pwd[1]=opData[1] ^ 0x55; for (c = 2; c < 8; c++){ ReqData->Pwd[c]=opData[c] ^ 0x55 ^ ReqData->Pwd[c-2]; }; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunSecurity)+sizeof(TReqDataSecurity); Result=isoExchangeBuffer(0,IsoSize); // Get Return if (Result==0) { if (ResParams->Err!=0) Result=CpuError(SwapWord(ResParams->Err)); }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::opClearPassword() { PReqFunSecurity ReqParams; PReqDataSecurity ReqData; PResParamsSecurity ResParams; PS7ResHeader23 Answer; int IsoSize, Result; // Setup pointers (note : PDUH_out and PDU.Payload are the same pointer) ReqParams=PReqFunSecurity(pbyte(PDUH_out)+sizeof(TS7ReqHeader)); ReqData =PReqDataSecurity(pbyte(ReqParams)+sizeof(TReqFunSecurity)); Answer =PS7ResHeader23(&PDU.Payload); ResParams=PResParamsSecurity(pbyte(Answer)+ResHeaderSize17); // Fill Header PDUH_out->P=0x32; // Always 0x32 PDUH_out->PDUType=PduType_userdata; // 0x07 PDUH_out->AB_EX=0x0000; // Always 0x0000 PDUH_out->Sequence=GetNextWord(); // AutoInc PDUH_out->ParLen =SwapWord(sizeof(TReqFunSecurity)); PDUH_out->DataLen=SwapWord(0x0004); // We need only 4 bytes // Fill params (mostly constants) ReqParams->Head[0]=0x00; ReqParams->Head[1]=0x01; ReqParams->Head[2]=0x12; ReqParams->Plen =0x04; ReqParams->Uk =0x11; ReqParams->Tg =grSecurity; ReqParams->SubFun =SFun_CancelPwd; ReqParams->Seq =0x00; // Fill Data ReqData->Ret =0x0A; ReqData->TS =0x00; ReqData->DLen =0x0000; IsoSize=sizeof(TS7ReqHeader)+sizeof(TReqFunSecurity)+4; Result=isoExchangeBuffer(0,IsoSize); // Get Return if (Result==0) { if (ResParams->Err!=0) Result=CpuError(SwapWord(ResParams->Err)); }; return Result; } //--------------------------------------------------------------------------- int TSnap7MicroClient::CpuError(int Error) { switch(Error) { case 0 : return 0; case Code7AddressOutOfRange : return errCliAddressOutOfRange; case Code7InvalidTransportSize : return errCliInvalidTransportSize; case Code7WriteDataSizeMismatch : return errCliWriteDataSizeMismatch; case Code7ResItemNotAvailable : case Code7ResItemNotAvailable1 : return errCliItemNotAvailable; case Code7DataOverPDU : return errCliSizeOverPDU; case Code7InvalidValue : return errCliInvalidValue; case Code7FunNotAvailable : return errCliFunNotAvailable; case Code7NeedPassword : return errCliNeedPassword; case Code7InvalidPassword : return errCliInvalidPassword; case Code7NoPasswordToSet : case Code7NoPasswordToClear : return errCliNoPasswordToSetOrClear; default: return errCliFunctionRefused; }; } //--------------------------------------------------------------------------- int TSnap7MicroClient::DataSizeByte(int WordLength) { switch (WordLength){ case S7WLBit : return 1; // S7 sends 1 byte per bit case S7WLByte : return 1; case S7WLChar : return 1; case S7WLWord : return 2; case S7WLDWord : return 4; case S7WLInt : return 2; case S7WLDInt : return 4; case S7WLReal : return 4; case S7WLCounter : return 2; case S7WLTimer : return 2; default : return 0; } } //--------------------------------------------------------------------------- longword TSnap7MicroClient::DWordAt(void * P) { longword DW; DW=*(longword*)P; return SwapDWord(DW); } //--------------------------------------------------------------------------- int TSnap7MicroClient::CheckBlock(int BlockType, int BlockNum, void * pBlock, int Size) { PS7CompactBlockInfo Info = PS7CompactBlockInfo(pBlock); if (BlockType>=0) // if (BlockType<0 the test is skipped { if ((BlockType!=Block_OB)&&(BlockType!=Block_DB)&&(BlockType!=Block_FB)&& (BlockType!=Block_FC)&&(BlockType!=Block_SDB)&&(BlockType!=Block_SFC)&& (BlockType!=Block_SFB)) return errCliInvalidBlockType; } if (BlockNum>=0) // if (BlockNum<0 the test is skipped { if (BlockNum>0xFFFF) return errCliInvalidBlockNumber; }; if (SwapDWord(Info->LenLoadMem)!=longword(Size)) return errCliInvalidBlockSize; // Check the presence of the footer if (SwapWord(Info->MC7Len)+sizeof(TS7CompactBlockInfo)>=u_int(Size)) return errCliInvalidBlockSize; return 0; } //--------------------------------------------------------------------------- int TSnap7MicroClient::SubBlockToBlock(int SBB) { switch (SBB) { case SubBlk_OB : return Block_OB; case SubBlk_DB : return Block_DB; case SubBlk_SDB : return Block_SDB; case SubBlk_FC : return Block_FC; case SubBlk_SFC : return Block_SFC; case SubBlk_FB : return Block_FB; case SubBlk_SFB : return Block_SFB; default : return 0; }; } //--------------------------------------------------------------------------- int TSnap7MicroClient::PerformOperation() { ClrError(); int Operation=Job.Op; switch(Operation) { case s7opNone: Job.Result=errCliInvalidParams; break; case s7opReadArea: Job.Result=opReadArea(); break; case s7opWriteArea: Job.Result=opWriteArea(); break; case s7opReadMultiVars: Job.Result=opReadMultiVars(); break; case s7opWriteMultiVars: Job.Result=opWriteMultiVars(); break; case s7opDBGet: Job.Result=opDBGet(); break; case s7opDBFill: Job.Result=opDBFill(); break; case s7opUpload: Job.Result=opUpload(); break; case s7opDownload: Job.Result=opDownload(); break; case s7opDelete: Job.Result=opDelete(); break; case s7opListBlocks: Job.Result=opListBlocks(); break; case s7opAgBlockInfo: Job.Result=opAgBlockInfo(); break; case s7opListBlocksOfType: Job.Result=opListBlocksOfType(); break; case s7opReadSzlList: Job.Result=opReadSZLList(); break; case s7opReadSZL: Job.Result=opReadSZL(); break; case s7opGetDateTime: Job.Result=opGetDateTime(); break; case s7opSetDateTime: Job.Result=opSetDateTime(); break; case s7opGetOrderCode: Job.Result=opGetOrderCode(); break; case s7opGetCpuInfo: Job.Result=opGetCpuInfo(); break; case s7opGetCpInfo: Job.Result=opGetCpInfo(); break; case s7opGetPlcStatus: Job.Result=opGetPlcStatus(); break; case s7opPlcHotStart: Job.Result=opPlcHotStart(); break; case s7opPlcColdStart: Job.Result=opPlcColdStart(); break; case s7opCopyRamToRom: Job.Result=opCopyRamToRom(); break; case s7opCompress: Job.Result=opCompress(); break; case s7opPlcStop: Job.Result=opPlcStop(); break; case s7opGetProtection: Job.Result=opGetProtection(); break; case s7opSetPassword: Job.Result=opSetPassword(); break; case s7opClearPassword: Job.Result=opClearPassword(); break; } Job.Time =SysGetTick()-JobStart; Job.Pending=false; return SetError(Job.Result); } //--------------------------------------------------------------------------- int TSnap7MicroClient::Disconnect() { JobStart=SysGetTick(); PeerDisconnect(); Job.Time=SysGetTick()-JobStart; Job.Pending=false; return 0; } //--------------------------------------------------------------------------- int TSnap7MicroClient::Reset(bool DoReconnect) { Job.Pending=false; if (DoReconnect) { Disconnect(); return Connect(); } else return 0; } //--------------------------------------------------------------------------- int TSnap7MicroClient::Connect() { int Result; JobStart=SysGetTick(); Result =PeerConnect(); Job.Time=SysGetTick()-JobStart; return Result; } //--------------------------------------------------------------------------- void TSnap7MicroClient::SetConnectionType(word ConnType) { ConnectionType=ConnType; } //--------------------------------------------------------------------------- void TSnap7MicroClient::SetConnectionParams(const char *RemAddress, word LocalTSAP, word RemoteTSAP) { SrcTSap = LocalTSAP; DstTSap = RemoteTSAP; strncpy(RemoteAddress, RemAddress, 16); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ConnectTo(const char *RemAddress, int Rack, int Slot) { word RemoteTSAP = (ConnectionType<<8)+(Rack*0x20)+Slot; SetConnectionParams(RemAddress, SrcTSap, RemoteTSAP); return Connect(); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetParam(int ParamNumber, void *pValue) { switch (ParamNumber) { case p_u16_RemotePort: *Puint16_t(pValue)=RemotePort; break; case p_i32_PingTimeout: *Pint32_t(pValue)=PingTimeout; break; case p_i32_SendTimeout: *Pint32_t(pValue)=SendTimeout; break; case p_i32_RecvTimeout: *Pint32_t(pValue)=RecvTimeout; break; case p_i32_WorkInterval: *Pint32_t(pValue)=WorkInterval; break; case p_u16_SrcRef: *Puint16_t(pValue)=SrcRef; break; case p_u16_DstRef: *Puint16_t(pValue)=DstRef; break; case p_u16_SrcTSap: *Puint16_t(pValue)=SrcTSap; break; case p_i32_PDURequest: *Pint32_t(pValue)=PDURequest; break; default: return errCliInvalidParamNumber; } return 0; } //--------------------------------------------------------------------------- int TSnap7MicroClient::SetParam(int ParamNumber, void *pValue) { switch (ParamNumber) { case p_u16_RemotePort: if (!Connected) RemotePort=*Puint16_t(pValue); else return errCliCannotChangeParam; break; case p_i32_PingTimeout: PingTimeout=*Pint32_t(pValue); break; case p_i32_SendTimeout: SendTimeout=*Pint32_t(pValue); break; case p_i32_RecvTimeout: RecvTimeout=*Pint32_t(pValue); break; case p_i32_WorkInterval: WorkInterval=*Pint32_t(pValue); break; case p_u16_SrcRef: SrcRef=*Puint16_t(pValue); break; case p_u16_DstRef: DstRef=*Puint16_t(pValue); break; case p_u16_SrcTSap: SrcTSap=*Puint16_t(pValue); break; case p_i32_PDURequest: PDURequest=*Pint32_t(pValue); break; default: return errCliInvalidParamNumber; } return 0; } //--------------------------------------------------------------------------- // Data I/O functions int TSnap7MicroClient::ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void * pUsrData) { if (!Job.Pending) { Job.Pending = true; Job.Op = s7opReadArea; Job.Area = Area; Job.Number = DBNumber; Job.Start = Start; Job.Amount = Amount; Job.WordLen = WordLen; Job.pData = pUsrData; JobStart = SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void * pUsrData) { if (!Job.Pending) { Job.Pending = true; Job.Op = s7opWriteArea; Job.Area = Area; Job.Number = DBNumber; Job.Start = Start; Job.Amount = Amount; Job.WordLen = WordLen; Job.pData = pUsrData; JobStart = SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ReadMultiVars(PS7DataItem Item, int ItemsCount) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opReadMultiVars; Job.Amount =ItemsCount; Job.pData =Item; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::WriteMultiVars(PS7DataItem Item, int ItemsCount) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opWriteMultiVars; Job.Amount =ItemsCount; Job.pData =Item; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::DBRead(int DBNumber, int Start, int Size, void * pUsrData) { return ReadArea(S7AreaDB, DBNumber, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::DBWrite(int DBNumber, int Start, int Size, void * pUsrData) { return WriteArea(S7AreaDB, DBNumber, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::MBRead(int Start, int Size, void * pUsrData) { return ReadArea(S7AreaMK, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::MBWrite(int Start, int Size, void * pUsrData) { return WriteArea(S7AreaMK, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::EBRead(int Start, int Size, void * pUsrData) { return ReadArea(S7AreaPE, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::EBWrite(int Start, int Size, void * pUsrData) { return WriteArea(S7AreaPE, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ABRead(int Start, int Size, void * pUsrData) { return ReadArea(S7AreaPA, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ABWrite(int Start, int Size, void * pUsrData) { return WriteArea(S7AreaPA, 0, Start, Size, S7WLByte, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::TMRead(int Start, int Amount, void * pUsrData) { return ReadArea(S7AreaTM, 0, Start, Amount, S7WLTimer, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::TMWrite(int Start, int Amount, void * pUsrData) { return WriteArea(S7AreaTM, 0, Start, Amount, S7WLTimer, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::CTRead(int Start, int Amount, void * pUsrData) { return ReadArea(S7AreaCT, 0, Start, Amount, S7WLCounter, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::CTWrite(int Start, int Amount, void * pUsrData) { return WriteArea(S7AreaCT, 0, Start, Amount, S7WLCounter, pUsrData); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ListBlocks(PS7BlocksList pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opListBlocks; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetAgBlockInfo(int BlockType, int BlockNum, PS7BlockInfo pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opAgBlockInfo; Job.Area =BlockType; Job.Number =BlockNum; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetPgBlockInfo(void * pBlock, PS7BlockInfo pUsrData, int Size) { PS7CompactBlockInfo Info; PS7BlockFooter Footer; int Result=CheckBlock(-1,-1,pBlock,Size); if (Result==0) { Info=PS7CompactBlockInfo(pBlock); pUsrData->BlkType =Info->SubBlkType; pUsrData->BlkNumber=SwapWord(Info->BlkNum); pUsrData->BlkLang =Info->BlkLang; pUsrData->BlkFlags =Info->BlkFlags; pUsrData->MC7Size =SwapWord(Info->MC7Len); pUsrData->LoadSize =SwapDWord(Info->LenLoadMem); pUsrData->LocalData=SwapDWord(Info->LocDataLen); pUsrData->SBBLength=SwapDWord(Info->SbbLen); pUsrData->CheckSum =0; // this info is not available pUsrData->Version =0; // this info is not available FillTime(SwapWord(Info->CodeTime_dy),pUsrData->CodeDate); FillTime(SwapWord(Info->IntfTime_dy),pUsrData->IntfDate); Footer=PS7BlockFooter(pbyte(Info)+pUsrData->LoadSize-sizeof(TS7BlockFooter)); memcpy(pUsrData->Author,Footer->Author,8); memcpy(pUsrData->Family,Footer->Family,8); memcpy(pUsrData->Header,Footer->Header,8); }; return SetError(Result); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ListBlocksOfType(int BlockType, TS7BlocksOfType *pUsrData, int &ItemsCount) { if (!Job.Pending) { if (ItemsCount<1) return SetError(errCliInvalidBlockSize); Job.Pending =true; Job.Op =s7opListBlocksOfType; Job.Area =BlockType; Job.pData =pUsrData; Job.pAmount =&ItemsCount; Job.Amount =ItemsCount; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::Upload(int BlockType, int BlockNum, void * pUsrData, int & Size) { if (!Job.Pending) { if (Size<=0) return SetError(errCliInvalidBlockSize); Job.Pending =true; Job.Op =s7opUpload; Job.Area =BlockType; Job.pData =pUsrData; Job.pAmount =&Size; Job.Amount =Size; Job.Number =BlockNum; Job.IParam =0; // not full upload, only data JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::FullUpload(int BlockType, int BlockNum, void * pUsrData, int & Size) { if (!Job.Pending) { if (Size<=0) return SetError(errCliInvalidBlockSize); Job.Pending =true; Job.Op =s7opUpload; Job.Area =BlockType; Job.pData =pUsrData; Job.pAmount =&Size; Job.Amount =Size; Job.Number =BlockNum; Job.IParam =1; // header + data + footer JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::Download(int BlockNum, void * pUsrData, int Size) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opDownload; memcpy(&opData, pUsrData, Size); Job.Number =BlockNum; Job.Amount =Size; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::Delete(int BlockType, int BlockNum) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opDelete; Job.Area =BlockType; Job.Number =BlockNum; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::DBGet(int DBNumber, void * pUsrData, int & Size) { if (!Job.Pending) { if (Size<=0) return SetError(errCliInvalidBlockSize); Job.Pending =true; Job.Op =s7opDBGet; Job.Number =DBNumber; Job.pData =pUsrData; Job.pAmount =&Size; Job.Amount =Size; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::DBFill(int DBNumber, int FillChar) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opDBFill; Job.Number =DBNumber; Job.IParam =FillChar; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetPlcDateTime(tm &DateTime) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetDateTime; Job.pData =&DateTime; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::SetPlcDateTime(tm * DateTime) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opSetDateTime; Job.pData =DateTime; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::SetPlcSystemDateTime() { time_t Now; time(&Now); struct tm * DateTime = localtime (&Now); return SetPlcDateTime(DateTime); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetOrderCode(PS7OrderCode pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetOrderCode; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetCpuInfo(PS7CpuInfo pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetCpuInfo; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetCpInfo(PS7CpInfo pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetCpInfo; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ReadSZL(int ID, int Index, PS7SZL pUsrData, int &Size) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opReadSZL; Job.ID =ID; Job.Index =Index; Job.pData =pUsrData; Job.pAmount =&Size; Job.Amount =Size; Job.IParam =1; // Data has to be copied into user buffer JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ReadSZLList(PS7SZLList pUsrData, int &ItemsCount) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opReadSzlList; Job.pData =pUsrData; Job.pAmount =&ItemsCount; Job.Amount =ItemsCount; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::PlcHotStart() { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opPlcHotStart; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::PlcColdStart() { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opPlcColdStart; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::PlcStop() { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opPlcStop; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::CopyRamToRom(int Timeout) { if (!Job.Pending) { if (Timeout>0) { Job.Pending =true; Job.Op =s7opCopyRamToRom; Job.IParam =Timeout; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliInvalidParams); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::Compress(int Timeout) { if (!Job.Pending) { if (Timeout>0) { Job.Pending =true; Job.Op =s7opCompress; Job.IParam =Timeout; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliInvalidParams); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetPlcStatus(int & Status) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetPlcStatus; Job.pData =&Status; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::GetProtection(PS7Protection pUsrData) { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opGetProtection; Job.pData =pUsrData; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::SetSessionPassword(char *Password) { if (!Job.Pending) { size_t L = strlen(Password); // checks the len if ((L<1) || (L>8)) return SetError(errCliInvalidParams); Job.Pending =true; // prepares an 8 char string filled with spaces memset(&opData,0x20,8); // copies strncpy((char*)&opData,Password,L); Job.Op =s7opSetPassword; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //--------------------------------------------------------------------------- int TSnap7MicroClient::ClearSessionPassword() { if (!Job.Pending) { Job.Pending =true; Job.Op =s7opClearPassword; JobStart =SysGetTick(); return PerformOperation(); } else return SetError(errCliJobPending); } //---------------------------------------------------------------------------
35.58456
146
0.535467
xeniumlee
cadde650de6efe7cfac79fe9334046d031d13d44
20,241
cpp
C++
XPowerControl/TokenRetriever.cpp
snowpoke/XPowerControl
a5e4493cde4bdc06df30dba69a9460247074fdcd
[ "MIT" ]
4
2021-11-11T17:03:20.000Z
2022-01-14T18:13:41.000Z
XPowerControl/TokenRetriever.cpp
snowpoke/XPowerControl
a5e4493cde4bdc06df30dba69a9460247074fdcd
[ "MIT" ]
1
2022-01-14T00:39:49.000Z
2022-01-14T00:39:49.000Z
XPowerControl/TokenRetriever.cpp
snowpoke/XPowerControl
a5e4493cde4bdc06df30dba69a9460247074fdcd
[ "MIT" ]
null
null
null
#include "TokenRetriever.h" #include "stdafx.h" #include "RetrieveTokenDlg.h" #include "token_retrieve.h" #include "nlohmann/json.hpp" #include "wstring_transform.h" #include "FirstSetup.h" #include "ActionRequiredDlg.h" #include "logging.h" #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <fstream> #include <curl/curl.h> #include <aclapi.h> #include <tchar.h> #include <pathcch.h> #pragma comment(lib, "Pathcch.lib") using namespace std; SECURITY_ATTRIBUTES give_all_rights() { DWORD dwRes, dwDisposition; PSID pEveryoneSID = NULL, pAdminSID = NULL; PACL pACL = NULL; PSECURITY_DESCRIPTOR pSD = NULL; EXPLICIT_ACCESS ea[2]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES sa; LONG lRes; HKEY hkSub = NULL; // Create a well-known SID for the Everyone group. if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID)) { _tprintf(_T("AllocateAndInitializeSid Error %u\n"), GetLastError()); goto Cleanup; } // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow Everyone read access to the key. ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = MAXIMUM_ALLOWED; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR)pEveryoneSID; // Create a SID for the BUILTIN\Administrators group. if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSID)) { _tprintf(_T("AllocateAndInitializeSid Error %u\n"), GetLastError()); goto Cleanup; } // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow the Administrators group full access to // the key. ea[1].grfAccessPermissions = MAXIMUM_ALLOWED; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP; ea[1].Trustee.ptstrName = (LPTSTR)pAdminSID; // Create a new ACL that contains the new ACEs. dwRes = SetEntriesInAcl(2, ea, NULL, &pACL); if (ERROR_SUCCESS != dwRes) { _tprintf(_T("SetEntriesInAcl Error %u\n"), GetLastError()); goto Cleanup; } // Initialize a security descriptor. pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (NULL == pSD) { _tprintf(_T("LocalAlloc Error %u\n"), GetLastError()); goto Cleanup; } if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { _tprintf(_T("InitializeSecurityDescriptor Error %u\n"), GetLastError()); goto Cleanup; } // Add the ACL to the security descriptor. if (!SetSecurityDescriptorDacl(pSD, TRUE, // bDaclPresent flag pACL, FALSE)) // not a default DACL { _tprintf(_T("SetSecurityDescriptorDacl Error %u\n"), GetLastError()); goto Cleanup; } // Initialize a security attributes structure. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = FALSE; Cleanup: if (pEveryoneSID) FreeSid(pEveryoneSID); if (pAdminSID) FreeSid(pAdminSID); if (pACL) LocalFree(pACL); if (pSD) LocalFree(pSD); if (hkSub) RegCloseKey(hkSub); return sa; } TokenRetriever::TokenRetriever(std::optional<CWnd*> status_element_t, std::optional<CButton*> ok_button_t, std::wstring mitm_exec_t, std::wstring emu_command_t) : status_element(status_element_t), ok_button(ok_button_t), mitm_exec(mitm_exec_t), emu_command(emu_command_t) { _logger = logging::get_logger(DEFAULT_LOG); } TokenRetriever::TokenRetriever() { TokenRetriever({}, {}, L"", L""); } HANDLE TokenRetriever::run_command(wstring command_t, LPCWSTR current_directory_t /* = NULL */, DWORD creation_flags_t /* = 0 */) { logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG); _logger->info("Running command: \"{}\"", transform::ws2s(command_t)); // we create an empty job object that will contain the process HANDLE job_handle = CreateJobObject(NULL, NULL); // we set up the job object so that closing the job causes all child processes to be terminated JOBOBJECT_BASIC_LIMIT_INFORMATION kill_flag_info; kill_flag_info.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info; job_info.BasicLimitInformation = kill_flag_info; SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info)); // we start the process STARTUPINFO si; PROCESS_INFORMATION pi; //SECURITY_ATTRIBUTES sa = give_all_rights(); // transfer all inheritance rights to child processes ZeroMemory(&si, sizeof(si)); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); auto create_success = CreateProcess(NULL, // lpApplicationName &command_t[0], // lpCommandLine NULL, // lpProcessAttributes NULL, // lpThreadAttributes TRUE, // bInheritHandles creation_flags_t, // dwCreationFlags NULL, // lpEnvironment current_directory_t, // lpCurrentDirectory &si, // lpStartupInfo &pi); // lpProcessInformation auto last_error_code = GetLastError(); _logger->info("CreateProcess returned {}, GetLastError returned {}", to_string(create_success), to_string(last_error_code)); // we associate the process with the job we created AssignProcessToJobObject(job_handle, pi.hProcess); return job_handle; // save handle to this object } void TokenRetriever::mitm_start() { DeleteFile(L"token.txt"); // delete files that contain results from previous mitmdump processes DeleteFile(L"authorization.txt"); DeleteFile(L"registration_token.txt"); DeleteFile(L"iksm_cookie.txt"); // get full path for mitm_script.py wchar_t buffer[MAX_PATH]; GetModuleFileName(NULL, buffer, MAX_PATH); // saves path of current executable in buffer PathCchRemoveFileSpec(buffer, MAX_PATH); // remove filename from path wstring mitm_script_location = wstring(buffer) + L"\\mitm_script.py"; mitm_handle = run_command(mitm_exec + L" -s \"" + mitm_script_location + L"\""); } void TokenRetriever::emu_start() { emu_handle = run_command(emu_command); } int TokenRetriever::writer(char* data, size_t size, size_t nmemb, std::string* writerData) { if (writerData == NULL) return 0; writerData->append(data, size * nmemb); return static_cast<int>(size * nmemb); } // trim from start (in place) static inline void ltrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // we sometimes get multiple json datasets in one response, we remove all but the first one string TokenRetriever::remove_multi_response(string buffer_t) { ltrim(buffer_t); // we trim from from the left, just to make sure this algorithm doesn't fail because of a space at the start int brackets = 0; string out_string = ""; for (char& c : buffer_t) { out_string += c; if (c == '{') brackets++; else if (c == '}') brackets--; if (brackets == 0) // since the very first character is {, this should only be 0 after the section has been closed break; } return out_string; } wstring TokenRetriever::access_token_to_iksm(string access_token_t) { CURL* curl1; CURL* curl2; CURLcode res; wstring ret = L""; if(status_element) (*status_element)->SetWindowTextW(L"Found authorization key! Retrieving token... [Auth Key Attempt #1]"); progress_percent = 70; // we obtain the device registration token // wait until registration token file is created while (!boost::filesystem::exists("registration_token.txt")) { } string registration_token = ""; int attempt_num = 0; try { string file_text = ""; do { attempt_num++; if (status_element) (*status_element)->SetWindowTextW((L"Found authorization key! Retrieving token... [Auth Key Attempt #" + to_wstring(attempt_num) + L"1]").c_str()); _logger->info("Found authorization key! Retrieving token... [Auth Key Attempt #{}]", to_string(attempt_num)); ifstream file; file.open("registration_token.txt"); std::string file_text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); Sleep(50); } while (file_text.length() == 0 && attempt_num <= 3); _logger->info("File 'registration_token.txt' has been found. Content of the file:\n{}", file_text); file_text = remove_multi_response(file_text); // we sometimes get two datasets as a response, we remove all but the first here nlohmann::json j = nlohmann::json::parse(file_text); registration_token = j["parameter"]["registrationToken"].get<string>(); } catch (const exception & e) { AfxMessageBox((L"Failed retrieving the registration token. Please try again or retrieve the token manually. " + transform::s2ws(e.what())).c_str()); _logger->error("Failed retrieving the registration token. e.what() returned: {}", e.what()); AfxThrowUserException(); } if (status_element) (*status_element)->SetWindowTextW(L"Retrieving token... [Registration Token OK]"); progress_percent = 80; // we obtain the WebServiceToken string gamewebtoken = ""; attempt_num = 1; while (gamewebtoken == "" && attempt_num <= 3) { wstring dlg_text = L"Retrieving token... [Gamewebtoken Attempt #" + to_wstring(attempt_num) + L"]"; if (status_element) (*status_element)->SetWindowTextW(dlg_text.c_str()); attempt_num++; curl1 = curl_easy_init(); if (curl1) { struct curl_slist* chunk = NULL; string req_url = "https://api-lp1.znc.srv.nintendo.net/v2/Game/GetWebServiceToken"; static string buffer; chunk = curl_slist_append(chunk, "host: api-lp1.znc.srv.nintendo.net"); chunk = curl_slist_append(chunk, "content-type: application/json"); chunk = curl_slist_append(chunk, ("Authorization: Bearer " + access_token_t).c_str()); curl_easy_setopt(curl1, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl1, CURLOPT_URL, req_url.c_str()); curl_easy_setopt(curl1, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl1, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(curl1, CURLOPT_POST, 1L); string data = "{\"parameter\": {\"f\": \"abcd\",\"id\": 5741031244955648,\"registrationToken\": \"" + registration_token + "\",\"requestId\": \"abcd\",\"timestamp\": 0 }}"; curl_easy_setopt(curl1, CURLOPT_POSTFIELDS, data.c_str()); try { _logger->info("Sending request to https://api-lp1.znc.srv.nintendo.net/v2/Game/GetWebServiceToken.\n \ Using access token {}\n \ Using post data {}\n \ Obtained response {}", access_token_t, data, buffer); res = curl_easy_perform(curl1); } catch (const exception& e) { wstring afx_message = L"The program failed to perform the web request. (Attempt " + to_wstring(attempt_num - 1) + L"/3)"; AfxMessageBox(afx_message.c_str()); _logger->error("The program failed to perform the web request. e.what() returned: {}", e.what()); continue; } curl_easy_cleanup(curl1); curl_slist_free_all(chunk); buffer = remove_multi_response(buffer); try { nlohmann::json j = nlohmann::json::parse(buffer); gamewebtoken = j["result"]["accessToken"].get<string>(); } catch (const exception& e) { wstring afx_message = L"Failed to read the token from file. (Attempt " + to_wstring(attempt_num - 1) + L"/3)"; afx_message += transform::s2ws(e.what()); AfxMessageBox(afx_message.c_str()); _logger->error("Failed to read the token from file. (Attempt {}/3) e.what() returned: {}", to_string(attempt_num - 1), e.what()); continue; } } } if (gamewebtoken == "") { AfxMessageBox(L"Failed retrieving the gamewebtoken. Please try again or retrieve the token manually."); _logger->error("Failed retrieving the gamewebtoken."); AfxThrowUserException(); } progress_percent = 90; attempt_num = 1; while (ret == L"" && attempt_num <= 3) { wstring dlg_text = L"Retrieving token... [Authorization Attempt #" + to_wstring(attempt_num) + L"]"; _logger->info("Retrieving token... [Authorization Attempt #{}]", to_string(attempt_num)); if (status_element) (*status_element)->SetWindowTextW(dlg_text.c_str()); attempt_num++; curl2 = curl_easy_init(); if (curl2) { DeleteFile(L"cookies.txt"); struct curl_slist* chunk = NULL; string req_url = "https://app.splatoon2.nintendo.net/?lang=en-GB&na_country=DE&na_lang=en-US"; string cookie_path = "cookies.txt"; chunk = curl_slist_append(chunk, "host: app.splatoon2.nintendo.net"); chunk = curl_slist_append(chunk, ("x-gamewebtoken: " + gamewebtoken).c_str()); static string buffer; curl_easy_setopt(curl2, CURLOPT_COOKIEJAR, cookie_path.c_str()); curl_easy_setopt(curl2, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl2, CURLOPT_URL, req_url.c_str()); curl_easy_setopt(curl2, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl2, CURLOPT_WRITEDATA, &buffer); _logger->info("Sending request to https://app.splatoon2.nintendo.net/?lang=en-GB&na_country=DE&na_lang=en-US \n \ Using x-gamewebtoken {}", gamewebtoken); try { res = curl_easy_perform(curl2); } catch (const exception& e) { wstring afx_message = L"The program failed to perform the web request. (Attempt " + to_wstring(attempt_num - 1) + L"/3)"; afx_message += transform::s2ws(e.what()); _logger->error("The program failed to perform the web request. (Attempt {}/3) e.what() returned: {}", to_string(attempt_num - 1), e.what()); AfxMessageBox(afx_message.c_str()); continue; } /* always cleanup */ curl_easy_cleanup(curl2); /* free the custom headers */ curl_slist_free_all(chunk); try { // for logging purposes, we read and print the entire cookie file ifstream temp_file; temp_file.open(cookie_path); std::string temp_file_text((std::istreambuf_iterator<char>(temp_file)), std::istreambuf_iterator<char>()); temp_file.close(); _logger->info("Web request returned the following cookie (content of 'cookies.txt'):\n{}", temp_file_text); // we now read the information from the cookie file wifstream file; file.open(cookie_path); wstring line; while (getline(file, line)) { if (line.size() >= 30 // line must have more characters than length of the token && boost::contains(line, "iksm_session")) { // line must contain iksm_session vector<wstring> elems; boost::split(elems, line, boost::is_any_of("\t")); bool token = false; for (wstring elem : elems) { // check for entry iksm_session, then set next entry as return value if (token) ret = elem; token = (boost::contains(elem, "iksm_session")); } } } DeleteFile(L"cookies.txt"); } catch (const exception& e) { wstring afx_message = L"Failed retrieving token information. (Attempt " + to_wstring(attempt_num - 1) + L"/3)"; _logger->error("Failed retrieving token information (Attempt {}/3). e.what() returned {}", to_string(attempt_num - 1), e.what()); AfxMessageBox(afx_message.c_str()); continue; } } else { wstring afx_message = L"Could not open web connection object. (Attempt " + to_wstring(attempt_num - 1) + L"/3)"; _logger->error("Could not open web connection object. (Attempt {}/3)", to_string(attempt_num - 1)); AfxMessageBox(afx_message.c_str()); continue; } } if (ret == L"") { AfxMessageBox(L"The program failed to obtain the authorization token. Please try again or retrieve the token manually."); _logger->error("The program failed to obtain the authorization token."); AfxThrowUserException(); } _logger->info("access_token_to_iksm returns the following access token: {}", transform::ws2s(ret)); return ret; } UINT TokenRetriever::token_listener(LPVOID pParam) { // checks if token file exists // this listener expects MITM and emu to be running, waits for results TokenRetriever* token_retriever = (TokenRetriever*)pParam; while (!token_retriever->kill_token_listener) { if (boost::filesystem::exists("authorization.txt")) { ifstream file("authorization.txt"); string authorization_token; file >> authorization_token; file.close(); token_retriever->_logger->info("File 'authorization.txt' has been found. Content of the file:\n{}", authorization_token); if (authorization_token == "") continue; DeleteFile(L"authorization.txt"); ActionRequiredDlg("media/splatoon2_option.png", L"Please select the \"Splatoon 2\" option."); while (!token_retriever->kill_token_listener) { if (boost::filesystem::exists("iksm_cookie.txt")) { // the text file describes the cookie that contains the iksm_session parameter ifstream file("iksm_cookie.txt"); string iksm_cookie = string(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); file.close(); token_retriever->_logger->info("File 'iksm_cookie.txt' has been found. Content of the file:\n{}", iksm_cookie); if (iksm_cookie == "") // if the file is read as empty, retry continue; const string SESSION_KEY = "iksm_session="; if (iksm_cookie.find(SESSION_KEY) == string::npos) { // check if the term was even found at all token_retriever->_logger->info("The key for the iksm session (\"{}\") parameter could not be found within the file.", SESSION_KEY); AfxMessageBox(L"The retrieved information is invalid. Please refer to the logs or contact the developer for help."); AfxThrowUserException(); } size_t iksm_position = iksm_cookie.find(SESSION_KEY) + SESSION_KEY.length(); // points to the first character after SESSION_KEY token_retriever->iksm_token = iksm_cookie.substr(iksm_position, 40); token_retriever->_logger->info("Retrieved token: {}", *(token_retriever->iksm_token)); if (token_retriever->iksm_token->length() < 40 // token needs to have 40 characters || any_of(token_retriever->iksm_token->begin(), token_retriever->iksm_token->end(), [](char c) {return !isalnum(c); })) { // token only contains alphanumerical characters token_retriever->_logger->warn("Retrieved token seems to have an invalid shape."); AfxMessageBox(L"The retrieved token seems malformed and might not work as intended."); } DeleteFile(L"iksm_cookie.txt"); break; } } if (token_retriever->kill_token_listener) break; //token_retriever->iksm_token = transform::ws2s(token_retriever->access_token_to_iksm(authorization_token)); Sleep(1000); //TODO: We only actually need to wait here during the first setup (and maybe not at all) CloseHandle(token_retriever->mitm_handle); token_retriever->_logger->info("Closed MITM handle."); //CloseHandle(token_retriever->emu_handle); if (token_retriever->status_element) token_retriever->status_element.value()->SetWindowTextW(L"Sending close signal..."); // NOTE: Using the same code here as in bs_setup() - turning this into its own function might be worthwhile CRegKey registry; ULONG sz_installdir = MAX_PATH; CString cstr_installdir = CString(); // Computer\HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks has info we need in InstallDir registry.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\BlueStacks", KEY_READ); registry.QueryStringValue(L"InstallDir", cstr_installdir.GetBuffer(sz_installdir), &sz_installdir); wstring installdir = wstring(cstr_installdir); // we run HD-Quit.exe to quit bluestacks HANDLE quit_handle = TokenRetriever::run_command(installdir + L"HD-Quit.exe"); HANDLE bs_process_handle = FirstSetup::job_to_process_handle(token_retriever->emu_handle); DWORD ret_code = WaitForSingleObject(bs_process_handle, INFINITE); token_retriever->_logger->info("BlueStacks process has been finished. WaitForSingleObject returned: {}", to_string(ret_code)); //tokenDlg->tokenEdit.SetWindowTextW(tokenDlg->found_token.c_str()); //tokenDlg->tokenEdit.EnableWindow(TRUE); if (token_retriever->ok_button) (*(token_retriever->ok_button))->EnableWindow(TRUE); break; } Sleep(50); } return 0; }
35.572935
176
0.716812
snowpoke
cadf2157e6ba812f8befd185ce6212e9fe62fb3c
7,195
cpp
C++
hooks/recv_commands/CMDRECV_Build.cpp
Lucifirius/yzoriansteampunk
7b629ffd9740f0ff3db1fb8cffe07f45b7528854
[ "Unlicense" ]
null
null
null
hooks/recv_commands/CMDRECV_Build.cpp
Lucifirius/yzoriansteampunk
7b629ffd9740f0ff3db1fb8cffe07f45b7528854
[ "Unlicense" ]
null
null
null
hooks/recv_commands/CMDRECV_Build.cpp
Lucifirius/yzoriansteampunk
7b629ffd9740f0ff3db1fb8cffe07f45b7528854
[ "Unlicense" ]
null
null
null
#include "CMDRECV_Build.h" #include <SCBW/api.h> //Helper functions declaration namespace { Bool32 OrderAllowed(CUnit* unit, u16 order, u32 nationID); //6DC20 u32 function_00473FB0(CUnit* unit, u8 playerId, int x, int y, u16 unitId, u8 unk1, u8 unk2, u8 unk3, u8 unk4 ); //73FB0 bool placeBuildingMsg(u32 result_function_473FB0); //8D930 bool CMDRECV_PlaceBuildingAllowedHelper(CUnit* unit, u8 orderId, u16 builtUnitId); //8DBD0 void function_0048DE70(CUnit* unit, u32 orderId, u16 dimensionX, u16 dimensionY, u32 builtUnitId); //8DE70 void cmdRECV_PlaceBuilding(s16 x, s16 y, u8 orderId, u16 builtUnitId); //8E190 } //unnamed namespace namespace hooks { bool CMDRECV_PlaceBuildingAllowed(CUnit* builder, u8 orderId, u16 builtUnitId) { bool bReturnValue = false; if(orderId >= OrderId::DroneStartBuild && orderId <= OrderId::CTFCOP2) { if( orderId == OrderId::DroneStartBuild || orderId == OrderId::BuildTerran || orderId == OrderId::BuildProtoss1 || orderId == OrderId::BuildProtoss2 || orderId == OrderId::PlaceAddon ) { if(builder->canMakeUnit(builtUnitId,*ACTIVE_NATION_ID)) bReturnValue = (OrderAllowed(builder,orderId,*ACTIVE_NATION_ID) != 0); } else if( orderId == OrderId::Build5 || //Build Nydus Exit orderId == OrderId::BuildingLand ) { if(builder->id == builtUnitId) bReturnValue = (OrderAllowed(builder,orderId,*ACTIVE_NATION_ID) != 0); } else if(orderId == OrderId::CTFCOP2) { //Create flag beacon if(*elapsedTimeSeconds <= 600 && builder->id == builtUnitId) bReturnValue = (OrderAllowed(builder,orderId,*ACTIVE_NATION_ID) != 0); } } return bReturnValue; } ; void cmdRECV_PlaceBuildingNormal(s16 x, s16 y, u32 orderId, u32 builtUnitId) { CUnit* builder; u32 result_function_00473FB0; *selectionIndexStart = 0; builder = getActivePlayerNextSelection(); result_function_00473FB0 = function_00473FB0( builder, builder->playerId, x, y, builtUnitId, 1, 0, 0, 0 ); if(placeBuildingMsg(result_function_00473FB0)) { s32 DimensionX, DimensionY; DimensionX = (s16)units_dat::BuildingDimensions[builtUnitId].x; if(DimensionX < 0) DimensionX++; DimensionX /= 2; DimensionX += (x * 32); DimensionY = (s16)units_dat::BuildingDimensions[builtUnitId].y; if(DimensionY < 0) DimensionY++; DimensionY /= 2; DimensionY += (y * 32); function_0048DE70(builder,orderId,DimensionX,DimensionY,builtUnitId); } } ; void cmdRECV_PlaceBuildingAddon(s16 x, s16 y, u32 orderId, u32 builtUnitId) { CUnit* builder; u32 result_function_00473FB0; s32 addonPlaceX = 0, addonPlaceY = 0; *selectionIndexStart = 0; builder = getActivePlayerNextSelection(); result_function_00473FB0 = function_00473FB0( builder, builder->playerId, x, y, builtUnitId, 1, 0, 0, 0 ); if(result_function_00473FB0 == 0) { addonPlaceX = (s16)units_dat::AddonPlacement[builtUnitId - UnitId::TerranCommandCenter].x; if(addonPlaceX < 0) addonPlaceX += 31; addonPlaceX /= 32; addonPlaceX = x - addonPlaceX; addonPlaceY = (s16)units_dat::AddonPlacement[builtUnitId - UnitId::TerranCommandCenter].y; if(addonPlaceY < 0) addonPlaceY += 31; addonPlaceY /= 32; addonPlaceY = y - addonPlaceY; result_function_00473FB0 = function_00473FB0( builder, builder->playerId, addonPlaceX, addonPlaceY, builder->id, 0, 0, 0, 0 ); } if(placeBuildingMsg(result_function_00473FB0)) { s32 DimensionX, DimensionY; DimensionX = (s16)units_dat::BuildingDimensions[builder->id].x; if(DimensionX < 0) DimensionX++; DimensionX /= 2; addonPlaceX *= 32; DimensionX += addonPlaceX; DimensionY = (s16)units_dat::BuildingDimensions[builder->id].y; if(DimensionY < 0) DimensionY++; DimensionY /= 2; addonPlaceY *= 32; DimensionY += addonPlaceY; function_0048DE70(builder,orderId,DimensionX,DimensionY,builtUnitId); } } ; void CMDRECV_Build(u8 orderId, s16 x, s16 y, u16 builtUnitId) { CUnit* builder; *selectionIndexStart = 0; builder = getActivePlayerNextSelection(); if(builder != NULL) { if(getActivePlayerNextSelection() == NULL) { //multiple selection not allowed if( x < mapTileSize->width && y < mapTileSize->height && CMDRECV_PlaceBuildingAllowedHelper(builder, orderId, builtUnitId) ) cmdRECV_PlaceBuilding(x, y, orderId, builtUnitId); } } } ; } //namespace hooks //-------- Helper function definitions. Do NOT modify! --------// namespace { const u32 Func_OrderAllowed = 0x0046DC20; Bool32 OrderAllowed(CUnit* unit, u16 order, u32 nationID) { static Bool32 bResult; __asm { PUSHAD MOV BX, order MOV EAX, unit PUSH nationID CALL Func_OrderAllowed MOV bResult, EAX POPAD } return bResult; } ; const u32 Func_Sub473FB0 = 0x00473FB0; u32 function_00473FB0(CUnit* unit, u8 playerId, int x, int y, u16 unitId, u8 unk1, u8 unk2, u8 unk3, u8 unk4 ) { u32 return_value; __asm { PUSHAD MOVZX EAX, unk4 /*28*/ PUSH EAX MOVZX EAX, unk3 /*24*/ PUSH EAX MOVZX EAX, unk2 /*20*/ PUSH EAX MOVZX EAX, unk1 /*1C*/ PUSH EAX MOVZX EAX, unitId /*18*/ PUSH EAX PUSH y /*14*/ PUSH x /*10*/ MOVZX EAX, playerId /*0C*/ PUSH EAX PUSH unit /*08*/ CALL Func_Sub473FB0 MOV return_value, EAX POPAD } return return_value; } ; const u32 Func_placeBuildingMsg = 0x0048D930; bool placeBuildingMsg(u32 result_function_473FB0) { static Bool32 bPreResult; __asm { PUSHAD MOV EAX, result_function_473FB0 CALL Func_placeBuildingMsg MOV bPreResult, EAX POPAD } return (bPreResult != 0); } ; const u32 Func_CMDRECV_PlaceBuildingAllowed = 0x0048DBD0; bool CMDRECV_PlaceBuildingAllowedHelper(CUnit* unit, u8 orderId, u16 builtUnitId) { static Bool32 bPreResult; __asm { PUSHAD MOV AX, builtUnitId MOV DL, orderId MOV ECX, unit CALL Func_CMDRECV_PlaceBuildingAllowed MOV bPreResult, EAX POPAD } return (bPreResult != 0); } ; const u32 Func_Sub48DE70 = 0x0048DE70; void function_0048DE70(CUnit* unit, u32 orderId, u16 dimensionX, u16 dimensionY, u32 builtUnitId) { static Point16 dim; dim.x = dimensionX;dim.y = dimensionY; __asm { PUSHAD PUSH builtUnitId PUSH dim PUSH orderId MOV EAX, unit CALL Func_Sub48DE70 POPAD } } ; const u32 Func_cmdRECV_PlaceBuilding = 0x0048E190; void cmdRECV_PlaceBuilding(s16 x, s16 y, u8 orderId, u16 builtUnitId) { static Point16 pos; pos.x = x;pos.y = y; __asm { PUSHAD MOVZX EAX, builtUnitId //bugfix: should have been "MOV AX, builtUnitId" but for some reason it crashed MOV CL, orderId PUSH pos CALL Func_cmdRECV_PlaceBuilding POPAD } } ; } //unnamed namespace //End of helper functions
19.393531
120
0.65615
Lucifirius
cae345cbe02769fdfae5082205b7110fbfca97c5
1,411
cpp
C++
iface_kcan.cpp
azarenko/cascade
47d538df4f2c8014cefbb43495d995e43c97c1b2
[ "Apache-2.0" ]
null
null
null
iface_kcan.cpp
azarenko/cascade
47d538df4f2c8014cefbb43495d995e43c97c1b2
[ "Apache-2.0" ]
null
null
null
iface_kcan.cpp
azarenko/cascade
47d538df4f2c8014cefbb43495d995e43c97c1b2
[ "Apache-2.0" ]
null
null
null
/* * iface_kcan.cpp * * (C) Copyright 2014 Ulrich Hecht * * This file is part of CASCADE. CASCADE is almost free software; you can * redistribute it and/or modify it under the terms of the Cascade Public * License 1.0. Read the file "LICENSE" for details. */ #include "iface_kcan.h" #include "iface_kl_tty.h" #include "iface_can.h" #include "os.h" #include "autotty.h" IfaceKCAN::IfaceKCAN(Cpu *c, UI* ui, const char *driver) : Interface(ui) { cpu = c; can_enabled = false; atty = new AutoTTY(ui, driver); iface = new IfaceKLTTY(c, ui, atty); iface->setSerial(serial); } void IfaceKCAN::setSerial(Serial *s) { serial = s; iface->setSerial(serial); } IfaceKCAN::~IfaceKCAN() { delete iface; delete atty; } void IfaceKCAN::setCAN(bool onoff) { DEBUG(IFACE, "KCAN setCAN %d\n", onoff); if (onoff != can_enabled) { delete iface; if(onoff) iface = new IfaceCAN(cpu, ui, atty); else iface = new IfaceKLTTY(cpu, ui, atty); iface->setSerial(serial); } can_enabled = onoff; } void IfaceKCAN::setBaudDivisor(int divisor) { iface->setBaudDivisor(divisor); } void IfaceKCAN::checkInput() { iface->checkInput(); } void IfaceKCAN::sendByte(uint8_t byte) { iface->sendByte(byte); } void IfaceKCAN::slowInitImminent() { iface->slowInitImminent(); } bool IfaceKCAN::sendSlowInitBitwise(uint8_t bit) { return iface->sendSlowInitBitwise(bit); }
18.565789
74
0.681077
azarenko
cae823fbd579dea15331da41a03b923dee520845
36
hpp
C++
src/boost_asio_streambuf.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_asio_streambuf.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_asio_streambuf.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/asio/streambuf.hpp>
18
35
0.777778
miathedev
caeb79731b880c33960723192eb0f6bdbbb6f2f3
8,678
cxx
C++
core/teca_temporal_reduction.cxx
burlen/teca_arch
6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_temporal_reduction.cxx
burlen/teca_arch
6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_temporal_reduction.cxx
burlen/teca_arch
6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "teca_temporal_reduction.h" #include "teca_binary_stream.h" #if defined(TECA_HAS_MPI) #include <mpi.h> #endif #if defined(TECA_HAS_BOOST) #include <boost/program_options.hpp> #endif using std::string; using std::vector; using std::cerr; using std::endl; // TODO // handle large messages, ie work around int in MPI api namespace { #if defined(TECA_HAS_MPI) // helper for sending binary data over MPI int send(MPI_Comm comm, int dest, teca_binary_stream &s) { unsigned long long n = s.size(); if (MPI_Send(&n, 1, MPI_UNSIGNED_LONG_LONG, dest, 3210, comm)) { TECA_ERROR("failed to send send message size") return -1; } if (n) { if (MPI_Send( s.get_data(), n, MPI_UNSIGNED_CHAR, dest, 3211, MPI_COMM_WORLD)) { TECA_ERROR("failed to send message") return -2; } } return 0; } // helper for receiving data over MPI int recv(MPI_Comm comm, int src, teca_binary_stream &s) { size_t n = 0; MPI_Status stat; if (MPI_Recv(&n, 1, MPI_UNSIGNED_LONG_LONG, src, 3210, comm, &stat)) { TECA_ERROR("failed to receive") return -2; } s.resize(n); if (n) { if (MPI_Recv(s.get_data(), n, MPI_UNSIGNED_CHAR, src, 3211, comm, &stat)) { TECA_ERROR("failed to receive") return -2; } } return 0; } #endif }; // -------------------------------------------------------------------------- teca_temporal_reduction::teca_temporal_reduction() : first_step(0), last_step(-1) {} #if defined(TECA_HAS_BOOST) // -------------------------------------------------------------------------- void teca_temporal_reduction::get_properties_description( const string &prefix, options_description &global_opts) { this->teca_threaded_algorithm::get_properties_description(prefix, global_opts); options_description opts("Options for " + prefix + "(teca_temporal_reduction)"); opts.add_options() TECA_POPTS_GET(long, prefix, first_step, "first time step to process") TECA_POPTS_GET(long, prefix, last_step, "last time step to process") ; global_opts.add(opts); } // -------------------------------------------------------------------------- void teca_temporal_reduction::set_properties( const string &prefix, variables_map &opts) { this->teca_threaded_algorithm::set_properties(prefix, opts); TECA_POPTS_SET(opts, long, prefix, first_step) TECA_POPTS_SET(opts, long, prefix, last_step) } #endif // -------------------------------------------------------------------------- std::vector<teca_metadata> teca_temporal_reduction::get_upstream_request( unsigned int port, const std::vector<teca_metadata> &input_md, const teca_metadata &request) { vector<teca_metadata> up_req; // locate available times long n_times; if (input_md[0].get("number_of_time_steps", n_times)) { TECA_ERROR("metadata is missing \"number_of_time_steps\"") return up_req; } // apply restriction long last = this->last_step >= 0 ? this->last_step : n_times - 1; long first = ((this->first_step >= 0) && (this->first_step <= last)) ? this->first_step : 0; n_times = last - first + 1; // partition time across MPI ranks. each rank // will end up with a unique block of times // to process. size_t rank = 0; size_t n_ranks = 1; #if defined(TECA_HAS_MPI) int is_init = 0; MPI_Initialized(&is_init); if (is_init) { int tmp = 0; MPI_Comm_size(MPI_COMM_WORLD, &tmp); n_ranks = tmp; MPI_Comm_rank(MPI_COMM_WORLD, &tmp); rank = tmp; } #endif size_t n_big_blocks = n_times%n_ranks; size_t block_size = 1; size_t block_start = 0; if (rank < n_big_blocks) { block_size = n_times/n_ranks + 1; block_start = block_size*rank; } else { block_size = n_times/n_ranks; block_start = block_size*rank + n_big_blocks; } // get the filters basic request vector<teca_metadata> base_req = this->initialize_upstream_request(port, input_md, request); // apply the base request to local times. // requests are mapped onto inputs round robbin for (size_t i = 0; i < block_size; ++i) { size_t step = i + block_start + first; size_t n_reqs = base_req.size(); for (size_t j = 0; j < n_reqs; ++j) { up_req.push_back(base_req[j]); up_req.back().insert("time_step", step); } } return up_req; } // -------------------------------------------------------------------------- teca_metadata teca_temporal_reduction::get_output_metadata( unsigned int port, const std::vector<teca_metadata> &input_md) { teca_metadata output_md = this->initialize_output_metadata(port, input_md); output_md.remove("time_step"); return output_md; } // -------------------------------------------------------------------------- const_p_teca_dataset teca_temporal_reduction::reduce_local( std::vector<const_p_teca_dataset> input_data) // pass by value is intentional { size_t n_in = input_data.size(); if (n_in == 0) return p_teca_dataset(); if (n_in == 1) return input_data[0]; while (n_in > 1) { if (n_in % 2) input_data[0] = this->reduce(input_data[0], input_data[n_in-1]); size_t n = n_in/2; for (size_t i = 0; i < n; ++i) { size_t ii = 2*i; input_data[i] = this->reduce(input_data[ii], input_data[ii+1]); } n_in = n; } return input_data[0]; } // -------------------------------------------------------------------------- const_p_teca_dataset teca_temporal_reduction::reduce_remote( const_p_teca_dataset local_data) // pass by value is intentional { #if defined(TECA_HAS_MPI) int is_init = 0; MPI_Initialized(&is_init); if (is_init) { size_t rank = 0; size_t n_ranks = 1; int tmp = 0; MPI_Comm_size(MPI_COMM_WORLD, &tmp); n_ranks = tmp; MPI_Comm_rank(MPI_COMM_WORLD, &tmp); rank = tmp; // special case 1 rank, nothing to do if (n_ranks < 2) return local_data; // reduce remote datasets in binary tree order size_t id = rank + 1; size_t up_id = id/2; size_t left_id = 2*id; size_t right_id = left_id + 1; teca_binary_stream bstr; // recv from left if (left_id <= n_ranks) { if (::recv(MPI_COMM_WORLD, left_id-1, bstr)) { TECA_ERROR("failed to recv from left") return p_teca_dataset(); } p_teca_dataset left_data; if (local_data && bstr) { left_data = local_data->new_instance(); left_data->from_stream(bstr); } local_data = this->reduce(local_data, left_data); bstr.resize(0); } // recv from right if (right_id <= n_ranks) { if (::recv(MPI_COMM_WORLD, right_id-1, bstr)) { TECA_ERROR("failed to recv from right") return p_teca_dataset(); } p_teca_dataset right_data; if (local_data && bstr) { right_data = local_data->new_instance(); right_data->from_stream(bstr); } local_data = this->reduce(local_data, right_data); bstr.resize(0); } // send up if (rank) { if (local_data) local_data->to_stream(bstr); if (::send(MPI_COMM_WORLD, up_id-1, bstr)) TECA_ERROR("failed to send up") // all but root returns an empty dataset return p_teca_dataset(); } } #endif // rank 0 has all the data return local_data; } // -------------------------------------------------------------------------- const_p_teca_dataset teca_temporal_reduction::execute( unsigned int port, const std::vector<const_p_teca_dataset> &input_data, const teca_metadata &request) { (void)port; (void)request; // noet: it is not an error to have no input data. // this can occur if there are fewer time steps // to process than there are MPI ranks. return this->reduce_remote(this->reduce_local(input_data)); }
26.217523
84
0.550472
burlen
caefba681239bdb5d2815a03d000c3a070935baa
1,272
hpp
C++
include/System/Threading/IThreadPoolWorkItem.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Threading/IThreadPoolWorkItem.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Threading/IThreadPoolWorkItem.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes // Completed includes // Begin forward declares // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: ThreadAbortException class ThreadAbortException; } // Completed forward declares // Type namespace: System.Threading namespace System::Threading { // Size: 0x0 #pragma pack(push, 1) // Autogenerated type: System.Threading.IThreadPoolWorkItem class IThreadPoolWorkItem { public: // Creating value type constructor for type: IThreadPoolWorkItem IThreadPoolWorkItem() noexcept {} // public System.Void ExecuteWorkItem() // Offset: 0xFFFFFFFF void ExecuteWorkItem(); // public System.Void MarkAborted(System.Threading.ThreadAbortException tae) // Offset: 0xFFFFFFFF void MarkAborted(System::Threading::ThreadAbortException* tae); }; // System.Threading.IThreadPoolWorkItem #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Threading::IThreadPoolWorkItem*, "System.Threading", "IThreadPoolWorkItem");
37.411765
108
0.698113
darknight1050
caf44b6636c37c36e9e9d05e8bcf81b1b9d0a989
3,413
cpp
C++
cpp/nn_trees/src/py_bindings.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
1
2019-02-15T09:40:43.000Z
2019-02-15T09:40:43.000Z
cpp/nn_trees/src/py_bindings.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/nn_trees/src/py_bindings.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
2
2018-09-29T10:17:26.000Z
2018-10-03T20:33:31.000Z
#include <cstdint> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include "nntree/dataset.h" #include "least_squares.h" #include "convolution.h" // TODO(equivalence1) make it a collection of separate files namespace py = pybind11; namespace nntree { namespace pymodule { template <typename T> struct PyCpuTensor : public core::CpuTensor<T> { explicit PyCpuTensor(py::buffer_info&& buff) { auto ptr = (T*) buff.ptr; auto shape = std::vector<uint64_t>(buff.shape.begin(), buff.shape.end()); auto strides = std::vector<uint64_t>(buff.strides.begin(), buff.strides.end()); this->FromMem(ptr, shape, strides, false); } }; // We have to store x and y arrays in DataSet // otherwise there will be memory leaks template <typename IN_T = double, typename OUT_T = double> class DataSet : public core::DataSet<IN_T, OUT_T> { public: DataSet(py::array_t<IN_T> x, py::array_t<OUT_T> y) // TODO(equvalence1) leak here : core::DataSet<IN_T, OUT_T>(new PyCpuTensor<IN_T>(x.request()), new PyCpuTensor<OUT_T>(y.request())) , x_(std::move(x)) , y_(std::move(y)) {} // Just a test function to check that we correctly accept data from python py::array_t<double> TestPrint(int64_t size) { auto X = x_.request(false); printf("%zu %zu\n", X.size / X.itemsize, X.itemsize); auto res = core::convolution((float*) X.ptr, size, 1, 1); // least_squares((float *)X.ptr, (float *)y_.request(false).ptr, X.size / X.itemsize, X.itemsize); // size = std::min(size, buff.size / buff.itemsize); // for (int64_t i = 0; i < size; i++) { // printf("%f ", ((float*)buff.ptr)[i]); // } py::array_t<double> result = py::array_t<double>(res.size()); auto buf = result.request(); auto ptr = (double*) buf.ptr; for (size_t i = 0; i < res.size(); ++i) { ptr[i] = res[i]; } //result.resize({size, 1}); return result; } private: py::array_t<IN_T> x_; py::array_t<OUT_T> y_; }; py::array_t<double> least_squares(DataSet<double, double>& ds) { core::CpuTensor<double> w; core::LeastSquares(ds, w); py::array_t<double> res = py::array_t<double>((size_t) w.Size()); auto res_buff = res.request(); auto res_buff_ptr = (double*) res_buff.ptr; for (int i = 0; i < res.size(); i++) { res_buff_ptr[i] = w.GetVal((uint64_t) i); } res.resize(w.Shape()); return res; } PYBIND11_MODULE(nntreepy, m) { m.doc() = "nntreepy module to work with intel mkl through python"; py::class_<DataSet<double, double>> dataset(m, "DataSet"); dataset.def(py::init<py::array_t<double>, py::array_t<double>>()); dataset.def("test_print", &DataSet<double, double>::TestPrint); m.def("least_squares", &least_squares); } } }
38.348315
147
0.517433
equivalence1
caf59ed68fb1e9a3a8d68687b61648006b54513a
14,894
hpp
C++
modules/containers/include/shard/containers/array.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/containers/include/shard/containers/array.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/containers/include/shard/containers/array.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Miklos Molnar. All rights reserved. #ifndef SHARD_CONTAINERS_ARRAY_HPP #define SHARD_CONTAINERS_ARRAY_HPP #include <shard/memory/allocator.hpp> #include <algorithm> #include <cstddef> #include <cstring> #include <iterator> #include <stdexcept> #include <utility> namespace shard { namespace containers { template <typename T> class array { public: using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = const value_type*; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; public: explicit array(allocator& a, size_type capacity = 0) : m_allocator(&a), m_capacity(capacity) { if (m_capacity > 0) { m_data = allocate(capacity); } } template <typename Iterator> array(allocator& a, Iterator begin, Iterator end) : m_allocator(&a), m_capacity(0) { auto size = std::distance(begin, end); if (size > 0) { m_data = allocate(size); m_size = size; m_capacity = size; std::copy(begin, end, m_data); } } array(allocator& a, std::initializer_list<value_type> il) : m_allocator(&a) { if (il.size() > 0) { m_data = allocate(il.size()); m_size = il.size(); m_capacity = il.size(); auto p = m_data; for (auto it = il.begin(); it != il.end(); ++it, ++p) { *p = *it; } } else { m_data = nullptr; m_size = 0; m_capacity = 0; } } /// Copy constructor array(const array& other) : m_allocator(other.m_allocator), m_size(other.m_size), m_capacity(other.m_capacity) { if (m_capacity > 0) { auto data = allocate(m_capacity); m_data = static_cast<pointer>(std::memcpy(data, other.m_data, m_capacity * value_size)); } } /// Move constructor array(array&& other) noexcept : m_allocator(other.m_allocator), m_data(other.m_data), m_size(other.m_size), m_capacity(other.m_capacity) { // invalidate "moved-from" object other.m_allocator = nullptr; other.m_data = nullptr; other.m_size = 0; other.m_capacity = 0; } ~array() { deallocate(); } /// Copy assignment operator array& operator=(const array& other) { if (this != &other) { // destroy elements and deallocate memory deallocate(); // allocate new memory m_allocator = other.m_allocator; if (other.m_capacity > 0) { auto data = allocate(other.m_capacity); m_data = static_cast<pointer>(std::memcpy(data, other.m_data, other.m_capacity * value_size)); } m_size = other.m_size; m_capacity = other.m_capacity; } return *this; } /// Move assignment operator array& operator=(array&& other) noexcept { // destroy elements and deallocate memory deallocate(); // allocate new memory m_allocator = other.m_allocator; if (other.m_capacity > 0) { m_data = allocate(other.m_capacity); for (std::size_t i = 0; i < other.m_size; ++i) { m_data[i] = std::move(other.m_data[i]); } } m_size = other.m_size; m_capacity = other.m_capacity; // deallocate "moved-from" memory other.m_allocator->deallocate(other.m_data); // invalidate "moved-from" object other.m_allocator = nullptr; other.m_data = nullptr; other.m_size = 0; other.m_capacity = 0; return *this; } // modifiers /// Add a new element at the end void append(const_reference value) { ensure_element_fits(); m_data[m_size++] = value; } /// Add a new element at the end void append(value_type&& value) { ensure_element_fits(); m_data[m_size++] = std::move(value); } // for STL compatibility void push_back(const_reference value) { append(value); } // for STL compatibility void push_back(value_type&& value) { append(std::move(value)); } /// Add a new element at the specified position iterator insert(const_iterator pos, const_reference value) { ensure_element_fits(); auto i = pos ? pos - cbegin() : 0; auto p = m_data + i; // move the elements in the range [p, end) to start at 'p + 1' std::move_backward(p, m_data + m_size, m_data + m_size + 1); m_data[i] = value; ++m_size; return m_data + i; } /// Add a new element at the specified position iterator insert(const_iterator pos, value_type&& value) { ensure_element_fits(); auto i = pos ? pos - cbegin() : 0; auto p = m_data + i; // move the elements in the range [p, end) to start at 'p + 1' std::move_backward(p, m_data + m_size, m_data + m_size + 1); m_data[i] = std::move(value); ++m_size; return m_data + i; } /// Create a new element in-place at the specified position template <typename... Args> iterator emplace(const_iterator pos, Args&&... args) { ensure_element_fits(); auto i = pos ? pos - cbegin() : 0; auto p = m_data + i; // move the elements in the range [p, end) to start at 'p + 1' std::move_backward(p, m_data + m_size, m_data + m_size + 1); new (m_data + i) value_type(std::forward<Args>(args)...); ++m_size; return m_data + i; } /// Create a new element in-place at the end template <typename... Args> void emplace_back(Args&&... args) { ensure_element_fits(); new (m_data + m_size) value_type(std::forward<Args>(args)...); ++m_size; } /// Remove the element at the specified position iterator remove(const_iterator pos) { assert(pos != end()); auto p = m_data + (pos - cbegin()); // move the elements in the range [p + 1, end) to start at 'p' destruct_after(std::move(p + 1, m_data + m_size, p)); return p; } /// Remove the elements in the specified range iterator remove(const_iterator first, const_iterator last) { assert(first <= last); auto start = first - cbegin(); auto p_first = m_data + start; if (first != last) { auto p_last = p_first + (last - first); // move the elements in the range [last, end) to start at 'p_first' // note: this does not move anything if last == end destruct_after(std::move(p_last, m_data + m_size, p_first)); } return p_first; } /// Remove the element at the end void remove_last() { assert(m_size > 0); destruct_after(m_data + m_size - 1); } // for STL compatibility void pop_back() { remove_last(); } /// Remove every element /// /// \note: This does *NOT* deallocate the used memory void clear() { if (!m_data) { return; } // destroy all the elements destruct_after(m_data); // reset the information m_size = 0; } /// Exchange the contents of the array with those of another void swap(array& other) { using std::swap; swap(m_allocator, other.m_allocator); swap(m_data, other.m_data); swap(m_size, other.m_size); swap(m_capacity, other.m_capacity); } // element access /// Get the first element reference first() { if (m_size == 0) { throw std::out_of_range("shard::containers::array::first()"); } return m_data[0]; } /// Get the first element const_reference first() const { if (m_size == 0) { throw std::out_of_range("shard::containers::array::first()"); } return m_data[0]; } /// Get the last element reference last() { if (m_size == 0) { throw std::out_of_range("shard::containers::array::last()"); } return m_data[m_size - 1]; } /// Get the last element const_reference last() const { if (m_size == 0) { throw std::out_of_range("shard::containers::array::last()"); } return m_data[m_size - 1]; } /// Get the element at the given index /// /// \note Will check if the index is in range reference at(size_type index) { auto& const_this = static_cast<const array&>(*this); return const_cast<reference>(const_this.at(index)); } /// Get the element at the given index /// /// \note Will check if the index is in range const_reference at(size_type index) const { if (index >= m_size) { throw std::out_of_range("shard::containers::array::at()"); } return m_data[index]; } /// Get the element at the given index /// /// \note Will *NOT* check if the index is in range reference operator[](size_type index) { return m_data[index]; } /// Get the element at the given index /// /// \note Will *NOT* check if the index is in range const_reference operator[](size_type index) const { return m_data[index]; } /// Return a pointer to the underlying raw array pointer data() noexcept { return m_data; } /// Return a pointer to the underlying raw array const_pointer data() const noexcept { return m_data; } // size & capacity /// Get the number of elements in the array size_type size() const noexcept { return m_size; } /// Check if the array is empty bool is_empty() const noexcept { return m_size == 0; } // for STL compatibility bool empty() const noexcept { return is_empty(); } /// Get the number of elements memory is reserved for size_type capacity() const noexcept { return m_capacity; } /// Reserve memory if (needed) for more elements void reserve(size_type new_capacity) { if (new_capacity > m_capacity) { reallocate(new_capacity); } } /// Set the size and potentially incur a reallocation /// /// \note This will not reduce memory usage even if the new size is less /// than the current size void resize(size_type new_size) { if (new_size > m_capacity) { grow(new_size); } if (new_size < m_size) { // destroy elements destruct_after(m_data + new_size); } else if (new_size > m_size) { // default construct elements in-place for (auto i = m_size; i < new_size; ++i) { new (m_data + i) value_type(); } } m_size = new_size; } /// Reallocate exactly the amount of memory needed to store the elements void shrink_to_fit() { reallocate(m_size); } // iterators iterator begin() noexcept { return m_data; } const_iterator begin() const noexcept { return m_data; } const_iterator cbegin() const noexcept { return m_data; } iterator end() noexcept { return m_data + m_size; } const_iterator end() const noexcept { return m_data + m_size; } const_iterator cend() const noexcept { return m_data + m_size; } reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } reverse_iterator rend() noexcept { return reverse_iterator(begin()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const noexcept { return rend(); } private: pointer allocate(size_type size) { auto data = static_cast<pointer>(m_allocator->allocate(value_size * size, value_align)); // throw an exception if the allocation failed if (!data) { throw std::bad_alloc(); } return data; } void ensure_element_fits() { if (m_size + 1 > m_capacity) { grow(m_size + 1); } } void grow(size_type min_capacity) { size_type new_capacity = 4; while (new_capacity < min_capacity) { new_capacity *= 2; } reallocate(new_capacity); } void reallocate(size_type new_capacity) { if (new_capacity == m_capacity) { return; } if (new_capacity < m_size) { m_size = new_capacity; } pointer new_data = nullptr; if (new_capacity > 0) { // ask the allocator for a new block of memory new_data = static_cast<pointer>(m_allocator->allocate(value_size * new_capacity, value_align)); // throw an exception if the allocation failed if (!new_data) { throw std::bad_alloc(); } // copy the old data to the new location std::memcpy(new_data, m_data, m_size * value_size); } if (m_data) { m_allocator->deallocate(m_data); } m_data = new_data; m_capacity = new_capacity; } void destruct_after(pointer new_end) { auto start = new_end - cbegin(); for (size_type i = start; i < m_size; ++i) { m_data[i].~value_type(); } m_size = start; } void deallocate() { if (!m_data) { return; } // destroy all the elements and deallocate the memory destruct_after(m_data); m_allocator->deallocate(m_data); // reset the data m_data = nullptr; m_size = 0; m_capacity = 0; } private: static constexpr auto value_size = sizeof(value_type); static constexpr auto value_align = alignof(value_type); private: allocator* m_allocator; pointer m_data = nullptr; size_type m_size = 0; size_type m_capacity; }; template <typename T> void swap(array<T>& lhs, array<T>& rhs) { lhs.swap(rhs); } template <typename T> bool operator==(const array<T>& lhs, const array<T>& rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template <typename T> bool operator!=(const array<T>& lhs, const array<T>& rhs) { return !(lhs == rhs); } } // namespace containers // bring symbols into parent namespace using containers::array; } // namespace shard #endif // SHARD_CONTAINERS_ARRAY_HPP
29.376726
116
0.586478
ikimol
caf88183ce6130f29517b09821f2a8484d40f5ca
8,573
cpp
C++
ManagedScripts/MLightPhysClassRefMultiListClass.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
ManagedScripts/MLightPhysClassRefMultiListClass.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
ManagedScripts/MLightPhysClassRefMultiListClass.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
/* Copyright 2020 Neijwiert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "stdafx.h" #include "MLightPhysClassRefMultiListClass.h" #include "Imports.h" #include "UnmanagedContainer.h" namespace RenSharp { LightPhysClassRefMultiListClass::LightPhysClassRefMultiListClass() : RefMultiListClass<ILightPhysClass ^>(IntPtr(Imports::CreateLightPhysClassRefMultiListClass())) { } LightPhysClassRefMultiListClass::LightPhysClassRefMultiListClass(IntPtr pointer) : RefMultiListClass<ILightPhysClass ^>(pointer) { } IUnmanagedContainer<IRefMultiListClass<ILightPhysClass ^> ^> ^LightPhysClassRefMultiListClass::CreateLightPhysClassRefMultiListClass() { return gcnew UnmanagedContainer<IRefMultiListClass<ILightPhysClass ^> ^>(gcnew LightPhysClassRefMultiListClass()); } bool LightPhysClassRefMultiListClass::Contains(ILightPhysClass ^obj) { return GenericContains(obj); } bool LightPhysClassRefMultiListClass::Add(ILightPhysClass ^obj, bool onlyOnce) { if (obj == nullptr || obj->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("obj"); } return InternalLightPhysClassRefMultiListClassPointer->Add( reinterpret_cast<::LightPhysClass *>(obj->LightPhysClassPointer.ToPointer()), onlyOnce); } bool LightPhysClassRefMultiListClass::AddTail(ILightPhysClass ^obj, bool onlyOnce) { if (obj == nullptr || obj->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("obj"); } return InternalLightPhysClassRefMultiListClassPointer->Add_Tail( reinterpret_cast<::LightPhysClass *>(obj->LightPhysClassPointer.ToPointer()), onlyOnce); } bool LightPhysClassRefMultiListClass::AddTail(ILightPhysClass ^obj) { if (obj == nullptr || obj->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("obj"); } return InternalLightPhysClassRefMultiListClassPointer->Add_Tail( reinterpret_cast<::LightPhysClass *>(obj->LightPhysClassPointer.ToPointer())); } bool LightPhysClassRefMultiListClass::AddAfter(ILightPhysClass ^obj, ILightPhysClass ^existingListMember, bool onlyOnce) { if (obj == nullptr || obj->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("obj"); } else if (existingListMember == nullptr || existingListMember->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("existingListMember"); } return InternalLightPhysClassRefMultiListClassPointer->Add_After( reinterpret_cast<::LightPhysClass *>(obj->LightPhysClassPointer.ToPointer()), reinterpret_cast<::LightPhysClass *>(existingListMember->LightPhysClassPointer.ToPointer()), onlyOnce); } bool LightPhysClassRefMultiListClass::AddAfter(ILightPhysClass ^obj, ILightPhysClass ^existingListMember) { if (obj == nullptr || obj->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("obj"); } else if (existingListMember == nullptr || existingListMember->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("existingListMember"); } return InternalLightPhysClassRefMultiListClassPointer->Add_After( reinterpret_cast<::LightPhysClass *>(obj->LightPhysClassPointer.ToPointer()), reinterpret_cast<::LightPhysClass *>(existingListMember->LightPhysClassPointer.ToPointer())); } bool LightPhysClassRefMultiListClass::ReleaseHead() { return InternalLightPhysClassRefMultiListClassPointer->Release_Head(); } ILightPhysClass ^LightPhysClassRefMultiListClass::GetHead() { auto result = InternalLightPhysClassRefMultiListClassPointer->Get_Head(); if (result == nullptr) { return nullptr; } else { return safe_cast<ILightPhysClass^>(PhysClass::CreatePhysClassWrapper(result)); } } ILightPhysClass ^LightPhysClassRefMultiListClass::PeekHead() { auto result = InternalLightPhysClassRefMultiListClassPointer->Peek_Head(); if (result == nullptr) { return nullptr; } else { return safe_cast<ILightPhysClass^>(PhysClass::CreatePhysClassWrapper(result)); } } ILightPhysClass ^LightPhysClassRefMultiListClass::RemoveHead() { auto result = InternalLightPhysClassRefMultiListClassPointer->Remove_Head(); if (result == nullptr) { return nullptr; } else { return safe_cast<ILightPhysClass^>(PhysClass::CreatePhysClassWrapper(result)); } } void LightPhysClassRefMultiListClass::ResetList() { InternalLightPhysClassRefMultiListClassPointer->Reset_List(); } bool LightPhysClassRefMultiListClass::Remove(ILightPhysClass ^item) { if (item == nullptr || item->LightPhysClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("item"); } return InternalLightPhysClassRefMultiListClassPointer->Remove( reinterpret_cast<::LightPhysClass *>(item->LightPhysClassPointer.ToPointer())); } IntPtr LightPhysClassRefMultiListClass::LightPhysClassRefMultiListClassPointer::get() { return IntPtr(InternalLightPhysClassRefMultiListClassPointer); } IUnmanagedContainer<IRefMultiListIterator<ILightPhysClass ^> ^> ^LightPhysClassRefMultiListClass::Iterator::get() { return LightPhysClassRefMultiListIterator::CreateLightPhysClassRefMultiListIterator(this); } bool LightPhysClassRefMultiListClass::InternalDestroyPointer() { Imports::DestroyLightPhysClassRefMultiListClass(InternalLightPhysClassRefMultiListClassPointer); Pointer = IntPtr::Zero; return true; } ::GenericMultiListClass* LightPhysClassRefMultiListClass::InternalGenericMultiListClassPointer::get() { return InternalLightPhysClassRefMultiListClassPointer; } ::RefMultiListClass<::LightPhysClass> *LightPhysClassRefMultiListClass::InternalLightPhysClassRefMultiListClassPointer::get() { return reinterpret_cast<::RefMultiListClass<::LightPhysClass> *>(Pointer.ToPointer()); } LightPhysClassRefMultiListIterator::LightPhysClassRefMultiListIterator(IRefMultiListClass<ILightPhysClass ^> ^list) { if (list == nullptr || list->Pointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("list"); } Pointer = IntPtr(Imports::CreateLightPhysClassRefMultiListIterator( reinterpret_cast<::RefMultiListClass<::LightPhysClass> *>(list->Pointer.ToPointer()))); } LightPhysClassRefMultiListIterator::LightPhysClassRefMultiListIterator(IntPtr pointer) : RefMultiListIterator<ILightPhysClass ^>(pointer) { } IUnmanagedContainer<IRefMultiListIterator<ILightPhysClass ^> ^> ^LightPhysClassRefMultiListIterator::CreateLightPhysClassRefMultiListIterator( IRefMultiListClass<ILightPhysClass ^> ^list) { return gcnew UnmanagedContainer<IRefMultiListIterator<ILightPhysClass ^> ^>(gcnew LightPhysClassRefMultiListIterator(list)); } ILightPhysClass ^LightPhysClassRefMultiListIterator::GetObj() { auto result = InternalLightPhysClassRefMultiListIteratorPointer->Get_Obj(); if (result == nullptr) { return nullptr; } else { return safe_cast<ILightPhysClass^>(PhysClass::CreatePhysClassWrapper(result)); } } ILightPhysClass ^LightPhysClassRefMultiListIterator::PeekObj() { auto result = InternalLightPhysClassRefMultiListIteratorPointer->Peek_Obj(); if (result == nullptr) { return nullptr; } else { return safe_cast<ILightPhysClass^>(PhysClass::CreatePhysClassWrapper(result)); } } void LightPhysClassRefMultiListIterator::RemoveCurrentObject() { InternalLightPhysClassRefMultiListIteratorPointer->Remove_Current_Object(); } IntPtr LightPhysClassRefMultiListIterator::LightPhysClassRefMultiListIteratorPointer::get() { return IntPtr(InternalLightPhysClassRefMultiListIteratorPointer); } bool LightPhysClassRefMultiListIterator::InternalDestroyPointer() { Imports::DestroyLightPhysClassRefMultiListIterator(InternalLightPhysClassRefMultiListIteratorPointer); Pointer = IntPtr::Zero; return true; } ::RefMultiListIterator<::LightPhysClass> *LightPhysClassRefMultiListIterator::InternalLightPhysClassRefMultiListIteratorPointer::get() { return reinterpret_cast<::RefMultiListIterator<::LightPhysClass> *>(Pointer.ToPointer()); } }
31.288321
143
0.787239
mpforums
cafa5426a3b859ccfd944cf9a6c09861bc5ce164
11,808
hpp
C++
control/json/actions/action.hpp
ibm-openbmc/phosphor-fan-presence
a899aa0cbdb7904d177fc5bb85aa605e4ff13747
[ "Apache-2.0" ]
null
null
null
control/json/actions/action.hpp
ibm-openbmc/phosphor-fan-presence
a899aa0cbdb7904d177fc5bb85aa605e4ff13747
[ "Apache-2.0" ]
null
null
null
control/json/actions/action.hpp
ibm-openbmc/phosphor-fan-presence
a899aa0cbdb7904d177fc5bb85aa605e4ff13747
[ "Apache-2.0" ]
1
2019-09-27T15:20:57.000Z
2019-09-27T15:20:57.000Z
/** * Copyright © 2022 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "../utils/flight_recorder.hpp" #include "../zone.hpp" #include "config_base.hpp" #include "group.hpp" #include <fmt/format.h> #include <nlohmann/json.hpp> #include <phosphor-logging/log.hpp> #include <algorithm> #include <functional> #include <iterator> #include <map> #include <memory> #include <numeric> namespace phosphor::fan::control::json { using json = nlohmann::json; using namespace phosphor::logging; /** * @class ActionParseError - A parsing error exception * * A parsing error exception that can be used to terminate the application * due to not being able to successfully parse a configured action. */ class ActionParseError : public std::runtime_error { public: ActionParseError() = delete; ActionParseError(const ActionParseError&) = delete; ActionParseError(ActionParseError&&) = delete; ActionParseError& operator=(const ActionParseError&) = delete; ActionParseError& operator=(ActionParseError&&) = delete; ~ActionParseError() = default; /** * @brief Action parsing error object * * When parsing an action from the JSON configuration, any critical * attributes that fail to be parsed for an action can throw an * ActionParseError exception to log the parsing failure details and * terminate the application. * * @param[in] name - Name of the action * @param[in] details - Additional details of the parsing error */ ActionParseError(const std::string& name, const std::string& details) : std::runtime_error( fmt::format("Failed to parse action {} [{}]", name, details) .c_str()) {} }; /** * @brief Function used in creating action objects * * @param[in] jsonObj - JSON object for the action * @param[in] groups - Groups of dbus objects the action uses * @param[in] zones - Zones the action runs against * * Creates an action object given the JSON configuration, list of groups and * sets the zones the action should run against. */ template <typename T> std::unique_ptr<T> createAction(const json& jsonObj, const std::vector<Group>& groups, std::vector<std::reference_wrapper<Zone>>& zones) { // Create the action and set its list of zones auto action = std::make_unique<T>(jsonObj, groups); action->setZones(zones); return action; } /** * @class ActionBase - Base action object * * Base class for fan control's event actions */ class ActionBase : public ConfigBase { public: ActionBase() = delete; ActionBase(const ActionBase&) = delete; ActionBase(ActionBase&&) = delete; ActionBase& operator=(const ActionBase&) = delete; ActionBase& operator=(ActionBase&&) = delete; virtual ~ActionBase() = default; /** * @brief Base action object * * @param[in] jsonObj - JSON object containing name and any profiles * @param[in] groups - Groups of dbus objects the action uses * * All actions derived from this base action object must be given a name * that uniquely identifies the action. Optionally, a configured action can * have a list of explicit profiles it should be included in, otherwise * always include the action where no profiles are given. */ ActionBase(const json& jsonObj, const std::vector<Group>& groups) : ConfigBase(jsonObj), _groups(groups), _uniqueName(getName() + "-" + std::to_string(_actionCount++)) {} /** * @brief Get the groups configured on the action * * @return List of groups */ inline const auto& getGroups() const { return _groups; } /** * @brief Set the zones the action is run against * * @param[in] zones - Zones the action runs against * * By default, the zones are set when the action object is created */ virtual void setZones(std::vector<std::reference_wrapper<Zone>>& zones) { _zones = zones; } /** * @brief Add a zone to the list of zones the action is run against if its * not already there * * @param[in] zone - Zone to add */ virtual void addZone(Zone& zone) { auto itZone = std::find_if(_zones.begin(), _zones.end(), [&zone](std::reference_wrapper<Zone>& z) { return z.get().getName() == zone.getName(); }); if (itZone == _zones.end()) { _zones.emplace_back(std::reference_wrapper<Zone>(zone)); } } /** * @brief Run the action * * Run the action function associated to the derived action object * that performs a specific tasks on a zone configured by a user. * * @param[in] zone - Zone to run the action on */ virtual void run(Zone& zone) = 0; /** * @brief Trigger the action to run against all of its zones * * This is the function used by triggers to run the actions against all the * zones that were configured for the action to run against. */ void run() { std::for_each(_zones.begin(), _zones.end(), [this](Zone& zone) { this->run(zone); }); } /** * @brief Returns a unique name for the action. * * @return std::string - The name */ const std::string& getUniqueName() const { return _uniqueName; } /** * @brief Set the name of the owning Event. * * Adds it to the unique name in parentheses. If desired, * the action child classes can do something else with it. * * @param[in] name - The event name */ virtual void setEventName(const std::string& name) { if (!name.empty()) { _uniqueName += '(' + name + ')'; } } /** * @brief Dump the action as JSON * * For now just dump its group names * * @return json */ json dump() const { json groups = json::array(); std::for_each(_groups.begin(), _groups.end(), [&groups](const auto& group) { groups.push_back(group.getName()); }); json output; output["groups"] = groups; return output; } protected: /** * @brief Logs a message to the flight recorder using * the unique name of the action. * * @param[in] message - The message to log */ void record(const std::string& message) const { FlightRecorder::instance().log(getUniqueName(), message); } /* Groups configured on the action */ const std::vector<Group> _groups; private: /* Zones configured on the action */ std::vector<std::reference_wrapper<Zone>> _zones; /* Unique name of the action. * It's just the name plus _actionCount at the time of action creation. */ std::string _uniqueName; /* Running count of all actions */ static inline size_t _actionCount = 0; }; /** * @class ActionFactory - Factory for actions * * Factory that registers and retrieves actions based on a given name. */ class ActionFactory { public: ActionFactory() = delete; ActionFactory(const ActionFactory&) = delete; ActionFactory(ActionFactory&&) = delete; ActionFactory& operator=(const ActionFactory&) = delete; ActionFactory& operator=(ActionFactory&&) = delete; ~ActionFactory() = default; /** * @brief Registers an action * * Registers an action as being available for configuration use. The action * is registered by its name and a function used to create the action * object. An action fails to be registered when another action of the same * name has already been registered. Actions with the same name would cause * undefined behavior, therefore are not allowed. * * Actions are registered prior to starting main(). * * @param[in] name - Name of the action to register * * @return The action was registered, otherwise an exception is thrown. */ template <typename T> static bool regAction(const std::string& name) { auto it = actions.find(name); if (it == actions.end()) { actions[name] = &createAction<T>; } else { log<level::ERR>( fmt::format("Action '{}' is already registered", name).c_str()); throw std::runtime_error("Actions with the same name found"); } return true; } /** * @brief Gets a registered action's object * * Gets a registered action's object of a given name from the JSON * configuration data provided. * * @param[in] name - Name of the action to create/get * @param[in] jsonObj - JSON object for the action * @param[in] groups - Groups of dbus objects the action uses * @param[in] zones - Zones the action runs against * * @return Pointer to the action object. */ static std::unique_ptr<ActionBase> getAction(const std::string& name, const json& jsonObj, const std::vector<Group>& groups, std::vector<std::reference_wrapper<Zone>>&& zones) { auto it = actions.find(name); if (it != actions.end()) { return it->second(jsonObj, groups, zones); } else { // Construct list of available actions auto acts = std::accumulate( std::next(actions.begin()), actions.end(), actions.begin()->first, [](auto list, auto act) { return std::move(list) + ", " + act.first; }); log<level::ERR>( fmt::format("Action '{}' is not registered", name).c_str(), entry("AVAILABLE_ACTIONS=%s", acts.c_str())); throw std::runtime_error("Unsupported action name given"); } } private: /* Map to store the available actions and their creation functions */ static inline std::map<std::string, std::function<std::unique_ptr<ActionBase>( const json&, const std::vector<Group>&, std::vector<std::reference_wrapper<Zone>>&)>> actions; }; /** * @class ActionRegister - Registers an action class * * Base action registration class that is extended by an action object so * that action is registered and available for use. */ template <typename T> class ActionRegister { public: ActionRegister(const ActionRegister&) = delete; ActionRegister(ActionRegister&&) = delete; ActionRegister& operator=(const ActionRegister&) = delete; ActionRegister& operator=(ActionRegister&&) = delete; virtual ~ActionRegister() = default; ActionRegister() { // Templates instantiated when used, need to assign a value // here so the compiler doesnt remove it registered = true; } private: /* Register actions in the factory */ static inline bool registered = ActionFactory::regAction<T>(T::name); }; } // namespace phosphor::fan::control::json
30.67013
80
0.615684
ibm-openbmc
1b00a7478640dc8659f0435fc32c0f77c9bbc9e2
3,566
cpp
C++
src/bvh_converter.cpp
lasagnaphil/c3d-to-bvh
cbb10c6e0207aa9c47b54359f785a2e6b78989c1
[ "MIT" ]
2
2020-04-21T12:24:09.000Z
2021-08-12T02:56:55.000Z
src/bvh_converter.cpp
lasagnaphil/c3d-to-bvh
cbb10c6e0207aa9c47b54359f785a2e6b78989c1
[ "MIT" ]
null
null
null
src/bvh_converter.cpp
lasagnaphil/c3d-to-bvh
cbb10c6e0207aa9c47b54359f785a2e6b78989c1
[ "MIT" ]
2
2021-06-29T11:46:06.000Z
2021-08-12T02:57:00.000Z
// // Created by lasagnaphil on 19. 11. 11.. // #include <iostream> #include <random> #include <regex> #include "imguix/imgui_plot.h" #include <MotionClipData.h> #include "App.h" #include "GizmosRenderer.h" #include "PhongRenderer.h" #include "c3d/PointMotionClip.h" #include "filesystem.h" namespace fs = std::filesystem; // #define SPLIT_CYCLES // #define OUTPUT_PHASE int main(int argc, char **argv) { if (argc != 3) { fmt::print("Usage: {} <input_c3d_folder> <output_bvh_folder>\n", argv[0]); exit(0); } std::string c3dDirectory = argv[1]; std::string bvhDirectory = argv[2]; auto c3dFiles = std::vector<fs::directory_entry>( fs::directory_iterator(c3dDirectory), fs::directory_iterator()); std::sort(c3dFiles.begin(), c3dFiles.end()); std::vector<ga::PointMotionClip> clips; clips.reserve(c3dFiles.size()); std::map<std::string, ga::PointMotionClip> refClips; for (auto& c3dFile : c3dFiles) { bool valid; auto clip = ga::PointMotionClip::fromC3D(c3dFile.path(), ga::MarkerType::Vicon, &valid); if (!valid) continue; clip.rescale(0.001f); auto namePrefix = clip.name.substr(0, 5); if (clip.isRefClip()) { if (clip.checkValidity() && refClips.count(namePrefix) == 0) { refClips[namePrefix] = clip; } continue; } clip.strip(); clip.fillInvalidPoints(); clip.smooth(); #ifdef SPLIT_CYCLES auto splitClips = clip.splitCycles(); for (auto& c : splitClips) { c.setRootToOrigin(); } clips.insert(clips.end(), splitClips.begin(), splitClips.end()); #else clip.setRootToOrigin(); clips.push_back(clip); #endif } #ifdef OUTPUT_PHASE std::ofstream ofs("phase_data.tsv"); #endif #ifdef SPLIT_CYCLES fs::create_directory("bvh"); #else fs::create_directory(bvhDirectory); #endif int refValid = 0, refInvalid = 0; for (auto& clip : clips) { auto refClipIt = refClips.find(clip.name.substr(0, 5)); ga::PointMotionClip refClip; if (refClipIt == refClips.end()) { fmt::print("Couldn't find reference clip for {}! Using self as reference.\n", clip.name); refInvalid++; refClip = clip; } else { refValid++; refClip = refClipIt->second; } #ifdef OUTPUT_PHASE ofs << clip.name << "\t" << clip.frame_cnt << "\t" << clip.midPhaseIdx << std::endl; #endif auto bvh = ga::convertToLowerBodyBVH(refClip, clip); #ifndef SPLIT_CYCLES // If not splitting cycles, make sure exported clip isn't too short or too long uint32_t minNumFrames = 30, maxNumFrames = 300; if (bvh.numFrames < minNumFrames || bvh.numFrames > maxNumFrames) { fmt::print("Result BVH {} is too long or too short! (frame_cnt = {})\n", clip.name, bvh.numFrames); continue; } #endif if (bvh.checkValidity()) { #ifdef SPLIT_CYCLES bvh.saveToFile("datasets/hospital/bvh/" + clip.name + ".bvh", EulOrdXYZs); #else bvh.saveToFile(std::string(argv[2]) + "/" + clip.name + ".bvh", EulOrdXYZs); #endif fmt::print("Converted {} with reference clip {}!\n", clip.name, refClip.name); } else { fmt::print("Result BVH {} is invalid!\n", clip.name); } } fmt::print("Statistics:\n"); fmt::print("valid = {}, invalid = {}\n", refValid, refInvalid); return 0; }
28.528
111
0.592821
lasagnaphil
1b0964323e5667bad8dddb2a54b342e789fad456
4,345
cc
C++
python/dune/gdt/prolongations.cc
pymor/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
4
2018-10-12T21:46:08.000Z
2020-08-01T18:54:02.000Z
python/dune/gdt/prolongations.cc
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
154
2016-02-16T13:50:54.000Z
2021-12-13T11:04:29.000Z
python/dune/gdt/prolongations.cc
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
5
2016-03-02T10:11:20.000Z
2020-02-08T03:56:24.000Z
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2020) #include "config.h" #include <dune/pybindxi/pybind11.h> #include <dune/pybindxi/stl.h> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/grid/grids.hh> #include <dune/xt/grid/gridprovider/provider.hh> #include <dune/xt/la/type_traits.hh> #include <dune/gdt/prolongations.hh> #include <python/dune/xt/common/configuration.hh> #include <python/dune/xt/common/fvector.hh> #include <python/dune/xt/common/parameter.hh> #include <python/dune/xt/grid/grids.bindings.hh> #include <python/dune/xt/grid/walker.hh> #include <python/dune/xt/la/traits.hh> namespace Dune { namespace GDT { namespace bindings { template <class V, class VectorTag, class GV, size_t r = 1> class prolong { using G = std::decay_t<XT::Grid::extract_grid_t<GV>>; static const size_t d = G::dimension; using GP = XT::Grid::GridProvider<G>; using E = XT::Grid::extract_entity_t<GV>; using DF = DiscreteFunction<V, GV, r>; using S = typename DF::SpaceType; public: static void bind(pybind11::module& m, const std::string& function_id = "prolong") { namespace py = pybind11; using namespace pybind11::literals; m.def( function_id.c_str(), [](const DF& source, DF& target) { GDT::prolong(source, target); }, "source"_a, "target"_a, py::call_guard<py::gil_scoped_release>()); if (std::is_same<VectorTag, XT::LA::bindings::Istl>::value) m.def( function_id.c_str(), [](const DF& source, const S& target_space, const VectorTag&) { return GDT::prolong<V>(source, target_space); }, "source"_a, "target"_a, "la_backend"_a = XT::LA::bindings::Istl(), py::call_guard<py::gil_scoped_release>()); else m.def( function_id.c_str(), [](const DF& source, const S& target_space, const VectorTag&) { return GDT::prolong<V>(source, target_space); }, "source"_a, "target"_a, "la_backend"_a, py::call_guard<py::gil_scoped_release>()); } // ... bind(...) }; // class prolong } // namespace bindings } // namespace GDT } // namespace Dune template <class V, class VT, class GridTypes = Dune::XT::Grid::bindings::AvailableGridTypes> struct prolong_for_all_grids { using G = Dune::XT::Common::tuple_head_t<GridTypes>; using GV = typename G::LeafGridView; static const constexpr size_t d = G::dimension; static void bind(pybind11::module& m) { using Dune::GDT::bindings::prolong; prolong<V, VT, GV>::bind(m); if (d > 1) prolong<V, VT, GV, d>::bind(m); // add your extra dimensions here // ... prolong_for_all_grids<V, VT, Dune::XT::Common::tuple_tail_t<GridTypes>>::bind(m); } }; template <class V, class VT> struct prolong_for_all_grids<V, VT, Dune::XT::Common::tuple_null_type> { static void bind(pybind11::module& /*m*/) {} }; PYBIND11_MODULE(_prolongations, m) { namespace py = pybind11; using namespace Dune; using namespace Dune::XT; using namespace Dune::GDT; py::module::import("dune.xt.common"); py::module::import("dune.xt.la"); py::module::import("dune.xt.grid"); py::module::import("dune.xt.functions"); py::module::import("dune.gdt._discretefunction_discretefunction"); py::module::import("dune.gdt._spaces_interface"); #if 0 // bindings for all but dune-istl disabled for the moment prolong_for_all_grids<LA::CommonDenseVector<double>, LA::bindings::Common, XT::Grid::bindings::AvailableGridTypes>::bind(m); # if HAVE_EIGEN prolong_for_all_grids<LA::EigenDenseVector<double>, LA::bindings::Eigen, XT::Grid::bindings::AvailableGridTypes>:: bind(m); # endif #endif // 0 prolong_for_all_grids<LA::IstlDenseVector<double>, LA::bindings::Istl, XT::Grid::bindings::AvailableGridTypes>::bind( m); }
30.815603
119
0.654085
pymor
db43fa54955a0edc604797ca9840f0f9dcc1f7fa
785
cpp
C++
Source/HeatCool/integrate_state_vec_3d_stubs.cpp
zingale/Nyx
d0dd183748e85615e32c327004d540d6ad3069c7
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/HeatCool/integrate_state_vec_3d_stubs.cpp
zingale/Nyx
d0dd183748e85615e32c327004d540d6ad3069c7
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/HeatCool/integrate_state_vec_3d_stubs.cpp
zingale/Nyx
d0dd183748e85615e32c327004d540d6ad3069c7
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <fstream> #include <iomanip> #include <AMReX_ParmParse.H> #include <AMReX_Geometry.H> #include <AMReX_MultiFab.H> #include <AMReX_Print.H> #include <AMReX_PlotFileUtil.H> #include <AMReX_BLFort.H> #include <Nyx.H> using namespace amrex; /* Private function to check function return values */ static int check_retval(void *flagvalue, const char *funcname, int opt); int Nyx::integrate_state_vec (amrex::MultiFab &S_old, amrex::MultiFab &D_old, const Real& a, const Real& delta_time) { amrex::Abort("Using stubs file for heat_cool_type=11"); return 0; } int Nyx::integrate_state_grownvec (amrex::MultiFab &S_old, amrex::MultiFab &D_old, const Real& a, const Real& delta_time) { amrex::Abort("Using stubs file for heat_cool_type=11"); return 0; }
21.216216
72
0.73121
zingale
db45486f46c4f164cd307f0214270a5a4c4612da
788
cpp
C++
code/3rd-party/imdexlib/tests/string_ref-test.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/3rd-party/imdexlib/tests/string_ref-test.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/3rd-party/imdexlib/tests/string_ref-test.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <imdexlib/string_ref.hpp> using namespace imdex; using namespace testing; using namespace std::string_literals; TEST(StringRefTest, EmptinessTest) { EXPECT_EQ(string_ref(), ""); EXPECT_EQ(string_ref(), ""s); EXPECT_TRUE(string_ref().empty()); EXPECT_FALSE(string_ref().nonEmpty()); } TEST(StringRefTest, CStringTest) { string_ref ref = "static str"; EXPECT_EQ(ref, "static str"); EXPECT_EQ(ref.c_str(), "static str"); } TEST(StringRefTest, StdStringTest) { auto str = "std::string"s; string_ref ref = str; EXPECT_EQ(ref, str); EXPECT_EQ(ref.c_str(), str.c_str()); } TEST(StringRefTest, UserDefinedLiteralTest) { auto ref = "static_str"_sr; EXPECT_EQ(ref, "static_str"); }
23.878788
45
0.687817
InNoHurryToCode
db4df42413a131a63df58fe7e80328fc2e65c16a
1,859
hh
C++
main/src/Geo/plane_fitting.hh
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/Geo/plane_fitting.hh
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/Geo/plane_fitting.hh
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "vector.hh" #include <memory> namespace Geo { /*! Finds the best plane for N 3d points (the pane that minimize the square distance of any point from the plane. */ struct IPlaneFit { /*!Set the expected number of points to be considered for minimum distance. It must not be smaller than the number of points added with add_point. */ virtual void init(size_t _size) = 0; /*!Set a new point. */ virtual void add_point(const VectorD3& _pt) = 0; /*!Computes the best plane as the plane passing for the _center with the given normal. The normal is a unit vector. */ virtual bool compute( VectorD3& _center, VectorD3& _normal, const bool _orient = false) = 0; /*! Factory */ static std::shared_ptr<IPlaneFit> make(); }; /*! Retun the normal of the best plane in a set of points. The normal is such that looking at the polygon from the normal direction it runs in counterclockwise direction. */ template <class VertexIteratorT> Geo::VectorD3 vertex_polygon_normal(VertexIteratorT _beg, VertexIteratorT _end) { auto pl_fit = Geo::IPlaneFit::make(); pl_fit->init(_end - _beg); for (auto vert_it = _beg; vert_it != _end; ++vert_it) { Geo::VectorD3 pt; (*vert_it)->geom(pt); pl_fit->add_point(pt); } Geo::VectorD3 c, n; pl_fit->compute(c, n, true); return n; } template <class PointIteratorT> Geo::VectorD3 point_polygon_normal( PointIteratorT _beg, PointIteratorT _end, Geo::VectorD3* _centr = nullptr) { auto pl_fit = Geo::IPlaneFit::make(); pl_fit->init(_end - _beg); for (auto pt_it = _beg; pt_it != _end; ++pt_it) pl_fit->add_point(*pt_it); Geo::VectorD3 c, n; pl_fit->compute(c, n, true); if (_centr != nullptr) *_centr = c; return n; } }//namespace Geo
25.465753
80
0.658419
marcomanno
db518c13f9e5e8995a973a92ee319d28dbd513df
67
cpp
C++
src/tree/SplayTree.cpp
vtta/libds
2356b4b1a79994ac231681e2dbd1b0fffd61ebca
[ "Unlicense" ]
null
null
null
src/tree/SplayTree.cpp
vtta/libds
2356b4b1a79994ac231681e2dbd1b0fffd61ebca
[ "Unlicense" ]
null
null
null
src/tree/SplayTree.cpp
vtta/libds
2356b4b1a79994ac231681e2dbd1b0fffd61ebca
[ "Unlicense" ]
null
null
null
// // Created by vtta 🍉 on 2020/1/16. // #include "SplayTree.hpp"
11.166667
34
0.61194
vtta
db58cf4e76d60b3f79dfb9240fdb107198464e02
1,017
cpp
C++
array-and-string/introduction-to-string/add-binary.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
array-and-string/introduction-to-string/add-binary.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
array-and-string/introduction-to-string/add-binary.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string addBinary(string a, string b) { string added; for (int ai = a.size() - 1, bi = b.size() - 1, carry = 0, curr_digit = 0; ai >= 0 or bi >= 0 or carry; added.push_back('0' + curr_digit), curr_digit = carry) { carry = 0; if (ai >= 0) curr_digit += a[ai--] - '0'; if (bi >= 0) curr_digit += b[bi--] - '0'; if (curr_digit > 1) { curr_digit -= 2; ++carry; } } reverse(added.begin(), added.end()); return added; } }; int main() { Solution s; string A1 = "11", B1 = "1"; cout << "11 + 1 => 100: " << s.addBinary(A1, B1) << endl; string A2 = "1010", B2 = "1011"; cout << "1010 + 1011 => 10101: " << s.addBinary(A2, B2) << endl; string A3 = "1", B3 = "1"; cout << "1 + 1 => 10: " << s.addBinary(A3, B3) << endl; string A4 = "1", B4 = "100001"; cout << "1 + 100001 => 100010: " << s.addBinary(A4, B4) << endl; return 0; }
25.425
165
0.518191
lpapp
db5a0cc481ded5de29a40ae70ce2fb8410a31ce8
2,310
cpp
C++
src/single_net/GridGraphBuilderBase.cpp
jacky860226/dr-cu
cd3f2f98a9bb4eb6a6531369018e3f1616a58642
[ "Unlicense" ]
1
2021-01-30T07:41:31.000Z
2021-01-30T07:41:31.000Z
src/single_net/GridGraphBuilderBase.cpp
jacky860226/dr-cu
cd3f2f98a9bb4eb6a6531369018e3f1616a58642
[ "Unlicense" ]
null
null
null
src/single_net/GridGraphBuilderBase.cpp
jacky860226/dr-cu
cd3f2f98a9bb4eb6a6531369018e3f1616a58642
[ "Unlicense" ]
null
null
null
#include "GridGraphBuilderBase.h" #include "PinTapConnector.h" DBU GridGraphBuilderBase::getPinPointDist(const vector<db::BoxOnLayer> &accessBoxes, const db::GridPoint &grid) { auto point = database.getLoc(grid); DBU minDist = std::numeric_limits<DBU>::max() / 10; // make it safe for adding in case no same-layer box for (const auto &box : accessBoxes) { if (box.layerIdx != grid.layerIdx) continue; DBU dist = Dist(box, point); if (dist < minDist) { minDist = dist; } } return minDist; } void GridGraphBuilderBase::updatePinVertex(int pinIdx, int vertexIdx) { auto it = graph.vertexToPin.find(vertexIdx); if (it != graph.vertexToPin.end()) { int oriPinIdx = it->second; if (pinIdx != oriPinIdx) { auto point = vertexToGridPoint[vertexIdx]; DBU oriDist = getPinPointDist(localNet.pinAccessBoxes[oriPinIdx], point); DBU newDist = getPinPointDist(localNet.pinAccessBoxes[pinIdx], point); if (newDist < oriDist) { graph.vertexToPin[vertexIdx] = pinIdx; auto &oriPinToVertex = graph.pinToVertex[oriPinIdx]; auto oriIt = find(oriPinToVertex.begin(), oriPinToVertex.end(), vertexIdx); assert(oriIt != oriPinToVertex.end()); *oriIt = oriPinToVertex.back(); oriPinToVertex.pop_back(); graph.pinToVertex[pinIdx].push_back(vertexIdx); } } } else { graph.vertexToPin[vertexIdx] = pinIdx; graph.pinToVertex[pinIdx].push_back(vertexIdx); } } void GridGraphBuilderBase::addOutofPinPenalty() { for (unsigned p = 0; p < localNet.numOfPins(); p++) { for (auto vertex : graph.pinToVertex[p]) { graph.vertexCost[vertex] += getPinPointDist(localNet.dbNet.pinAccessBoxes[p], vertexToGridPoint[vertex]) * outOfPinWireLengthPenalty; PinTapConnector pinTapConnector(vertexToGridPoint[vertex], localNet.dbNet, p); if (pinTapConnector.bestVio > 0) { graph.vertexCost[vertex] += database.getUnitSpaceVioCost(); } // Note: before fixing (removing redundant pinToVertex), charged multiple times } } }
42
118
0.61645
jacky860226
db60fa0ebbaedd970814294220ffe33263388a5e
9,697
cpp
C++
lgc/builder/BuilderBase.cpp
Sisyph/llpc
719c9414987921159200729e78ecf1c2e98dd420
[ "MIT" ]
112
2018-07-02T06:56:25.000Z
2022-02-08T12:07:19.000Z
lgc/builder/BuilderBase.cpp
Sisyph/llpc
719c9414987921159200729e78ecf1c2e98dd420
[ "MIT" ]
1,612
2018-07-04T19:08:21.000Z
2022-03-31T23:24:55.000Z
lgc/builder/BuilderBase.cpp
vettoreldaniele/llpc
41fd5608f7b697c1416b983b89b2f62f0907d4a3
[ "MIT" ]
114
2018-07-04T18:47:13.000Z
2022-03-30T19:53:19.000Z
/* *********************************************************************************************************************** * * Copyright (c) 2020-2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file BuilderBase.cpp * @brief LLPC source file: implementation of BuilderBase *********************************************************************************************************************** */ #include "lgc/util/BuilderBase.h" #include "llvm/IR/IntrinsicsAMDGPU.h" using namespace lgc; using namespace llvm; // ===================================================================================================================== // Create an LLVM function call to the named function. The callee is built automically based on return // type and its parameters. // // @param funcName : Name of the callee // @param retTy : Return type of the callee // @param args : Arguments to pass to the callee // @param attribs : Function attributes // @param instName : Name to give instruction CallInst *BuilderCommon::CreateNamedCall(StringRef funcName, Type *retTy, ArrayRef<Value *> args, ArrayRef<Attribute::AttrKind> attribs, const Twine &instName) { Module *module = GetInsertBlock()->getParent()->getParent(); Function *func = dyn_cast_or_null<Function>(module->getFunction(funcName)); if (!func) { SmallVector<Type *, 8> argTys; argTys.reserve(args.size()); for (auto arg : args) argTys.push_back(arg->getType()); auto funcTy = FunctionType::get(retTy, argTys, false); func = Function::Create(funcTy, GlobalValue::ExternalLinkage, funcName, module); func->setCallingConv(CallingConv::C); func->addFnAttr(Attribute::NoUnwind); for (auto attrib : attribs) func->addFnAttr(attrib); } auto call = CreateCall(func, args, instName); call->setCallingConv(CallingConv::C); call->setAttributes(func->getAttributes()); return call; } // ===================================================================================================================== // Emits a amdgcn.reloc.constant intrinsic that represents a relocatable i32 value with the given symbol name // // @param symbolName : Name of the relocation symbol associated with this relocation Value *BuilderBase::CreateRelocationConstant(const Twine &symbolName) { auto mdNode = MDNode::get(getContext(), MDString::get(getContext(), symbolName.str())); return CreateIntrinsic(Intrinsic::amdgcn_reloc_constant, {}, {MetadataAsValue::get(getContext(), mdNode)}); } // ===================================================================================================================== // Generate an add of an offset to a byte pointer. This is provided to use in the case that the offset is, // or might be, a relocatable value, as it implements a workaround to get more efficient code for the load // that uses the offset pointer. // // @param pointer : Pointer to add to // @param byteOffset : Byte offset to add // @param instName : Name to give instruction Value *BuilderBase::CreateAddByteOffset(Value *pointer, Value *byteOffset, const Twine &instName) { if (auto call = dyn_cast<CallInst>(byteOffset)) { if (call->getIntrinsicID() == Intrinsic::amdgcn_reloc_constant) { // Where the offset is the result of CreateRelocationConstant, // LLVM's internal handling of GEP instruction results in a lot of junk code and prevented selection // of the offset-from-register variant of the s_load_dwordx4 instruction. To workaround this issue, // we use integer arithmetic here so the amdgpu backend can pickup the optimal instruction. // TODO: Figure out how to fix this properly, then remove this function and switch its users to // use a simple CreateGEP instead. Type *origPointerTy = pointer->getType(); pointer = CreatePtrToInt(pointer, getInt64Ty()); pointer = CreateAdd(pointer, CreateZExt(byteOffset, getInt64Ty()), instName); return CreateIntToPtr(pointer, origPointerTy); } } return CreateGEP(getInt8Ty(), pointer, byteOffset, instName); } // ===================================================================================================================== // Create a map to i32 function. Many AMDGCN intrinsics only take i32's, so we need to massage input data into an i32 // to allow us to call these intrinsics. This helper takes a function pointer, massage arguments, and passthrough // arguments and massages the mappedArgs into i32's before calling the function pointer. Note that all massage // arguments must have the same type. // // @param mapFunc : The function to call on each provided i32. // @param mappedArgs : The arguments to be massaged into i32's and passed to function. // @param passthroughArgs : The arguments to be passed through as is (no massaging). Value *BuilderBase::CreateMapToInt32(MapToInt32Func mapFunc, ArrayRef<Value *> mappedArgs, ArrayRef<Value *> passthroughArgs) { // We must have at least one argument to massage. assert(mappedArgs.size() > 0); Type *const type = mappedArgs[0]->getType(); // Check the massage types all match. for (unsigned i = 1; i < mappedArgs.size(); i++) assert(mappedArgs[i]->getType() == type); if (mappedArgs[0]->getType()->isVectorTy()) { // For vectors we extract each vector component and map them individually. const unsigned compCount = cast<FixedVectorType>(type)->getNumElements(); SmallVector<Value *, 4> results; for (unsigned i = 0; i < compCount; i++) { SmallVector<Value *, 4> newMappedArgs; for (Value *const mappedArg : mappedArgs) newMappedArgs.push_back(CreateExtractElement(mappedArg, i)); results.push_back(CreateMapToInt32(mapFunc, newMappedArgs, passthroughArgs)); } Value *result = UndefValue::get(FixedVectorType::get(results[0]->getType(), compCount)); for (unsigned i = 0; i < compCount; i++) result = CreateInsertElement(result, results[i], i); return result; } else if (type->isIntegerTy() && type->getIntegerBitWidth() == 1) { SmallVector<Value *, 4> newMappedArgs; for (Value *const mappedArg : mappedArgs) newMappedArgs.push_back(CreateZExt(mappedArg, getInt32Ty())); Value *const result = CreateMapToInt32(mapFunc, newMappedArgs, passthroughArgs); return CreateTrunc(result, getInt1Ty()); } else if (type->isIntegerTy() && type->getIntegerBitWidth() < 32) { SmallVector<Value *, 4> newMappedArgs; Type *const vectorType = FixedVectorType::get(type, type->getPrimitiveSizeInBits() == 16 ? 2 : 4); Value *const undef = UndefValue::get(vectorType); for (Value *const mappedArg : mappedArgs) { Value *const newMappedArg = CreateInsertElement(undef, mappedArg, static_cast<uint64_t>(0)); newMappedArgs.push_back(CreateBitCast(newMappedArg, getInt32Ty())); } Value *const result = CreateMapToInt32(mapFunc, newMappedArgs, passthroughArgs); return CreateExtractElement(CreateBitCast(result, vectorType), static_cast<uint64_t>(0)); } else if (type->getPrimitiveSizeInBits() == 64) { SmallVector<Value *, 4> castMappedArgs; for (Value *const mappedArg : mappedArgs) castMappedArgs.push_back(CreateBitCast(mappedArg, FixedVectorType::get(getInt32Ty(), 2))); Value *result = UndefValue::get(castMappedArgs[0]->getType()); for (unsigned i = 0; i < 2; i++) { SmallVector<Value *, 4> newMappedArgs; for (Value *const castMappedArg : castMappedArgs) newMappedArgs.push_back(CreateExtractElement(castMappedArg, i)); Value *const resultComp = CreateMapToInt32(mapFunc, newMappedArgs, passthroughArgs); result = CreateInsertElement(result, resultComp, i); } return CreateBitCast(result, type); } else if (type->isFloatingPointTy()) { SmallVector<Value *, 4> newMappedArgs; for (Value *const mappedArg : mappedArgs) newMappedArgs.push_back(CreateBitCast(mappedArg, getIntNTy(mappedArg->getType()->getPrimitiveSizeInBits()))); Value *const result = CreateMapToInt32(mapFunc, newMappedArgs, passthroughArgs); return CreateBitCast(result, type); } else if (type->isIntegerTy(32)) return mapFunc(*this, mappedArgs, passthroughArgs); else { llvm_unreachable("Should never be called!"); return nullptr; } }
47.072816
120
0.645664
Sisyph
db635b6fae4b1613134a71a127109df6b950600b
962
cpp
C++
fboss/lib/SnapshotManager.cpp
rsunkad/fboss
760255f88fdaeb7f12d092a41362acf1e9a45bbb
[ "BSD-3-Clause" ]
1
2021-08-21T08:14:07.000Z
2021-08-21T08:14:07.000Z
fboss/lib/SnapshotManager.cpp
rsunkad/fboss
760255f88fdaeb7f12d092a41362acf1e9a45bbb
[ "BSD-3-Clause" ]
1
2021-08-21T07:48:15.000Z
2021-08-21T07:48:15.000Z
fboss/lib/SnapshotManager.cpp
LaudateCorpus1/fboss
0e54a9ec6e80376356dfbf6b6ac46f196f1cb534
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/lib/SnapshotManager.h" #include "fboss/lib/AlertLogger.h" using namespace std::chrono; DEFINE_int32( link_snapshot_publish_interval, duration_cast<seconds>(std::chrono::hours(1)).count(), "Time interval between link snapshots (in seconds)"); namespace facebook::fboss { void SnapshotWrapper::publish() { auto serializedSnapshot = apache::thrift::SimpleJSONSerializer::serialize<std::string>(snapshot_); if (!published_) { XLOG(INFO) << LinkSnapshotAlert() << "Collected snapshot " << LinkSnapshotParam(serializedSnapshot); published_ = true; } } } // namespace facebook::fboss
28.294118
79
0.711019
rsunkad
db649449d4e94764ff15e29711d74faab8460629
28,379
cpp
C++
WaveletTL/adaptive/apply_tensor.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
WaveletTL/adaptive/apply_tensor.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
WaveletTL/adaptive/apply_tensor.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
// implementation for apply_tensor.h namespace WaveletTL { template <class PROBLEM> void APPLY_TENSOR(PROBLEM& P, const InfiniteVector<double, typename PROBLEM::Index>& v, const double eta, InfiniteVector<double, typename PROBLEM::Index>& w, const int jmax, const CompressionStrategy strategy, const bool preconditioning) { // Remark: Remark from APPLY applies here as well, since binary binning part is the similar. // linfty norm is used, resulting in the Factor 2 for p. typedef typename PROBLEM::Index Index; w.clear(); if (v.size() > 0) { // compute the number of bins V_0,...,V_q const double norm_v = linfty_norm(v); #if _APPLY_TENSOR_DEBUGMODE == 1 if (norm_v > 1e+10) { cout << "APPLY_TENSOR (Index):: l_infty norm of v is too high!"<<endl; cout << "v = " << v << endl; } #endif // Explicit sorting into bins is not necessary! // We may compute the bin number, norm of all entries in the bins, and number of entries in each bin non the less. // this enables us to compute the j_p in [DSS] // Theory: The i-th bin contains the entries of v with modulus in the interval // (2^{-(i+1)/2}||v||_\infty,2^{-i/2}||v||_\infty], 0 <= i <= q-1, the remaining elements (with even smaller modulus) // are collected in the q-th bin. // q is chosen s.t. elements not in any bin have norm <= threshold (= eta/(2*norm_A)) // The entries not in any bin are discarded. const double norm_A = P.norm_A(); double threshold = eta/2.0/norm_A; //const unsigned int q = (unsigned int) std::max(2*ceil(log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2), 0.); const unsigned int q = std::max ((unsigned int)1, 2*log2( (unsigned int) std::max(1, (int) ceil (sqrt(v.size())*norm_v/threshold) ) ) ); #if _APPLY_TENSOR_DEBUGMODE == 1 assert (q == (unsigned int) std::max(2*ceil(log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2), 0.) ); #endif Array1D<double> bin_norm_sqr(q); //square norm of the coeffs in the bins Array1D<int> bin_size(q); // number of entries in each bin // the bin number corresponding to an entry of v is computed twice in this code. storing it into an InfiniteVector is probably not faster //InfiniteVector<int, typename PROBLEM::Index> bin_number; // for each entry of v: store its bin - so the binnumber has to be computed only once - may be unnecessary #if _APPLY_TENSOR_DEBUGMODE == 1 for (unsigned int i=0; i< q;++i) { assert (bin_norm_sqr[i] == 0); assert (bin_size[i] == 0); } #endif { unsigned int temp_i; for (typename InfiniteVector<double,Index>::const_iterator it(v.begin());it != v.end(); ++it) { //const unsigned int i = std::min(q, (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2)); //i = std::min(q, (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2)); //temp_i = std::min(q, 2*floor(log2(floor(norm_v/fabs(*it)))) ); #if _APPLY_TENSOR_DEBUGMODE == 1 assert (std::min(q, 2*floor(log2(floor(norm_v/fabs(*it)))) ) = std::min(q, (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2))); #endif temp_i = 2*log2(floor(norm_v/fabs(*it))) -1; // bins: 1,...,q but observe temp_i: 0,...,q-1 if (temp_i < q) { //bins[i].push_back(std::make_pair(it.index(), *it)); bin_norm_sqr[temp_i] += (*it)*(*it); bin_size[temp_i] += 1; } } } // end of sorting into bins // In difference to the isotropic APPLY we use the bins directly as the segments v_{[0]},...,v_{[\ell]}. // [DSS]: compute smallest \ell such that // ||v-\sum_{k=0}^\ell v_{[k]}|| <= threshold // i.e. // ||v-\sum_{k=0}^\ell v_{[k]}||^2 <= threshold^2, // where threshold = eta * theta / ||A||, theta = 1/2 threshold = threshold*threshold; double delta(l2_norm_sqr(v)); //double bound = temp_d - threshold; unsigned int ell=0, num_of_relevant_entries(0); // number of bins needed to approximate v; number_of_coeffs in the first ell buckets if (delta <= threshold) { // v is well approximated by 0 return; } else { while (delta > threshold) { num_of_relevant_entries += bin_size[ell]; delta -= bin_norm_sqr[ell]; //bound -= bin_norm_sqr[ell]; ell++; if (ell > q) { break; } } } // we need buckets 0,...,ell-1 #if 0 // compute ell in a different way to check validity of code. needs explicit computation of bins double bound = l2_norm_sqr(v) - threshold; //double error_sqr = l2_norm_sqr(v); double new_norm_sqr(0); //Array1D<double> bin_norm_sqr(q+1); //square norm of the coeffs in the bins unsigned int ell2(0); unsigned int num_relevant_entries=0; if (l2_norm_sqr(v) > threshold) { unsigned int vsize = v.size(); while (true) { bin_norm_sqr[ell2]=0; for (typename std::list<std::pair<Index, double> >::const_iterator it(bins[ell].begin()), itend(bins[ell].end()); it != itend; ++it) { bin_norm_sqr[ell] += (it->second) * (it->second); //num_relevant_entries++; } if (bin_norm_sqr[ell2] < 1e-15 && bins[ell2].size() > 0) // this bin contains only very small coefs. Thus it and all later bins are not of any importance { //error_sqr = threshold; // we are near the machine limit if (ell2 > 0) { --ell2; } break; } num_relevant_entries += bins[ell2].size(); new_norm_sqr += bin_norm_sqr[ell2]; //error_sqr -= bin_norm_sqr[ell2]; if (new_norm_sqr >= bound) //if (error_sqr <= threshold) { break; } else if (num_relevant_entries == vsize) { //error_sqr = 0; break; } else { ell2++; } } } assert (ell == ell2); #endif // Compute z = \sum_{p=0}^ell A^{jp}v_{[p]}, // where A^{(jp)} is the optimal approximation matrix for each bin. // Optimality is meant in the sense that the computational effort is minimal and the error bound is met. // The computation is tailored for biorthogonal anisotropical wavelets: // A^{jp} has C*jp^dim nontrivial entries per row/column which need C*jp^dim many operations to be computed, further // \| A -A^{jp} \| \leq D 2^{-\rho jp} (A is compressible with s* = \infty) // jp is computed such that effort for apply is minimal, i.e., // \sum _{p=0}^ell C*jp^dim * bin_size[p] -> minimal, // under the error bound condition // \sum_{p=0}^ell D*s^{-\rho jp} \|v_p\|_2 \leq eta-delta, // where rho < 1/2 is the compressibility of A (valid for biorthogonl anisotropical wavelets) // eta is the target accuracy of APPLY, // delta = \|A\|\|v - \sum_{p=1}^\ell v_p\|_2 (<= eta/2) delta = sqrt(delta) * norm_A; assert (delta <= eta/2); // we use the formula for jp tilde from [DSS] for orthogonal wavelets, i.e., effort C*jp^1. // effect: error \eta-\delta is met, but effort may be suboptimal // => with D = P.alphak(p) //jp_tilde = ceil (log(sqrt(bin_norm_sqr[p])*num_relevant_entries*P.alphak(p)/(bin_size[p]*(eta-delta)))/M_LN2 ); Array1D<int> jp_tilde(ell); for (unsigned int i = 0; i < ell; ++i) { //jp_tilde[i] = ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ); jp_tilde[i] = ceil (log2(ceil (sqrt(bin_norm_sqr[i]) * num_of_relevant_entries * P.alphak(i) / (bin_size[i]*(eta-delta)))) ); #if _APPLY_TENSOR_DEBUGMODE == 1 assert (jp_tilde[i] == ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ) ); #endif } // hack: We work with full vectors (of size degrees_of_freedom). // We do this because adding sparse vectors seems to be inefficient. // Below we will then copy ww into the sparse vector w. // Probably this will be handled in a more elegant way someday. // ww should be of a similar structure to the cache in P Vector<double> ww(P.basis().degrees_of_freedom()); //cout << *(P.basis().get_wavelet(4000)) << endl; // compute w = \sum_{k=0}^\ell A_{J-k}v_{[k]} for (typename InfiniteVector<double,Index>::const_iterator it(v.begin()), itend(v.end());it != itend; ++it) { #if _APPLY_TENSOR_DEBUGMODE == 1 assert ( (2*log2(floor(norm_v/fabs(*it))) -1) >= 0 ); assert ( (2*log2(floor(norm_v/fabs(*it))) -1) < ell ); #endif //temp_i = 2*log2(floor(norm_v/fabs(*it))) -1 //add_compressed_column_tensor(P, *it, it, jp_tilde[2*log2(floor(norm_v/fabs(*it))) -1], ww, jmax, strategy, preconditioning); P.add_ball(it.index(),ww,jp_tilde[2*log2(floor(norm_v/fabs(*it))) -1],*it,jmax,strategy,preconditioning); } // copy ww into w for (unsigned int i = 0; i < ww.size(); i++) { if (ww[i] != 0.) { w.set_coefficient(*(P.basis().get_wavelet(i)), ww[i]); } } } } template <class PROBLEM> void APPLY_TENSOR(PROBLEM& P, const InfiniteVector<double, int>& v, const double eta, InfiniteVector<double, int>& w, const int jmax, const CompressionStrategy strategy, const bool preconditioning) { // Remark: Remark from APPLY applies here as well, since binary binning part is the similar. // linfty norm is used, resulting in the Factor 2 for p. w.clear(); if (v.size() > 0) { // compute the number of bins V_0,...,V_q const double norm_v = linfty_norm(v); #if _APPLY_TENSOR_DEBUGMODE == 1 if (norm_v > 1e+10) { cout << "APPLY_TENSOR (int):: l_infty norm of v is too high!"<<endl; cout << "v = " << v << endl; } #endif // Explicit sorting into bins is not necessary! // We may compute the bin number, norm of all entries in the bins, and number of entries in each bin non the less. // this enables us to compute the j_p in [DSS] // Theory: The i-th bin contains the entries of v with modulus in the interval // (2^{-(i+1)/2}||v||_\infty,2^{-i/2}||v||_\infty], 0 <= i <= q-1, the remaining elements (with even smaller modulus) // are collected in the q-th bin (discarded). // q is chosen s.t. elements not in any bin have norm <= threshold (= eta/(2*norm_A)) // The entries not in any bin are discarded. const double norm_A = P.norm_A(); double threshold = eta/2.0/norm_A; const unsigned int q = (unsigned int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2), 0.); //const unsigned int q = (unsigned int)(log2( (unsigned int) ceil (v.size()*norm_v*norm_v/threshold/threshold) ) +1); //const unsigned int q = (unsigned int)(2* log2( (unsigned int) ceil (sqrt(v.size())*norm_v/threshold) ) +1); #if _APPLY_TENSOR_DEBUGMODE == 1 assert (ceil (v.size()*norm_v*norm_v/threshold/threshold) > 0); // CLEANUP if (abs (q - (unsigned int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) ) > 1 ) { cout << "q = " << q << endl; cout << "v.size()*norm_v*norm_v/threshold/threshold = " << v.size()*norm_v*norm_v/threshold/threshold << endl; cout << "log (v.size()*norm_v*norm_v/threshold/threshold) / M_LN2 = " << log (v.size()*norm_v*norm_v/threshold/threshold) / M_LN2 << endl<< endl; cout << "sqrt(v.size())*norm_v/threshold = " << sqrt(v.size())*norm_v/threshold << endl; cout << "log (sqrt(v.size())*norm_v/threshold) / M_LN2 = " << log (sqrt(v.size())*norm_v/threshold) / M_LN2 << endl << endl; cout << "(unsigned int) ceil (sqrt(v.size())*norm_v/threshold) = " << (unsigned int) ceil (sqrt(v.size())*norm_v/threshold) << endl; cout << "log2( (unsigned int) ceil (sqrt(v.size())*norm_v/threshold) ) = " << log2( (unsigned int) ceil (sqrt(v.size())*norm_v/threshold) ) << endl << endl; cout << "(unsigned int) ceil (v.size()*norm_v*norm_v/threshold/threshold) = " << (unsigned int) ceil (v.size()*norm_v*norm_v/threshold/threshold) << endl; cout << "(unsigned int) ceil (v.size()*norm_v*norm_v*norm_A*2.0/eta*norm_A*2.0/eta) = " << (unsigned int) ceil (v.size()*norm_v*norm_v*norm_A*2.0/eta*norm_A*2.0/eta)<< endl; cout << "(sqrt((double)v.size())*norm_v*norm_A*2.0/eta) = " << (sqrt((double)v.size())*norm_v*norm_A*2.0/eta) << endl; cout << "ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) = " << ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) << endl; cout << "v.size() = " << v.size() << "; norm_v = " << norm_v << "; norm_A = " << norm_A << "; eta = " << eta << endl; cout << "q = " << q << "; (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) = " << (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) << endl; cout << "abs ((int)q - (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) ) = " << abs ((int)q - (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) ) << endl; } assert (abs ((int)q - (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) ) <= 1 ); assert ((int)q<= (int) std::max(ceil(2*log(sqrt((double)v.size())*norm_v*norm_A*2.0/eta)/M_LN2) , 0.) ); #endif Array1D<double> bin_norm_sqr(q); //square norm of the coeffs in the bins Array1D<int> bin_size(q); // number of entries in each bin // the bin number corresponding to an entry of v is computed twice in this code. storing it into an InfiniteVector is probably not faster! E.g., //InfiniteVector<int, typename PROBLEM::Index> bin_number; // for each entry of v: store its bin - so the binnumber has to be computed only once - may be unnecessary for (unsigned int i=0; i<q;++i) { bin_norm_sqr[i] = 0; bin_size[i] = 0; } unsigned int temp_i; for (typename InfiniteVector<double,int>::const_iterator it(v.begin());it != v.end(); ++it) { temp_i = (unsigned int)floor(2*log(norm_v/fabs(*it))/M_LN2); // bins: 1,...,q but observe temp_i: 0,...,q-1 // temp_i = 2*log2( (unsigned int) floor(norm_v/fabs(*it))); // bins: 1,...,q but observe temp_i: 0,...,q-1 #if _APPLY_TENSOR_DEBUGMODE == 1 if (std::min(q, temp_i) != std::min(q, (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2))) { cout << endl << "Line 307" << endl; cout << "q = " << q << "; norm_v = " << norm_v << "; fabs(*it) = " << fabs(*it) << endl; cout << "floor(norm_v/fabs(*it)) = " << floor(norm_v/fabs(*it)) << endl; cout << "(unsigned int) floor(norm_v/fabs(*it)) = " << (unsigned int) floor(norm_v/fabs(*it)) << endl; cout << "2*log2( (unsigned int) floor(norm_v/fabs(*it))) = " << 2*log2( (unsigned int) floor(norm_v/fabs(*it))) << endl << endl;; cout << "fabs(*it)/norm_v = " << fabs(*it)/norm_v << endl; cout << "floor(-2*log(fabs(*it)/norm_v)/M_LN2) = " << floor(-2*log(fabs(*it)/norm_v)/M_LN2) << endl; cout << "(unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2) = " << (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2) << endl; } assert (std::min(q, temp_i) == std::min(q, (unsigned int)floor(-2*log(fabs(*it)/norm_v)/M_LN2))); #endif if (temp_i < q) { //bins[i].push_back(std::make_pair(it.index(), *it)); bin_norm_sqr[temp_i] += (*it)*(*it); bin_size[temp_i] += 1; } } // end of sorting into bins #if _APPLY_TENSOR_DEBUGMODE == 1 for (unsigned int i=0; i<q; ++i) { assert ( (bin_size[i] == 0) == (bin_norm_sqr[i] == 0)); } #endif // q is pessimistic! int number_of_buckets(q); while (number_of_buckets > 0) { if (bin_size[number_of_buckets-1] != 0) break; --number_of_buckets; } //cout << "bin_size = " << bin_size << endl; // In difference to the isotropic APPLY we use the bins directly as the segments v_{[0]},...,v_{[\ell]}. // [DSS]: compute smallest \ell such that // ||v-\sum_{k=0}^\ell v_{[k]}|| <= threshold // i.e. // ||v-\sum_{k=0}^\ell v_{[k]}||^2 <= threshold^2, // where threshold = eta * theta / ||A||, theta = 1/2 // if threshold^2 > 1e-14 the computation of the squared l2 norm fails. // we will always need all entries of v in this setting threshold = threshold*threshold; double delta(l2_norm_sqr(v)); if (delta <= threshold) { // v is well approximated by 0 return; } unsigned int ell=0, num_of_relevant_entries(0); // number of bins needed to approximate v; number_of_coeffs in the first ell buckets if (threshold > 1e-12) { //double bound = temp_d - threshold; double temp_d(0); cout << "delta = " << delta << endl; while (delta > threshold) { if (bin_size[ell] != 0) { num_of_relevant_entries += bin_size[ell]; delta -= bin_norm_sqr[ell]; temp_d += bin_norm_sqr[ell]; cout << "bin_norm_sqr[" << ell << "]= " << bin_norm_sqr[ell] << "; temp_d = " << temp_d << "; delta = " << delta << "; threshold = " << threshold << endl; // bound -= bin_norm_sqr[ell]; } ell++; if (ell >= number_of_buckets) { cout << "we need all buckets!" << endl; break; } } if (delta < 0) { delta = 0; assert (num_of_relevant_entries == v.size()); } // we need buckets 0,...,ell-1 } else { ell = number_of_buckets; num_of_relevant_entries = v.size(); delta = 0; } // Compute z = \sum_{p=0}^ell A^{jp}v_{[p]}, // where A^{(jp)} is the optimal approximation matrix for each bin. // Optimality is meant in the sense that the computational effort is minimal and the error bound is met. // The computation is tailored for biorthogonal anisotropical wavelets: // A^{jp} has C*jp^dim nontrivial entries per row/column which need C*jp^dim many operations to be computed, further // \| A -A^{jp} \| \leq D 2^{-\rho jp} (A is compressible with s* = \infty) // jp is computed such that effort for apply is minimal, i.e., // \sum _{p=0}^ell C*jp^dim * bin_size[p] -> minimal, // under the error bound condition // \sum_{p=0}^ell D*s^{-\rho jp} \|v_p\|_2 \leq eta-delta, // where rho < 1/2 is the compressibility of A (valid for biorthogonal anisotropical wavelets) // eta is the target accuracy of APPLY, // delta = \|A\|\|v - \sum_{p=1}^\ell v_p\|_2 (<= eta/2) // assert (delta <= threshold); delta = sqrt(delta) * norm_A; //if (!( (! (delta <= eta/2) ) == (delta > eta/2))) if (!(delta <= eta/2)) { cout << "was soll das?" << endl; cout << "delta = " << delta << "; eta = " << eta << "; eta/2 = " << eta/2 << endl; cout << "(delta <= eta/2) = " << (delta <= eta/2) << "; (delta > eta/2) = " << (delta > eta/2) << endl; cout << "l2_norm_sqr(v) = " << l2_norm_sqr(v) << endl; cout << "bin_size = " << bin_size << endl; cout << "bin_norm_sqr = " << bin_norm_sqr << endl; cout << "ell = " << ell << endl; } assert (delta <= eta/2); // we use the formula for jp tilde from [DSS] for orthogonal wavelets, i.e., effort C*jp^1. // effect: error \eta-\delta is met, but effort may be suboptimal // => with D = P.alphak(p) //jp_tilde = ceil (log(sqrt(bin_norm_sqr[p])*num_relevant_entries*P.alphak(p)/(bin_size[p]*(eta-delta)))/M_LN2 ); Array1D<int> jp_tilde(ell); // jp_tilde[i] == approximation that is needed for the ith bin for (unsigned int i = 0; i < ell; ++i) { //jp_tilde[i] = ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ); if (bin_size[i] > 0) { jp_tilde[i] = (int)ceil (log(sqrt(bin_norm_sqr[i]) * num_of_relevant_entries * P.alphak(i) / (bin_size[i]*(eta-delta))) / M_LN2 ); // jp_tilde[i] = (int)ceil (log2(ceil (sqrt(bin_norm_sqr[i]) * num_of_relevant_entries * P.alphak(i) / (bin_size[i]*(eta-delta)))) ); #if _APPLY_TENSOR_DEBUGMODE == 1 if (jp_tilde[i] < 0) { cout << "i = " << i << "; jp_tilde["<< i << "] = " << jp_tilde[i] << endl; cout << "bin_norm_sqr[" << i<< "] = " << bin_norm_sqr[i] << "; num_of_relevant_entries = " << num_of_relevant_entries << "; P.alphak(" << i<< ") = " << P.alphak(i) << "; bin_size[" << i<< "] = " << bin_size[i] << "; eta = " << eta << "; delta = " << delta << endl; } assert(jp_tilde[i] >= 0); if (jp_tilde[i] != ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ) ) { cout << "i = " << i << "; jp_tilde["<< i << "] = " << jp_tilde[i] << endl; cout << "bin_norm_sqr[" << i<< "] = " << bin_norm_sqr[i] << "; num_of_relevant_entries = " << num_of_relevant_entries << "; P.alphak(" << i<< ") = " << P.alphak(i) << "; bin_size[" << i<< "] = " << bin_size[i] << "; eta = " << eta << "; delta = " << delta << endl; cout << "sqrt(bin_norm_sqr[" << i<< "])*num_of_relevant_entries*P.alphak(" << i<< ")/(bin_size[" << i <<" ]*(eta-delta)) = " << sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)) << endl; cout << "ceil (log(" << sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)) << ")/M_LN2 ) = " << ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ) << endl; } assert (jp_tilde[i] == ceil (log(sqrt(bin_norm_sqr[i])*num_of_relevant_entries*P.alphak(i)/(bin_size[i]*(eta-delta)))/M_LN2 ) ); #endif } else { jp_tilde[i] = 0; } } // hack: We work with full vectors (of size degrees_of_freedom). // We do this because adding sparse vectors seems to be inefficient. // Below we will then copy ww into the sparse vector w. // Probably this will be handled in a more elegant way someday. // ww should be of a similar structure to the cache in P Vector<double> ww(P.basis()->degrees_of_freedom()); // compute w = \sum_{k=0}^(\ell-1) A_{J-k}v_{[k]} for (typename InfiniteVector<double,int>::const_iterator it(v.begin()), itend(v.end());it != itend; ++it) { #if _APPLY_TENSOR_DEBUGMODE == 1 if (log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) < 0) { cout << "norm_v = " << norm_v << "; fabs(*it) = " << fabs(*it) << "; log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) = " << log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) << endl; } assert ( log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) >= 0 ); // if (log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) >= q) // { // cout << "ell = " << ell << endl; // cout << "norm_v = " << norm_v << "; fabs(*it) = " << fabs(*it) << "; log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) = " << log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) << endl; // } // assert ( log2((unsigned int)(norm_v*norm_v/fabs(*it)/fabs(*it))) < q ); #endif //temp_i = 2*log2(floor(norm_v/fabs(*it))) -1 //add_compressed_column_tensor(P, *it, it, jp_tilde[2*log2(floor(norm_v/fabs(*it))) -1], ww, jmax, strategy, preconditioning); temp_i = (unsigned int)floor(2*log(norm_v/fabs(*it))/M_LN2); // bins: 1,...,q but observe temp_i: 0,...,q-1 //temp_i = log2((unsigned int)(floor(norm_v*norm_v/fabs(*it)/fabs(*it)))); if ( temp_i < ell ) { P.add_ball(it.index() ,ww,jp_tilde[temp_i],*it ,jmax,strategy,preconditioning); } } // copy ww into w for (unsigned int i = 0; i < ww.size(); i++) { if (ww[i] != 0.) { w.set_coefficient(i, ww[i]); } } } } }
57.331313
289
0.496881
kedingagnumerikunimarburg
db64bacaf64c5a59e0124f28fd2c7dfeaae023e7
12,719
hpp
C++
runtime/utils/qcor_utils.hpp
vetter/qcor
6f86835737277a26071593bb10dd8627c29d74a3
[ "BSD-3-Clause" ]
59
2019-08-22T18:40:38.000Z
2022-03-09T04:12:42.000Z
runtime/utils/qcor_utils.hpp
vetter/qcor
6f86835737277a26071593bb10dd8627c29d74a3
[ "BSD-3-Clause" ]
137
2019-09-13T15:50:18.000Z
2021-12-06T14:19:46.000Z
runtime/utils/qcor_utils.hpp
vetter/qcor
6f86835737277a26071593bb10dd8627c29d74a3
[ "BSD-3-Clause" ]
26
2019-07-08T17:30:35.000Z
2021-12-03T16:24:12.000Z
/******************************************************************************* * Copyright (c) 2018-, UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution. * * Contributors: * Alexander J. McCaskey - initial API and implementation * Thien Nguyen - implementation *******************************************************************************/ #pragma once #include <argparse.hpp> // #include <complex> #include <iostream> #include <memory> #include <tuple> #include <vector> #include <Eigen/Dense> #include "qcor_ir.hpp" namespace xacc { class IRProvider; class IRTransformation; class AcceleratorBuffer; namespace internal_compiler { class qreg; } } // namespace xacc namespace qcor { namespace constants { static constexpr double pi = 3.141592653589793238; } namespace arg { // Expose ArgumentParser for custom instantiation using ArgumentParser = argparse::ArgumentParser; // Default argument parser ArgumentParser &get_parser(); // Parameter packing // Call add_argument with variadic number of string arguments template <typename... Targs> argparse::Argument &add_argument(Targs... Fargs) { return get_parser().add_argument(Fargs...); } // Getter for options with default values. // @throws std::logic_error if there is no such option // @throws std::logic_error if the option has no value // @throws std::bad_any_cast if the option is not of type T // template <typename T = std::string> T get_argument(std::string_view argument_name) { return get_parser().get<T>(argument_name); } // Main entry point for parsing command-line arguments using this // ArgumentParser // @throws std::runtime_error in case of any invalid argument // void parse_args(int argc, const char *const argv[]); } // namespace arg template <typename T> using PairList = std::vector<std::pair<T, T>>; using HeterogeneousMap = xacc::HeterogeneousMap; using IRTransformation = xacc::IRTransformation; using IRProvider = xacc::IRProvider; using qreg = xacc::internal_compiler::qreg; using UnitaryMatrix = Eigen::MatrixXcd; using DenseMatrix = Eigen::MatrixXcd; // The ResultsBuffer is returned upon completion of // the taskInitiate async call, it contains the buffer, // the optimal value for the objective function, and the // optimal parameters // class ResultsBuffer { // public: // xacc::internal_compiler::qreg q_buffer; // double opt_val; // std::vector<double> opt_params; // double value; // }; // A Handle is just a future on ResultsBuffer // using Handle = std::future<ResultsBuffer>; // Sync up a Handle // ResultsBuffer sync(Handle &handle); // Indicate we have an error with the given message. // This should abort execution void error(const std::string &msg); std::vector<std::string> split(const std::string &str, char delimiter); void persist_var_to_qreg(const std::string &key, double &val, qreg &q); void persist_var_to_qreg(const std::string &key, int &val, qreg &q); template <typename T> std::vector<T> linspace(T a, T b, size_t N) { T h = (b - a) / static_cast<T>(N - 1); std::vector<T> xs(N); typename std::vector<T>::iterator x; T val; for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h) *x = val; return xs; } inline std::vector<int> range(int N) { std::vector<int> vec(N); std::iota(vec.begin(), vec.end(), 0); return vec; } inline std::vector<int> range(int start, int stop, int step) { if (step == 0) { error("step for range must be non-zero."); } int i = start; std::vector<int> vec; while ((step > 0) ? (i < stop) : (i > stop)) { vec.push_back(i); i += step; } return vec; } inline std::vector<int> range(int start, int stop) { return range(start, stop, 1); } // Get size() of any types that have size() implemented. template <typename T> int len(const T &countable) { return countable.size(); } template <typename T> int len(T &countable) { return countable.size(); } // Python-like print instructions: inline void print() { std::cout << "\n"; } template <typename T, typename... TAIL> void print(const T &t, TAIL... tail) { std::cout << t << " "; print(tail...); } std::shared_ptr<qcor::IRTransformation> createTransformation( const std::string &transform_type); // The TranslationFunctor maps vector<double> to a tuple of Args... template <typename... Args> using TranslationFunctor = std::function<std::tuple<Args...>(const std::vector<double> &)>; // ArgsTranslator takes a std function that maps a // vector<double> argument to a tuple corresponding to // the arguments for the quantum kernel in question // // FIXME provide example here template <typename... Args> class ArgsTranslator { protected: TranslationFunctor<Args...> functor; public: ArgsTranslator(TranslationFunctor<Args...> ts) : functor(ts) {} std::tuple<Args...> operator()(const std::vector<double> &x) { return functor(x); } }; template <typename... Args> std::shared_ptr<ArgsTranslator<Args...>> createArgsTranslator( TranslationFunctor<Args...> functor) { return std::make_shared<ArgsTranslator<Args...>>(functor); } // The GradientEvaluator is user-provided function that sets the // gradient dx for a given variational iteration at parameter set x using GradientEvaluator = std::function<void(std::vector<double> x, std::vector<double> &dx)>; namespace __internal__ { UnitaryMatrix map_composite_to_unitary_matrix( std::shared_ptr<CompositeInstruction> composite); std::string translate(const std::string compiler, std::shared_ptr<CompositeInstruction> program); void append_plugin_path(const std::string path); // Internal function for creating a CompositeInstruction, this lets us // keep XACC out of the include headers here and put it in the cpp. std::shared_ptr<qcor::CompositeInstruction> create_composite(std::string name); // Return the CTRL-U CompositeInstruction generator std::shared_ptr<qcor::CompositeInstruction> create_ctrl_u(); std::shared_ptr<qcor::CompositeInstruction> create_and_expand_ctrl_u( HeterogeneousMap &&m); // Return the IR Transformation std::shared_ptr<qcor::IRTransformation> get_transformation( const std::string &transform_type); // return the IR Provider std::shared_ptr<qcor::IRProvider> get_provider(); // Decompose the given unitary matrix with the specified decomposition // algorithm. std::shared_ptr<qcor::CompositeInstruction> decompose_unitary(const std::string algorithm, UnitaryMatrix &mat, qreg &buffer); // Decompose the given unitary matrix with the specified decomposition algorithm // and optimizer // std::shared_ptr<qcor::CompositeInstruction> // decompose_unitary(const std::string algorithm, UnitaryMatrix &mat, qreg &buffer, // std::shared_ptr<xacc::Optimizer> optimizer); // Utility for calling a Functor via mapping a tuple of Args to // a sequence of Args... template <typename Function, typename Tuple, size_t... I> auto evaluate_shared_ptr_fn_with_tuple_args(Function f, Tuple t, std::index_sequence<I...>) { return f->operator()(std::get<I>(t)...); } // Utility for calling a Functor via mapping a tuple of Args to // a sequence of Args... template <typename Function, typename Tuple> auto evaluate_shared_ptr_fn_with_tuple_args(Function f, Tuple t) { static constexpr auto size = std::tuple_size<Tuple>::value; return evaluate_shared_ptr_fn_with_tuple_args( f, t, std::make_index_sequence<size>{}); } // Utility for calling a Functor via mapping a tuple of Args to // a sequence of Args... template <typename Function, typename Tuple, size_t... I> auto evaluate_function_with_tuple_args(Function f, Tuple t, std::index_sequence<I...>) { return f(std::get<I>(t)...); } // Utility for calling a Functor via mapping a tuple of Args to // a sequence of Args... template <typename Function, typename Tuple> auto evaluate_function_with_tuple_args(Function f, Tuple t) { static constexpr auto size = std::tuple_size<Tuple>::value; return evaluate_function_with_tuple_args(f, t, std::make_index_sequence<size>{}); } // This internal utility class enables the merging of all // quantum kernel double or std::vector<double> parameters // into a single std::vector<double> (these correspond to circuit // rotation parameters) class ConvertDoubleLikeToVectorDouble { public: std::vector<double> &vec; ConvertDoubleLikeToVectorDouble(std::vector<double> &v) : vec(v) {} void operator()(std::vector<double> tuple_element_vec) { for (auto &e : tuple_element_vec) { vec.push_back(e); } } void operator()(double tuple_element_double) { vec.push_back(tuple_element_double); } template <typename T> void operator()(T &) {} }; // Utility function for looping over tuple elements template <typename TupleType, typename FunctionType> void tuple_for_each( TupleType &&, FunctionType, std::integral_constant< size_t, std::tuple_size< typename std::remove_reference<TupleType>::type>::value>) {} // Utility function for looping over tuple elements template <std::size_t I, typename TupleType, typename FunctionType, typename = typename std::enable_if< I != std::tuple_size<typename std::remove_reference< TupleType>::type>::value>::type> // Utility function for looping over tuple elements void tuple_for_each(TupleType &&t, FunctionType f, std::integral_constant<size_t, I>) { f(std::get<I>(t)); __internal__::tuple_for_each(std::forward<TupleType>(t), f, std::integral_constant<size_t, I + 1>()); } // Utility function for looping over tuple elements template <typename TupleType, typename FunctionType> void tuple_for_each(TupleType &&t, FunctionType f) { __internal__::tuple_for_each(std::forward<TupleType>(t), f, std::integral_constant<size_t, 0>()); } } // namespace __internal__ // Create and return a random vector<ScalarType> of the given size // where all elements are within the given range std::vector<double> random_vector(const double l_range, const double r_range, const std::size_t size); // Take a function and return a TranslationFunctor template <typename... Args> auto args_translator( std::function<std::tuple<Args...>(const std::vector<double>)> &&functor_lambda) { return TranslationFunctor<Args...>(functor_lambda); } // C++17 python-like enumerate utility function template <typename T, typename TIter = decltype(std::begin(std::declval<T>())), typename = decltype(std::end(std::declval<T>()))> constexpr auto enumerate(T &&iterable) { struct iterator { size_t i; TIter iter; bool operator!=(const iterator &other) const { return iter != other.iter; } void operator++() { ++i; ++iter; } auto operator*() const { return std::tie(i, *iter); } }; struct iterable_wrapper { T iterable; auto begin() { return iterator{0, std::begin(iterable)}; } auto end() { return iterator{0, std::end(iterable)}; } }; return iterable_wrapper{std::forward<T>(iterable)}; } // Set the backend that quantum kernels are targeting void set_backend(const std::string &backend); // Utility function to expose the XASM xacc Compiler // from the cpp implementation and not include it in the header list above. std::shared_ptr<CompositeInstruction> compile(const std::string &src); // Toggle verbose mode void set_verbose(bool verbose); // Get if we are verbose or not bool get_verbose(); // Set the shots for a given quantum kernel execution void set_shots(const int shots); // constexpr std::complex<double> I{0.0, 1.0}; // // Note: cannot use std::complex_literal // // because https://gcc.gnu.org/onlinedocs/gcc/Complex.html#Complex // inline constexpr std::complex<double> operator"" _i(long double x) noexcept { // return {0., static_cast<double>(x)}; // } #define qcor_expect(test_condition) \ { \ if (!(test_condition)) { \ std::stringstream ss; \ ss << __FILE__ << ":" << __LINE__ << ": Assertion failed: '" \ << #test_condition << "'."; \ error(ss.str()); \ } \ } } // namespace qcor
33.383202
83
0.673245
vetter
db6dfe59498a0a886f2f20aedf9ea06cf84df418
2,125
cc
C++
proxy/http/remap/RemapPluginInfo.cc
best8tom/trafficserver
86fffc0f7c3073df3610a06753cc10c5c49231f0
[ "Apache-2.0" ]
1
2019-11-08T05:57:11.000Z
2019-11-08T05:57:11.000Z
proxy/http/remap/RemapPluginInfo.cc
best8tom/trafficserver
86fffc0f7c3073df3610a06753cc10c5c49231f0
[ "Apache-2.0" ]
2
2018-04-18T20:46:52.000Z
2018-09-19T20:07:01.000Z
proxy/http/remap/RemapPluginInfo.cc
best8tom/trafficserver
86fffc0f7c3073df3610a06753cc10c5c49231f0
[ "Apache-2.0" ]
null
null
null
/** @file Information about remap plugin libraries. @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "RemapPluginInfo.h" #include "tscore/ink_string.h" #include "tscore/ink_memory.h" RemapPluginInfo::List RemapPluginInfo::g_list; RemapPluginInfo::RemapPluginInfo(ts::file::path &&library_path) : path(std::move(library_path)) {} RemapPluginInfo::~RemapPluginInfo() { if (dl_handle) { dlclose(dl_handle); } } // // Find a plugin by path from our linked list // RemapPluginInfo * RemapPluginInfo::find_by_path(std::string_view library_path) { auto spot = std::find_if(g_list.begin(), g_list.end(), [&](self_type const &info) -> bool { return 0 == library_path.compare(info.path.view()); }); return spot == g_list.end() ? nullptr : static_cast<self_type *>(spot); } // // Add a plugin to the linked list // void RemapPluginInfo::add_to_list(RemapPluginInfo *pi) { g_list.append(pi); } // // Remove and delete all plugins from a list. // void RemapPluginInfo::delete_list() { g_list.apply([](self_type *info) -> void { delete info; }); g_list.clear(); } // // Tell all plugins (that so wish) that remap.config is being reloaded // void RemapPluginInfo::indicate_reload() { g_list.apply([](self_type *info) -> void { if (info->config_reload_cb) { info->config_reload_cb(); } }); }
26.234568
119
0.714353
best8tom
db7407dc8fd825dd88ffd4fed64e358534cd4992
4,254
cpp
C++
Source/SFMLIntegration/CConvexShape.cpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
Source/SFMLIntegration/CConvexShape.cpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
Source/SFMLIntegration/CConvexShape.cpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
// // CConvexShape.cpp // TimGameLib // // Created by Tim Brier on 18/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "CConvexShape.hpp" #include "../CollisionHandler.hpp" // ============================================================================= // CConvexShape constructor/destructor // ----------------------------------------------------------------------------- CConvexShape::CConvexShape(unsigned int pointCount /* = 0 */) : sf::ConvexShape(pointCount) { } CConvexShape::CConvexShape(std::list<CVector2f> &thePoints) : sf::ConvexShape((int) thePoints.size()) { int theIndex = 0; FOR_EACH_IN_LIST(CVector2f, thePoints) { setPoint(theIndex, (*it)); theIndex++; } } CConvexShape::~CConvexShape() { } // ============================================================================= // CConvexShape::GetLines // Build and return a list of lines within the shape using global coords // ----------------------------------------------------------------------------- std::list<CLine> CConvexShape::GetGlobalLines() { std::list<CLine> theResult; int numPoints = getPointCount(); CVector2f pos = getPosition(); for (int i = 0; i < numPoints; i++) { CVector2f start = GetGlobalPoint(i); CVector2f end = GetGlobalPoint((i+1) % numPoints); theResult.push_back(CLine(start, end)); } return theResult; } // ============================================================================= // CConvexShape::GetGlobalPoint // Get the indexth point in the shape in global coords // ----------------------------------------------------------------------------- CVector2f CConvexShape::GetGlobalPoint(unsigned int index) { CVector2f localPoint = getPoint(index); CVector2f scaledPoint = localPoint; CVector2f scale = getScale(); scaledPoint.x *= scale.x; scaledPoint.y *= scale.y; return getPosition() + scaledPoint; } // ============================================================================= // CConvexShape::IsCollidingWith // ----------------------------------------------------------------------------- bool CConvexShape::IsCollidingWith(CConvexShape &other, CVector2f *correctionVector /* = NULL */) { CVector2f cv; bool theResult = CollisionHandler::AreColliding(*this, other, &cv, kCDOverlapping); if (correctionVector != NULL) { *correctionVector = cv; } return theResult; } // ============================================================================= // CConvexShape::IsInside // ----------------------------------------------------------------------------- bool CConvexShape::IsInside(CConvexShape &other, CVector2f *correctionVector /* = NULL */) { CVector2f cv; bool theResult = CollisionHandler::AreColliding(*this, other, &cv, kCDLhsInside); if (correctionVector != NULL) { *correctionVector = cv; } return theResult; } // ============================================================================= // CConvexShape::IsCollidingWith // ----------------------------------------------------------------------------- bool CConvexShape::IsContaining(CConvexShape &other, CVector2f *correctionVector /* = NULL */) { CVector2f cv; bool theResult = CollisionHandler::AreColliding(*this, other, &cv, kCDRhsInside); if (correctionVector != NULL) { *correctionVector = cv; } return theResult; }
31.279412
80
0.398213
sizlo
db751b9004b42f6197d66f02deaf91742ce01b37
1,210
cpp
C++
online_judges/ac/103B.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
2
2018-02-20T14:44:57.000Z
2018-02-20T14:45:03.000Z
online_judges/ac/103B.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
online_judges/ac/103B.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #ifdef PAPITAS #define DEBUG 1 #else #define DEBUG 0 #endif #define _DO_(x) if(DEBUG) x bool visited[110][110]; bool nvisited[110]; int parent[110]; int c = 0; vector<int> adj[110]; vector< vector<int> > cycles; void cycle(int u, vector<int> path){ c++; vector<int> edg = adj[u]; nvisited[u] = true; for(int i = 0; i < edg.size(); i++){ if(!visited[u][edg[i]]){ visited[u][edg[i]] = true; visited[edg[i]][u] = true; vector<int> next = path; next.push_back(edg[i]); if(!nvisited[edg[i]]){ cycle(edg[i], next); }else{ cycles.push_back(next); } } } } int main() { ios::sync_with_stdio(false);cin.tie(NULL); #ifdef PAPITAS freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif int n, m, a, b; cin >> n >> m; for(int i = 0; i < m; i++){ cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } vector<int> path; path.push_back(1); cycle(1, path); if(cycles.size() == 1 && c == n){ /*vector<int> cycle = cycles[0]; int s = cycle[cycle.size() - 1]; int i = cycle.size() - 2;*/ cout << "FHTAGN!"; }else{ cout << "NO"; } return 0; }
17.794118
43
0.580165
miaortizma
db76c004750cc3b8bef6870594b33b1160540c47
135,686
cpp
C++
src/prod/src/data/logicallog/LogTestBase.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/src/data/logicallog/LogTestBase.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/src/data/logicallog/LogTestBase.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "TestHeaders.h" #include <boost/test/unit_test.hpp> #include "Common/boost-taef.h" namespace LogTests { using namespace Common; using namespace ktl; using namespace Data::Log; using namespace Data::Utilities; volatile bool LogTestBase::g_UseKtlFilePrefix = true; LPCWSTR LogTestBase::GetTestDirectoryPath() { #if !defined(PLATFORM_UNIX) if (LogTestBase::g_UseKtlFilePrefix) { return L"\\??\\c:\\LogTestTemp"; } else { return L"c:\\LogTestTemp"; } #else return L"/tmp/logtesttemp/"; #endif } Common::StringLiteral const TraceComponent("LogTestBase"); NTSTATUS CreateKtlLogManager( __in KtlLoggerMode ktlLoggerMode, __in KAllocator& allocator, __out KtlLogManager::SPtr& physicalLogManager) { switch (ktlLoggerMode) { case KtlLoggerMode::Default: #if !defined(PLATFORM_UNIX) return KtlLogManager::CreateDriver(KTL_TAG_TEST, allocator, physicalLogManager); #else return KtlLogManager::CreateInproc(KTL_TAG_TEST, allocator, physicalLogManager); #endif break; case KtlLoggerMode::InProc: return KtlLogManager::CreateInproc(KTL_TAG_TEST, allocator, physicalLogManager); break; case KtlLoggerMode::OutOfProc: return KtlLogManager::CreateDriver(KTL_TAG_TEST, allocator, physicalLogManager); break; default: KInvariant(FALSE); return STATUS_NOT_IMPLEMENTED; break; } } VOID LogTestBase::RestoreEOFState( __in Data::Log::ILogicalLog& log, __in LONG dataSize, __in LONG prefetchSize) { LONGLONG fixPos = dataSize - prefetchSize; NTSTATUS status = SyncAwait(log.TruncateTail(fixPos, CancellationToken::None)); VERIFY_STATUS_SUCCESS(L"ILogicalLog::TruncateTail", status); KBuffer::SPtr fixBuffer; PUCHAR b; AllocBuffer(prefetchSize, fixBuffer, b); BuildDataBuffer(*fixBuffer, fixPos); status = SyncAwait(log.AppendAsync(*fixBuffer, 0, prefetchSize, CancellationToken::None)); VERIFY_STATUS_SUCCESS(L"IeLogicalLog::AppendAsync", status); status = SyncAwait(log.FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS(L"ILogicalLog::FlushWithMarkerAsync", status); } VOID LogTestBase::GenerateUniqueFilename(__out KString::SPtr& filename) { BOOLEAN res; NTSTATUS status = KString::Create(filename, GetThisAllocator()); KInvariant(NT_SUCCESS(status)); res = filename->Concat(GetTestDirectoryPath()); KInvariant(res); res = filename->Concat(KVolumeNamespace::PathSeparator); KInvariant(res); KGuid guid; guid.CreateNew(); const KWString guidStr(GetThisAllocator(), guid); PWCHAR guidStrPtr = (PWCHAR)guidStr; res = filename->Concat(guidStrPtr); KInvariant(res); res = filename->Concat(L".testlog"); KInvariant(res); } VOID LogTestBase::CreateTestDirectory() { if (!Common::Directory::Exists(GetTestDirectoryPath())) { Common::ErrorCode errorCode = Common::Directory::Create2(GetTestDirectoryPath()); VERIFY_IS_TRUE(errorCode.IsSuccess(), L"Common::Directory::Create2"); } } VOID LogTestBase::DeleteTestDirectory() { Common::ErrorCode errorCode = Common::Directory::Delete(GetTestDirectoryPath(), true); VERIFY_IS_TRUE(errorCode.IsSuccess(), L"Common::Directory::Delete"); } VOID LogTestBase::AllocBuffer( __in LONG length, __out KBuffer::SPtr& buffer, __out PUCHAR& bufferPtr) { NTSTATUS status; KBuffer::SPtr b; status = KBuffer::Create(length, b, GetThisAllocator(), GetThisAllocationTag()); VERIFY_IS_TRUE(NT_SUCCESS(status)); buffer = Ktl::Move(b); bufferPtr = static_cast<PUCHAR>(buffer->GetBuffer()); } VOID LogTestBase::BuildDataBuffer( __in KBuffer& buffer, __in LONGLONG positionInStream, __in LONG entropy, __in UCHAR recordSize) { // // Build a data buffer that represents the position in the log. Buffers built // are exactly reproducible as they are used for writing and reading // PUCHAR b = static_cast<PUCHAR>(buffer.GetBuffer()); ULONG length = buffer.QuerySize(); for (ULONG i = 0; i < length; i++) { LONGLONG pos = positionInStream + i; LONGLONG value = (pos * pos) + pos + entropy; b[i] = static_cast<UCHAR>(value % recordSize); } } VOID LogTestBase::ValidateDataBuffer( __in KBuffer& buffer, __in ULONG length, __in ULONG offsetInBuffer, __in LONGLONG positionInStream, __in ULONG entropy, __in UCHAR recordSize) { // // Build a data buffer that represents the position in the log. Buffers built // are exactly reproducible as they are used for writing and reading // PUCHAR bptr = static_cast<PUCHAR>(buffer.GetBuffer()); for (ULONG i = 0; i < length; i++) { LONGLONG position = positionInStream + i; LONGLONG value = (position * position) + position + entropy; UCHAR b = static_cast<UCHAR>(value % recordSize); if (bptr[i + offsetInBuffer] != b) { TestCommon::TestSession::WriteError(TraceComponent, "Data error {0} expecting {1} at stream offset {2}", bptr[i + offsetInBuffer], b, positionInStream + i); VERIFY_IS_TRUE(bptr[i + offsetInBuffer] == b); } } } const int NumStreams = 100; VOID LogTestBase::OpenManyStreamsTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreateDefaultPhysicalLog(*logManager, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); KString::SPtr logicalLogName; GenerateUniqueFilename(logicalLogName); KGuid logicalLogId; logicalLogId.CreateNew(); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); KEvent taskComplete(FALSE, FALSE); // auto reset // The original bug causes these tests to deadlock, so post them on the // threadpool to check for failure (rather than waiting for test timeout) // Test creating and immediately closing streams { Common::Threadpool::Post([&]() { for (int i = 0; i < NumStreams; i++) { ILogicalLogReadStream::SPtr readStream; status = logicalLog->CreateReadStream(readStream, 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } status = SyncAwait(readStream->CloseAsync()); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } readStream = nullptr; } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAndImmediatelyClose", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test creating and immediately disposing streams { Common::Threadpool::Post([&]() { for (int i = 0; i < NumStreams; i++) { ILogicalLogReadStream::SPtr readStream; status = logicalLog->CreateReadStream(readStream, 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } readStream->Dispose(); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } readStream = nullptr; } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAndImmediatelyDispose", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test creating and immediately destructing streams { Common::Threadpool::Post([&]() { for (int i = 0; i < NumStreams; i++) { ILogicalLogReadStream::SPtr readStream; status = logicalLog->CreateReadStream(readStream, 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } readStream = nullptr; } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAndImmediatelyDestruct", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test creating all streams then closing { // Note: this actually passes with the original bug, as only the streams array 'append' codepath is exercised Common::Threadpool::Post([&]() { ILogicalLogReadStream::SPtr streams[NumStreams]; for (int i = 0; i < NumStreams; i++) { status = logicalLog->CreateReadStream(streams[i], 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } } for (int i = 0; i < NumStreams; i++) { status = SyncAwait(streams[i]->CloseAsync()); streams[i] = nullptr; if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAllThenClose", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test creating all streams then disposing { // Note: this actually passes with the original bug, as only the streams array 'append' codepath is exercised Common::Threadpool::Post([&]() { ILogicalLogReadStream::SPtr streams[NumStreams]; for (int i = 0; i < NumStreams; i++) { status = logicalLog->CreateReadStream(streams[i], 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } } for (int i = 0; i < NumStreams; i++) { streams[i]->Dispose(); streams[i] = nullptr; } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAllThenDispose", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test creating all streams then destructing { // Note: this actually passes with the original bug, as only the streams array 'append' codepath is exercised Common::Threadpool::Post([&]() { ILogicalLogReadStream::SPtr streams[NumStreams]; for (int i = 0; i < NumStreams; i++) { status = logicalLog->CreateReadStream(streams[i], 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } } for (int i = 0; i < NumStreams; i++) { streams[i] = nullptr; } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_OpenAllThenDestruct", status); } // Close and reopen the log status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // Test with random choice of when to cleanup stream { // Note: this actually passes with the original bug, as only the streams array 'append' codepath is exercised Common::Threadpool::Post([&]() { Common::Random random(NumStreams); ILogicalLogReadStream::SPtr streams[NumStreams]; for (int i = 0; i < NumStreams; i++) { status = logicalLog->CreateReadStream(streams[i], 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } switch (random.Next() % 6) { case 0: case 1: case 2: // let it be cleaned up later break; case 3: // Close now status = SyncAwait(streams[i]->CloseAsync()); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } streams[i] = nullptr; break; case 4: // Dispose now streams[i]->Dispose(); streams[i] = nullptr; break; case 5: // Destruct now streams[i] = nullptr; break; } } for (int i = 0; i < NumStreams; i++) { if (streams[i] != nullptr) { switch (random.Next() % 3) { case 0: // Close status = SyncAwait(streams[i]->CloseAsync()); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } streams[i] = nullptr; break; case 1: // Dispose streams[i]->Dispose(); streams[i] = nullptr; break; case 2: // Destruct streams[i] = nullptr; break; } } } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_RandomCleanup", status); } // Do the random cleanup test again without reopening the log { // Note: this actually passes with the original bug, as only the streams array 'append' codepath is exercised Common::Threadpool::Post([&]() { Common::Random random(NumStreams); ILogicalLogReadStream::SPtr streams[NumStreams]; for (int i = 0; i < NumStreams; i++) { status = logicalLog->CreateReadStream(streams[i], 0); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } switch (random.Next() % 6) { case 0: case 1: case 2: // let it be cleaned up later break; case 3: // Close now status = SyncAwait(streams[i]->CloseAsync()); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } streams[i] = nullptr; break; case 4: // Dispose now streams[i]->Dispose(); streams[i] = nullptr; break; case 5: // Destruct now streams[i] = nullptr; break; } } for (int i = 0; i < NumStreams; i++) { if (streams[i] != nullptr) { switch (random.Next() % 3) { case 0: // Close status = SyncAwait(streams[i]->CloseAsync()); if (!NT_SUCCESS(status)) { taskComplete.SetEvent(); return; } streams[i] = nullptr; break; case 1: // Dispose streams[i]->Dispose(); streams[i] = nullptr; break; case 2: // Destruct streams[i] = nullptr; break; } } } status = STATUS_SUCCESS; taskComplete.SetEvent(); }); bool completed = taskComplete.WaitUntilSet(15000); VERIFY_IS_TRUE(completed); // Likely deadlocked if false VERIFY_STATUS_SUCCESS("OpenManyStreamsTest_RandomCleanup", status); } // Cleanup status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::BasicIOTest(__in KtlLoggerMode, __in KGuid const & physicalLogId) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KString::SPtr logicalLogName; GenerateUniqueFilename(logicalLogName); KGuid logicalLogId; logicalLogId.CreateNew(); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); static const LONG MaxLogBlkSize = 128 * 1024; // Prove simple recovery status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); const int recordSize = 131; // Prove we can write bytes KBuffer::SPtr x; PUCHAR xPtr; AllocBuffer(recordSize, x, xPtr); BuildDataBuffer(*x, 0, 0, recordSize); ValidateDataBuffer(*x, x->QuerySize(), 0, 0, 0, recordSize); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); status = SyncAwait(logicalLog->AppendAsync(*x, 0, x->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); VERIFY_ARE_EQUAL(recordSize, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushWithMarkerAsync", status); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; // Prove simple (non-null recovery - only one (asn 1) physical record in the log) status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(recordSize, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(recordSize, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); status = SyncAwait(logicalLog->AppendAsync(*x, 0, x->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); VERIFY_ARE_EQUAL(recordSize * 2, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushWithMarkerAsync", status); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; // Prove simple (non-null recovery) status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(recordSize * 2, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(recordSize * 2, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // Prove simple read and positioning works AllocBuffer(recordSize, x, xPtr); LONG bytesRead; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(recordSize, bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, 0, 0, recordSize); VERIFY_ARE_EQUAL(recordSize, logicalLog->ReadPosition); // Prove next sequential physical read works AllocBuffer(recordSize, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(recordSize, bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, 0, 0, recordSize); VERIFY_ARE_EQUAL(recordSize * 2, logicalLog->ReadPosition); // Positioning and reading partial and across physical records work int offset = 1; status = logicalLog->SeekForRead(offset, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); AllocBuffer(recordSize, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(recordSize, bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, offset, 0, recordSize); VERIFY_ARE_EQUAL(recordSize + offset, logicalLog->ReadPosition); // Prove reading a short record works x->Zero(); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(recordSize - 1, bytesRead); ValidateDataBuffer(*x, recordSize - 1, 0, offset, 0, recordSize); VERIFY_ARE_EQUAL(logicalLog->WritePosition, logicalLog->ReadPosition); // Prove reading at EOS works AllocBuffer(recordSize, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(0, bytesRead); VERIFY_ARE_EQUAL(logicalLog->WritePosition, logicalLog->ReadPosition); // Prove position beyond and just EOS and reading works LONGLONG currentPos; status = logicalLog->SeekForRead(1, Common::SeekOrigin::Enum::End); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); currentPos = logicalLog->ReadPosition; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(0, bytesRead); LONGLONG eos; status = logicalLog->SeekForRead(0, Common::SeekOrigin::Enum::End); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); eos = logicalLog->ReadPosition; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(0, bytesRead); VERIFY_ARE_EQUAL(logicalLog->WritePosition, eos); status = logicalLog->SeekForRead(-1, Common::SeekOrigin::Enum::End); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); currentPos = logicalLog->ReadPosition; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, 1, 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(1, bytesRead); ValidateDataBuffer(*x, 1, 0, currentPos, 0, recordSize); status = logicalLog->SeekForRead(-1, Common::SeekOrigin::Enum::End); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); currentPos = logicalLog->ReadPosition; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, 2, 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(1, bytesRead); ValidateDataBuffer(*x, 1, 0, currentPos, 0, recordSize); status = logicalLog->SeekForRead(-2, Common::SeekOrigin::Enum::End); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); currentPos = logicalLog->ReadPosition; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, 2, 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(2, bytesRead); ValidateDataBuffer(*x, 2, 0, currentPos, 0, recordSize); // Prove we can position forward to every location currentPos = eos - 1; while (currentPos >= 0) { status = logicalLog->SeekForRead(currentPos, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); VERIFY_ARE_EQUAL(currentPos, logicalLog->ReadPosition); KBuffer::SPtr rBuff; status = KBuffer::Create((ULONG)(eos - currentPos), rBuff, GetThisAllocator()); VERIFY_STATUS_SUCCESS("KBuffer::Create", status); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *rBuff, 0, rBuff->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(rBuff->QuerySize(), (ULONG)bytesRead); currentPos--; } // Prove Stream read abstraction works through a BufferedStream // (since we don't have a BufferedStream, use KStream) ILogicalLogReadStream::SPtr readStream; status = logicalLog->CreateReadStream(readStream, 0); VERIFY_STATUS_SUCCESS("LogicalLog::CreateReadStream", status); ktl::io::KStream::SPtr bStream = readStream.RawPtr(); bStream->Position = bStream->Length + 1; // seek to end + 1 currentPos = bStream->Position; ULONG uBytesRead; status = SyncAwait(bStream->ReadAsync(*x, uBytesRead, 0, x->QuerySize())); VERIFY_STATUS_SUCCESS("KStream::ReadAsync", status); VERIFY_ARE_EQUAL(0, uBytesRead); bStream->Position = bStream->Length; // seek to end eos = bStream->Position; VERIFY_ARE_EQUAL(logicalLog->WritePosition, eos); bStream->Position = bStream->Length - 1; // seek to end - 1 currentPos = bStream->Position; status = SyncAwait(bStream->ReadAsync(*x, uBytesRead, 0, 1)); VERIFY_STATUS_SUCCESS("KStream::ReadAsync", status); VERIFY_ARE_EQUAL(1, uBytesRead); ValidateDataBuffer(*x, 1, 0, currentPos, 0, recordSize); bStream->Position = bStream->Length - 1; // seek to end - 1 currentPos = bStream->Position; status = SyncAwait(bStream->ReadAsync(*x, uBytesRead, 0, 2)); VERIFY_STATUS_SUCCESS("KStream::ReadAsync", status); VERIFY_ARE_EQUAL(1, uBytesRead); ValidateDataBuffer(*x, 1, 0, currentPos, 0, recordSize); bStream->Position = bStream->Length - 2; // seek to end - 2 currentPos = bStream->Position; status = SyncAwait(bStream->ReadAsync(*x, uBytesRead, 0, 2)); VERIFY_STATUS_SUCCESS("KStream::ReadAsync", status); VERIFY_ARE_EQUAL(2, uBytesRead); ValidateDataBuffer(*x, 2, 0, currentPos, 0, recordSize); currentPos = eos - 1; while (currentPos >= 0) { bStream->Position = currentPos; KBuffer::SPtr rBuff; status = KBuffer::Create((ULONG)(eos - currentPos), rBuff, GetThisAllocator()); VERIFY_STATUS_SUCCESS("KBuffer::Create", status); status = SyncAwait(bStream->ReadAsync(*rBuff, uBytesRead, 0, rBuff->QuerySize())); VERIFY_STATUS_SUCCESS("KStream::ReadAsync", status); VERIFY_ARE_EQUAL(rBuff->QuerySize(), uBytesRead); currentPos--; } status = SyncAwait(bStream->CloseAsync()); VERIFY_STATUS_SUCCESS("KStream::CloseAsync", status); bStream = nullptr; readStream->Dispose(); // idempotent readStream = nullptr; status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->DeleteLogicalLogOnlyAsync(logicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("IPhysicalLogHandle::DeleteLogicalLogOnlyAsync", status); // Prove some large I/O status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); AllocBuffer(1024 * 1024, x, xPtr); BuildDataBuffer(*x, 0, 0, recordSize); status = SyncAwait(logicalLog->AppendAsync(*x, 0, x->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); VERIFY_ARE_EQUAL(1024 * 1024, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushWithMarkerAsync", status); AllocBuffer(1024 * 1024, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(x->QuerySize(), (ULONG)bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, 0, 0, recordSize); // Prove basic head truncation behavior status = SyncAwait(logicalLog->TruncateHead(128 * 1024)); VERIFY_STATUS_SUCCESS("LogicalLog::TruncateHead", status); VERIFY_ARE_EQUAL(128 * 1024, logicalLog->HeadTruncationPosition); // Force a record out to make sure the head truncation point is captured const KStringView testStr1(L"Test String Record"); AllocBuffer(testStr1.LengthInBytes(), x, xPtr); LPCWSTR str = testStr1; KMemCpySafe(xPtr, x->QuerySize(), str, testStr1.LengthInBytes()); status = SyncAwait(logicalLog->AppendAsync(*x, 0, x->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushAsync", status); // Prove head truncation point is recovered LONGLONG currentLength = logicalLog->WritePosition; LONGLONG currentTrucPoint = logicalLog->HeadTruncationPosition; status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(currentLength, logicalLog->WritePosition); VERIFY_ARE_EQUAL(currentTrucPoint, logicalLog->HeadTruncationPosition); // Prove basic tail truncation behavior status = logicalLog->SeekForRead(currentLength - x->QuerySize(), Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); LONGLONG newEos = logicalLog->ReadPosition; AllocBuffer(256, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); KString::SPtr chars; status = KString::Create(chars, GetThisAllocator(), bytesRead / sizeof(WCHAR)); VERIFY_STATUS_SUCCESS("KString::Create", status); chars->SetLength(chars->BufferSizeInChars()); KMemCpySafe((PBYTE)(PVOID)*chars, chars->LengthInBytes(), xPtr, (ULONG)bytesRead); VERIFY_ARE_EQUAL(testStr1, *chars); // Chop off the last and part of the 2nd to last records newEos = newEos - bytesRead - 1; status = SyncAwait(logicalLog->TruncateTail(newEos, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::TruncateTail", status); VERIFY_ARE_EQUAL(newEos, logicalLog->WritePosition); // Prove we can read valid up to the new EOS but not beyond status = logicalLog->SeekForRead(newEos - 128, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); AllocBuffer(256, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(128, bytesRead); ValidateDataBuffer(*x, bytesRead, 0, newEos - 128, 0, recordSize); // Prove we recover the correct tail position (WritePosition) status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(newEos, logicalLog->WritePosition); VERIFY_ARE_EQUAL(currentTrucPoint, logicalLog->HeadTruncationPosition); // Prove we can truncate all content via tail truncation VERIFY_ARE_NOT_EQUAL(0, logicalLog->Length); status = SyncAwait(logicalLog->TruncateTail(currentTrucPoint + 1, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::TruncateTail", status); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(currentTrucPoint + 1, logicalLog->WritePosition); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(currentTrucPoint + 1, logicalLog->WritePosition); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(currentTrucPoint, logicalLog->HeadTruncationPosition); // Add proof for truncating all but one byte - read it for the right value LONGLONG currentWritePos = logicalLog->WritePosition; AllocBuffer(1024 * 1024, x, xPtr); BuildDataBuffer(*x, currentWritePos, 0, recordSize); status = SyncAwait(logicalLog->AppendAsync(*x, 0, x->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); VERIFY_ARE_EQUAL(currentWritePos + (1024 * 1024), logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushWithMarkerAsync", status); status = logicalLog->SeekForRead(currentWritePos, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); VERIFY_ARE_EQUAL(currentWritePos, logicalLog->ReadPosition); AllocBuffer(1024 * 1024, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(x->QuerySize(), (ULONG)bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, currentWritePos, 0, recordSize); status = SyncAwait(logicalLog->TruncateHead(currentWritePos + (1024 * 513))); VERIFY_STATUS_SUCCESS("LogicalLog::TruncateHead", status); VERIFY_ARE_EQUAL(currentWritePos + (1024 * 513), logicalLog->HeadTruncationPosition); status = logicalLog->SeekForRead(currentWritePos + (1024 * 513) + 1, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); VERIFY_ARE_EQUAL(currentWritePos + (1024 * 513) + 1, logicalLog->ReadPosition); AllocBuffer((ULONG)logicalLog->Length, x, xPtr); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, x->QuerySize(), 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(x->QuerySize(), (ULONG)bytesRead); ValidateDataBuffer(*x, x->QuerySize(), 0, currentWritePos + (1024 * 513) + 1, 0, recordSize); status = SyncAwait(logicalLog->TruncateTail(currentWritePos + (1024 * 513) + 2, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::TruncateTail", status); VERIFY_ARE_EQUAL(1, logicalLog->Length); status = logicalLog->SeekForRead(currentWritePos + (1024 * 513) + 1, Common::SeekOrigin::Enum::Begin); VERIFY_STATUS_SUCCESS("LogicalLog::SeekForRead", status); VERIFY_ARE_EQUAL(currentWritePos + (1024 * 513) + 1, logicalLog->ReadPosition); ((PBYTE)x->GetBuffer())[0] = ~(((PBYTE)x->GetBuffer())[0]); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *x, 0, 1, 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::ReadAsync", status); VERIFY_ARE_EQUAL(1, bytesRead); ValidateDataBuffer(*x, 1, 0, currentWritePos + (1024 * 513) + 1, 0, recordSize); // Prove close down status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::WriteAtTruncationPointsTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState(logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KGuid logicalLogId; logicalLogId.CreateNew(); KString::SPtr logicalLogFileName; GenerateUniqueFilename(logicalLogFileName); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // Prove simple recovery status = SyncAwait(logicalLog->CloseAsync()); VERIFY_STATUS_SUCCESS("logicalLog->CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // // Test 1: Write all 1's from 0 - 999, truncate tail (newest data) at 500, write 2's at 500 - 599 // and read back verifying that 0 - 499 are 1's and 500-599 are 2's. Read back at 499, 500 and 501 // and verify that those are correct. // KBuffer::SPtr buffer1; PUCHAR buffer1Ptr; AllocBuffer(1000, buffer1, buffer1Ptr); for (int i = 0; i < 1000; i++) { buffer1Ptr[i] = 1; } status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL(1000, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); status = SyncAwait(logicalLog->TruncateTail(500, CancellationToken::None)); VERIFY_STATUS_SUCCESS("TruncateTail", status); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); VERIFY_ARE_EQUAL(500, logicalLog->WritePosition); KBuffer::SPtr buffer2; PUCHAR buffer2Ptr; AllocBuffer(100, buffer2, buffer2Ptr); for (int i = 0; i < 100; i++) { buffer2Ptr[i] = 2; } status = SyncAwait(logicalLog->AppendAsync(*buffer2, 0, buffer2->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL(600, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); KBuffer::SPtr bufferRead; PUCHAR bufferReadPtr; AllocBuffer(600, bufferRead, bufferReadPtr); LONG bytesRead; status = SyncAwait(logicalLog->ReadAsync(bytesRead, *bufferRead, 0, 600, 0, CancellationToken::None)); VERIFY_STATUS_SUCCESS("Read", status); for (int i = 0; i < 500; i++) { VERIFY_ARE_EQUAL(1, bufferReadPtr[i]); } for (int i = 500; i < 600; i++) { VERIFY_ARE_EQUAL(2, bufferReadPtr[i]); } bufferReadPtr[0] = 0; status = logicalLog->SeekForRead(499, SeekOrigin::Begin); VERIFY_STATUS_SUCCESS("SeekForRead", status); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *bufferRead, 0, 1, 0, CancellationToken::None)); VERIFY_ARE_EQUAL(1, bufferReadPtr[0]); bufferReadPtr[0] = 0; status = logicalLog->SeekForRead(500, SeekOrigin::Begin); VERIFY_STATUS_SUCCESS("SeekForRead", status); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *bufferRead, 0, 1, 0, CancellationToken::None)); VERIFY_ARE_EQUAL(2, bufferReadPtr[0]); bufferReadPtr[0] = 0; status = logicalLog->SeekForRead(501, SeekOrigin::Begin); VERIFY_STATUS_SUCCESS("SeekForRead", status); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *bufferRead, 0, 1, 0, CancellationToken::None)); VERIFY_ARE_EQUAL(2, bufferReadPtr[0]); // // Test 2: Truncate head (oldest data) at 500 and try to truncate tail (newest data) to 490 and expect failure. // Truncate tail back to 500 and then write and then read back // status = SyncAwait(logicalLog->TruncateHead(499)); VERIFY_STATUS_SUCCESS("TruncateHead", status); status = SyncAwait(logicalLog->TruncateTail(490, CancellationToken::None)); VERIFY_IS_FALSE(NT_SUCCESS(status)); status = SyncAwait(logicalLog->TruncateTail(500, CancellationToken::None)); VERIFY_STATUS_SUCCESS("TruncateTail", status); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); KBuffer::SPtr buffer3; PUCHAR buffer3Ptr; AllocBuffer(50, buffer3, buffer3Ptr); for (int i = 0; i < 50; i++) { buffer3Ptr[i] = 3; } status = SyncAwait(logicalLog->AppendAsync(*buffer3, 0, buffer3->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL(550, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); KBuffer::SPtr bufferRead3; PUCHAR bufferRead3Ptr; AllocBuffer(50, bufferRead3, bufferRead3Ptr); for (int i = 0; i < 50; i++) { bufferRead3Ptr[i] = 0; } status = logicalLog->SeekForRead(500, SeekOrigin::Begin); VERIFY_STATUS_SUCCESS("SeekForRead", status); status = SyncAwait(logicalLog->ReadAsync(bytesRead, *bufferRead3, 0, 50, 0, CancellationToken::None)); for (int i = 0; i < 50; i++) { VERIFY_ARE_EQUAL(3, bufferRead3Ptr[i]); } // // Test 3: truncate tail all the way back to the head // auto headTruncationPosition = logicalLog->HeadTruncationPosition; status = SyncAwait(logicalLog->TruncateHead(headTruncationPosition + 1)); VERIFY_STATUS_SUCCESS("TruncateHead", status); // Prove close down status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::RemoveFalseProgressTest(__in KtlLoggerMode) { // Main line test NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState(logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KGuid logicalLogId; logicalLogId.CreateNew(); KString::SPtr logicalLogFileName; GenerateUniqueFilename(logicalLogFileName); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // // Test 1: Write 100000 bytes and then close the log. Reopen and then truncate // tail at 80000. Next write and flush 1000 more. Verify no failure on last // write. // KBuffer::SPtr buffer1; PUCHAR buffer1Ptr; AllocBuffer(1000, buffer1, buffer1Ptr); for (int i = 0; i < 1000; i++) { buffer1Ptr[i] = 1; } for (int i = 0; i < 100; i++) { status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL((i + 1) * 1000, logicalLog->WritePosition); } status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = SyncAwait(logicalLog->TruncateTail(80000, CancellationToken::None)); VERIFY_STATUS_SUCCESS("TruncateTail", status); status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); // Prove close down status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::ReadAheadCacheTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KString::SPtr logicalLogName; GenerateUniqueFilename(logicalLogName); KGuid logicalLogId; logicalLogId.CreateNew(); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); static const LONG MaxLogBlkSize = 1024 * 1024; // // Write a nice pattern in the log which would be easy to validate the data // LONG dataSize = 16 * 1024 * 1024; // 16MB LONG chunkSize = 1024; LONG prefetchSize = 1024 * 1024; LONG loops = dataSize / chunkSize; KBuffer::SPtr bufferBigK, buffer1K; PUCHAR bufferBig, buffer1; AllocBuffer(2 * prefetchSize, bufferBigK, bufferBig); AllocBuffer(chunkSize, buffer1K, buffer1); for (LONG i = 0; i < loops; i++) { LONGLONG pos = i * chunkSize; BuildDataBuffer(*buffer1K, pos); // // TODO: Fix buffer1K to be correct size. Add 1 to work around bug in KFileStream::WriteAsync // where a full KBuffer cannot be written // status = SyncAwait(logicalLog->AppendAsync(*buffer1K, 0, buffer1K->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::AppendAsync", status); } status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::FlushWithMarkerAsync", status); // // Verify length // VERIFY_IS_TRUE(logicalLog->GetLength() == dataSize); VERIFY_IS_TRUE(logicalLog->GetWritePosition() == dataSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; // // Reopen to verify length // status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); // // Verify length // VERIFY_IS_TRUE(logicalLog->GetLength() == dataSize); VERIFY_IS_TRUE(logicalLog->GetWritePosition() == dataSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; // // Test 1: Sequentially read through file and verify that data is correct // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 1: Sequentially read through file and verify that data is correct"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_STATUS_SUCCESS("LogicalLog::CreateReadStream", status); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); for (LONG i = 0; i < loops; i++) { ULONG read; status = SyncAwait(stream->ReadAsync(*buffer1K, read, 0, chunkSize)); VERIFY_STATUS_SUCCESS("LogicalLogReadStream::ReadAsync", status); LONGLONG pos = i * chunkSize; ValidateDataBuffer(*buffer1K, read, 0, pos); } status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 2: Read at the end of the file to trigger a prefetch read beyond the end of the file is where the // last prefetch isn't a full record. // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 2: Read at the end of the file to trigger a prefetch read beyond the end of the file is where the last prefetch isn't a full record."); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); LONGLONG pos = dataSize - (prefetchSize + (prefetchSize / 2)); stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer1K, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*buffer1K, read, 0, pos); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 3: Read at the end of the file to trigger a prefetch read that is exactly the end of the file. // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 3: Read at the end of the file to trigger a prefetch read that is exactly the end of the file."); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); LONGLONG pos = dataSize - 2 * prefetchSize; stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer1K, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*buffer1K, read, 0, pos); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 4: Read at end of file where read isn't a full record and prefetch read is out of bounds. // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 4: Read at end of file where read isn't a full record and prefetch read is out of bounds."); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); LONGLONG pos = dataSize - (prefetchSize / 2); stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer1K, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*buffer1K, read, 0, pos); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 5: Read beyond end of file. // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 5: Read beyond end of file."); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); LONGLONG pos = dataSize - 1; stream->SetPosition(pos /*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer1K, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*buffer1K, read, 0, pos); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 6: Random access reads of less than a prefetch record size and verify that data is correct // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 6: Random access reads of less than a prefetch record size and verify that data is correct"); Common::Random random((int)GetTickCount64()); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // TODO: replace 32 with 1024. Workaround for Rich's bug for (LONG i = 0; i < 32; i++) { ULONG len = random.Next() % (prefetchSize - 1); KBuffer::SPtr buffer; PUCHAR b; AllocBuffer(len, buffer, b); // // Pick a random place but do not go beyond end of file // or into the space already truncated head // LONGLONG r = random.Next(); LONGLONG m = (dataSize - (prefetchSize + 4096 + len)); LONGLONG pos = (r % m); pos = pos + (prefetchSize + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); // TODO: Remove this when I feel good about the math CODING_ERROR_ASSERT(pos >= (prefetchSize + 4096)); TestCommon::TestSession::WriteInfo(TraceComponent, "pos: {0}, len: {1}, dataSize {2}", pos, len, dataSize); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer, read, 0, len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); CODING_ERROR_ASSERT(len == read); VERIFY_IS_TRUE(len == read); ValidateDataBuffer(*buffer, read, 0, pos); } status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); logicalLog = nullptr; } { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 6a: Specific read pattern"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); LONG count = 56; KArray<LONG> pos1(GetThisAllocator(), count, count); KArray<LONG> len1(GetThisAllocator(), count, count); pos1.SetCount(count); len1.SetCount(count); pos1[0] = 6643136; len1[0] = 284158; pos1[1] = 8749250; len1[1] = 719631; pos1[2] = 7968798; len1[2] = 217852; pos1[3] = 5589085; len1[3] = 37828; pos1[4] = 8951191; len1[4] = 658471; pos1[5] = 2036603; len1[5] = 779626; pos1[6] = 13515405; len1[6] = 753509; pos1[7] = 2026546; len1[7] = 127354; pos1[8] = 12065124; len1[8] = 485889; pos1[9] = 2922527; len1[9] = 748745; pos1[10] = 12362362; len1[10] = 324286; pos1[11] = 15079374; len1[11] = 411635; pos1[12] = 308588; len1[12] = 515382; pos1[13] = 7394979; len1[13] = 535056; pos1[14] = 9878541; len1[14] = 445104; pos1[15] = 6615835; len1[15] = 924314; pos1[16] = 11835666; len1[16] = 259902; pos1[17] = 8862263; len1[17] = 949164; pos1[18] = 5386414; len1[18] = 517708; pos1[19] = 11259477; len1[19] = 675057; pos1[20] = 14395727; len1[20] = 973734; pos1[21] = 9391625; len1[21] = 1021568; pos1[22] = 298673; len1[22] = 858879; pos1[23] = 11966559; len1[23] = 170338; pos1[24] = 5228510; len1[24] = 331768; pos1[25] = 12273354; len1[25] = 711678; pos1[26] = 13006046; len1[26] = 865901; pos1[27] = 8447558; len1[27] = 519960; pos1[28] = 12824484; len1[28] = 10713; pos1[29] = 3156718; len1[29] = 55952; pos1[30] = 9152582; len1[30] = 1018119; pos1[31] = 365742; len1[31] = 953577; pos1[32] = 5241993; len1[32] = 706563; pos1[33] = 32648; len1[33] = 791071; pos1[34] = 8868714; len1[34] = 983844; pos1[35] = 2129328; len1[35] = 658494; pos1[36] = 246918; len1[36] = 101502; pos1[37] = 6577103; len1[37] = 266030; pos1[38] = 12713793; len1[38] = 814882; pos1[39] = 7880614; len1[39] = 107285; pos1[40] = 12539585; len1[40] = 898134; pos1[41] = 1772169; len1[41] = 145642; pos1[42] = 1857848; len1[42] = 971131; pos1[43] = 6954824; len1[43] = 620271; pos1[44] = 6379690; len1[44] = 231407; pos1[45] = 11807777; len1[45] = 576393; pos1[46] = 7501047; len1[46] = 291417; pos1[47] = 5570240; len1[47] = 763674; pos1[48] = 15955814; len1[48] = 1591; pos1[49] = 7792962; len1[49] = 967045; pos1[50] = 2646688; len1[50] = 277177; pos1[51] = 12045117; len1[51] = 820311; pos1[52] = 8775100; len1[52] = 723454; pos1[53] = 13038687; len1[53] = 699561; pos1[54] = 1578657; len1[54] = 591083; pos1[55] = 3419389; len1[55] = 778550; for (LONG i = 0; i < count; i++) { ULONG len = len1[i]; KBuffer::SPtr buffer; PUCHAR b; AllocBuffer(len, buffer, b); // // Pick a random place but do not go beyond end of file // LONGLONG pos = pos1[i]; stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer, read, 0, len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(len == read); ValidateDataBuffer(*buffer, read, 0, pos); } status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); logicalLog = nullptr; } { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 6b: Specific read pattern"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); for (LONG i = 0; i < 4; i++) { ULONG len = 996198; KBuffer::SPtr buffer; PUCHAR b; AllocBuffer(len, buffer, b); // // Pick a random place but do not go beyond end of file // LONGLONG pos = 15117795; stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer, read, 0, len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(len == read); ValidateDataBuffer(*buffer, read, 0, pos); } status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 7: Random access reads of more than a prefetch record size and verify that data is correct // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 7: Random access reads of more than a prefetch record size and verify that data is correct"); Common::Random random((int)GetTickCount64()); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // TODO: replace 32 with 1024 when Rich fixes for (LONG i = 0; i < 32; i++) { ULONG len = random.Next() % (3 * prefetchSize); KBuffer::SPtr buffer; PUCHAR b; AllocBuffer(len, buffer, b); // // Pick a random place but do not go beyond end of file // LONGLONG r = random.Next(); LONGLONG m = (dataSize - (prefetchSize + 4096 + len)); LONGLONG pos = (r % m); pos = pos + (prefetchSize + 4096); // TODO: Remove this when I feel good about the math CODING_ERROR_ASSERT(pos >= (prefetchSize + 4096)); stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*buffer, read, 0, len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(len == read); ValidateDataBuffer(*buffer, read, 0, pos); } status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 8: Read section of file and then truncate head in the middle of the read buffer. Ensure reading truncated // space fails and untruncated succeeds // // // Test 9: Read section of file and then truncate head in the middle of the prefetch read buffer. Ensure reading truncated // space fails and untruncated succeeds // { LONGLONG pos; ULONG read; TestCommon::TestSession::WriteInfo(TraceComponent, "Test 9: Read section of file and then truncate head in the middle of the prefetch read buffer. Ensure reading truncated space fails and untruncated succeeds"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // // Perform gratuitous read to ensure read stream is // initialized // status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); // // truncate head in the middle of the prefetch buffer // TestCommon::TestSession::WriteInfo(TraceComponent, "Truncate head at {0}", prefetchSize + 4096); status = SyncAwait(logicalLog->TruncateHead(prefetchSize + 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); #if 0 // Test only for KtlLogger // // reads should not work // status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 0); pos = 4096; stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 0); pos = prefetchSize + 256; stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 0); #endif // // read in untruncated space // pos = prefetchSize + 4096 + 512; stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*bufferBigK, read, 0, pos); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 10: Read section of file and then truncate tail in the middle of the read buffer. Ensure reading truncated // space fails and untruncated succeeds // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 10: Read section of file and then truncate tail in the middle of the read buffer. Ensure reading truncated space fails and untruncated succeeds"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // // Test 10a: Fill read buffer and truncate tail ahead of it. Verify that only data before truncate tail // is read and is correct // TestCommon::TestSession::WriteInfo(TraceComponent, "Test 10a: Fill read buffer and truncate tail ahead of it. Verify that only data before truncate tail is read and is correct"); LONGLONG pos = dataSize - (16384 + 4096); LONGLONG tailTruncatePos = pos + (8192 + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 16384)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 8192); ValidateDataBuffer(*bufferBigK, read, 0, pos); // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); // // Test 10b: Fill read buffer and truncate before current read pointer. Verify no data read // TestCommon::TestSession::WriteInfo(TraceComponent, "Test 10b: Fill read buffer and truncate before current read pointer. Verify no data read"); pos = dataSize - (16384 + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 4096); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; tailTruncatePos = pos - 128; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 0); // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); // // Test 10c: Fill read buffer and overwrite it with different data. Continue reading and verify that // new data is read // TestCommon::TestSession::WriteInfo(TraceComponent, "Test 10c: Fill read buffer and overwrite it with different data. Continue reading and verify that new data is read"); pos = dataSize - (16384 + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 4096); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; tailTruncatePos = pos - 128; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); LONGLONG fillSize = dataSize - tailTruncatePos; KBuffer::SPtr fillBuffer; PUCHAR b; AllocBuffer(static_cast<LONG>(fillSize), fillBuffer, b); BuildDataBuffer(*fillBuffer, tailTruncatePos, 5); status = SyncAwait(logicalLog->AppendAsync(*fillBuffer, 0, (LONG)fillSize, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 256)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 256); ValidateDataBuffer(*bufferBigK, read, 0, pos, 5); pos += read; // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 11: Read section of file and then truncate tail in the middle of the prefetch read buffer. Ensure reading truncated // space fails and untruncated succeeds // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 11: Read section of file and then truncate tail in the middle of the prefetch read buffer. Ensure reading truncated space fails and untruncated succeeds"); ILogicalLogReadStream::SPtr stream; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // // Test 11a: Fill read buffer and truncate tail ahead of it. Verify that only data before truncate tail // is read and is correct // TestCommon::TestSession::WriteInfo(TraceComponent, "Test 11a: Fill read buffer and truncate tail ahead of it. Verify that only data before truncate tail is read and is correct"); LONGLONG pos = dataSize - (prefetchSize + 16384 + 4096); LONGLONG tailTruncatePos = pos + (prefetchSize + 8192 + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); ULONG read; status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 16384 + prefetchSize)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == static_cast<ULONG>(8192 + prefetchSize)); ValidateDataBuffer(*bufferBigK, read, 0, pos); // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); // // Test 11c: Fill read buffer and overwrite it with different data. Continue reading and verify that // new data is read // TestCommon::TestSession::WriteInfo(TraceComponent, "Test 11c: Fill read buffer and overwrite it with different data. Continue reading and verify that new data is read"); pos = dataSize - (prefetchSize + 16384 + 4096); stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 4096); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; tailTruncatePos = (pos + prefetchSize) - 128; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); LONGLONG fillSize = dataSize - tailTruncatePos; KBuffer::SPtr fillBuffer; PUCHAR b; AllocBuffer(static_cast<ULONG>(fillSize), fillBuffer, b); BuildDataBuffer(*fillBuffer, tailTruncatePos, 5); status = SyncAwait(logicalLog->AppendAsync(*fillBuffer, 0, (LONG)fillSize, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); LONGLONG read1Len = tailTruncatePos - pos; status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, (LONG)read1Len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == (ULONG)read1Len); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; LONGLONG read2Len = dataSize - tailTruncatePos; status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, (LONG)read2Len)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == (ULONG)read2Len); ValidateDataBuffer(*bufferBigK, read, 0, pos, 5); pos += read; // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 12: Write at the end of the file within the read buffer and verify that read succeeds with correct data // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 12: Write at the end of the file within the read buffer and verify that read succeeds with correct data"); ILogicalLogReadStream::SPtr stream; ULONG read; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_STATUS_SUCCESS("LogicalLog::CreateReadStream", status); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // // Perform gratuitous read to ensure read stream is // initialized // status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); // // Truncate tail to make space at the end of the file and then read at the end of the file to fill // read buffer. Write at end of file and then continue to read the new data. // LONGLONG pos = dataSize - (16384 + 4096); LONGLONG tailTruncatePos = pos + 4096; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 2048)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 2048); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; LONGLONG fillSize = dataSize - tailTruncatePos; KBuffer::SPtr fillBuffer; PUCHAR b; AllocBuffer(static_cast<ULONG>(fillSize + 1), fillBuffer, b); BuildDataBuffer(*fillBuffer, tailTruncatePos, 7); status = SyncAwait(logicalLog->AppendAsync(*fillBuffer, 0, (LONG)fillSize, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 4096)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 4096); ValidateDataBuffer(*bufferBigK, 2048, 0, pos); ValidateDataBuffer(*bufferBigK, read - 2048, 2048, pos + 2048, 7); pos += read; // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; } // // Test 13: Write at the end of the file within the prefetch buffer and verify that read succeeds with correct data // { TestCommon::TestSession::WriteInfo(TraceComponent, "Test 13: Write at the end of the file within the prefetch buffer and verify that read succeeds with correct data"); ILogicalLogReadStream::SPtr stream; ULONG read; status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); status = logicalLog->CreateReadStream(stream, prefetchSize); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(stream->GetLength() == logicalLog->GetLength()); // // Perform gratuitous read to ensure read stream is // initialized // status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, chunkSize)); // // Truncate tail to make space at the end of the file and then read at the end of the file to fill // read buffer. Write at end of file and then continue to read the new data. // LONGLONG pos = dataSize - (16384 + 4096 + prefetchSize); LONGLONG tailTruncatePos = pos + 4096 + prefetchSize; status = SyncAwait(logicalLog->TruncateTail(tailTruncatePos, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); stream->SetPosition(pos/*, SeekOrigin.Begin*/); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, 2048)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == 2048); ValidateDataBuffer(*bufferBigK, read, 0, pos); pos += read; LONGLONG fillSize = dataSize - tailTruncatePos; KBuffer::SPtr fillBuffer; PUCHAR b; AllocBuffer(static_cast<ULONG>(fillSize), fillBuffer, b); BuildDataBuffer(*fillBuffer, tailTruncatePos, 9); status = SyncAwait(logicalLog->AppendAsync(*fillBuffer, 0, (LONG)fillSize, CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_IS_TRUE(NT_SUCCESS(status)); ULONG readExpected = (16384 + 2048 + prefetchSize); status = SyncAwait(stream->ReadAsync(*bufferBigK, read, 0, readExpected)); VERIFY_IS_TRUE(NT_SUCCESS(status)); VERIFY_IS_TRUE(read == readExpected); LONG firstRead = prefetchSize + 2048; ValidateDataBuffer(*bufferBigK, firstRead, 0, pos); ValidateDataBuffer(*bufferBigK, readExpected - firstRead, firstRead, pos + firstRead, 9); pos += read; // // Overwrite end of file to bring back to original state // RestoreEOFState(*logicalLog, dataSize, prefetchSize); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; //* Cleanup status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } } VOID LogTestBase::TruncateInDataBufferTest(__in KtlLoggerMode ktlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState(logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KGuid logicalLogId; logicalLogId.CreateNew(); KString::SPtr logicalLogFileName; GenerateUniqueFilename(logicalLogFileName); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // // Test 1: Write a whole bunch of stuff to the log and then flush to be sure the logical log // write buffer is empty. Next write less than a write buffer's worth to fill the write buffer // with some data but do not flush. TruncateTail at an offset that is in the write buffer and // verify success. // KBuffer::SPtr buffer1; PUCHAR buffer1Ptr; AllocBuffer(1000, buffer1, buffer1Ptr); for (int i = 0; i < 1000; i++) { buffer1Ptr[i] = 1; } for (int i = 0; i < 100; i++) { status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL((i + 1) * 1000, logicalLog->WritePosition); } status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); auto truncateTailPosition = logicalLog->WritePosition - 50; status = SyncAwait(logicalLog->TruncateTail(truncateTailPosition, CancellationToken::None)); VERIFY_STATUS_SUCCESS("TruncateTail", status); status = SyncAwait(logicalLog->CloseAsync()); VERIFY_STATUS_SUCCESS("logicalLog->CloseAsync", status); logicalLog = nullptr; // // prove truncate tail succeeded // status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); VERIFY_ARE_EQUAL(truncateTailPosition, logicalLog->WritePosition); status = SyncAwait(logicalLog->CloseAsync()); VERIFY_STATUS_SUCCESS("logicalLog->CloseAsync", status); logicalLog = nullptr; // // Test 2: Prove that TruncateHead eventually happens // status = OpenLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); for (int i = 0; i < 100; i++) { status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); } status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); auto truncateHeadPosition = logicalLog->WritePosition - 50; status = SyncAwait(logicalLog->FlushAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushAsync", status); status = SyncAwait(logicalLog->TruncateHead(truncateHeadPosition)); VERIFY_STATUS_SUCCESS("TruncateHead", status); // // Write after the truncate head to help force the truncate to happen // status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarker", status); // // prove HeadTruncationPosition cannot be moved backwards // status = SyncAwait(logicalLog->TruncateHead(truncateHeadPosition - 1)); VERIFY_STATUS_SUCCESS("TruncateHead", status); VERIFY_ARE_EQUAL(truncateHeadPosition, logicalLog->HeadTruncationPosition); KNt::Sleep(60 * 1000); // todo: Can I make this shorter???? status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; // // prove truncate head succeeded // KtlLogManager::SPtr physicalLogManager; status = CreateKtlLogManager(ktlLoggerMode, GetThisAllocator(), physicalLogManager); VERIFY_STATUS_SUCCESS("KtlLogManager::Create", status); status = SyncAwait(physicalLogManager->OpenLogManagerAsync(nullptr, nullptr)); VERIFY_STATUS_SUCCESS("OpenLogManagerAsync", status); KtlLogContainer::SPtr physicalLogContainer; KtlLogManager::AsyncOpenLogContainer::SPtr openLogContainerContext; status = physicalLogManager->CreateAsyncOpenLogContainerContext(openLogContainerContext); VERIFY_STATUS_SUCCESS("CreateAsyncOpenLogContainerContext", status); status = SyncAwait(openLogContainerContext->OpenLogContainerAsync(*physicalLogName, physicalLogId, nullptr, physicalLogContainer)); VERIFY_STATUS_SUCCESS("OpenLogContainer", status); KtlLogStream::SPtr physicalLogStream; KtlLogContainer::AsyncOpenLogStreamContext::SPtr openLogStreamContext; status = physicalLogContainer->CreateAsyncOpenLogStreamContext(openLogStreamContext); VERIFY_STATUS_SUCCESS("CreateAsyncOpenLogStreamContext", status); ULONG maxMS; status = SyncAwait(openLogStreamContext->OpenLogStreamAsync(logicalLogId, &maxMS, physicalLogStream, nullptr)); VERIFY_STATUS_SUCCESS("OpenLogStream", status); KtlLogStream::AsyncQueryRecordRangeContext::SPtr queryRecordRangeContext; status = physicalLogStream->CreateAsyncQueryRecordRangeContext(queryRecordRangeContext); VERIFY_STATUS_SUCCESS("CreateAsyncQueryRecordRangeContext", status); KSynchronizer synch; RvdLogAsn truncationLsn; queryRecordRangeContext->StartQueryRecordRange(nullptr, nullptr, &truncationLsn, nullptr, synch.AsyncCompletionCallback()); status = synch.WaitForCompletion(); VERIFY_STATUS_SUCCESS("QueryRecordRange", status); VERIFY_ARE_NOT_EQUAL(static_cast<RvdLogAsn>(0), truncationLsn); status = SyncAwait(physicalLogStream->CloseAsync(nullptr)); VERIFY_STATUS_SUCCESS("CloseAsync", status); physicalLogStream = nullptr; status = SyncAwait(physicalLogContainer->CloseAsync(nullptr)); VERIFY_STATUS_SUCCESS("CloseAsync", status); physicalLogContainer = nullptr; status = SyncAwait(physicalLogManager->CloseLogManagerAsync(nullptr)); VERIFY_STATUS_SUCCESS("CloseLogManagerAsync", status); physicalLogManager = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::SequentialAndRandomStreamTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState(logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KGuid logicalLogId; logicalLogId.CreateNew(); KString::SPtr logicalLogFileName; GenerateUniqueFilename(logicalLogFileName); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // // Write a lot of stuff to the log in short records and then read it back sequentially // using a random access stream and a sequential access stream. Expect the sequential // access stream to run much faster // KBuffer::SPtr buffer1; PUCHAR buffer1Ptr; AllocBuffer(1000, buffer1, buffer1Ptr); for (int i = 0; i < 1000; i++) { buffer1Ptr[i] = 1; } for (int i = 0; i < 10000; i++) { status = SyncAwait(logicalLog->AppendAsync(*buffer1, 0, buffer1->QuerySize(), CancellationToken::None)); VERIFY_STATUS_SUCCESS("AppendAsync", status); VERIFY_ARE_EQUAL((i + 1) * 1000, logicalLog->WritePosition); status = SyncAwait(logicalLog->FlushWithMarkerAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("FlushWithMarkerAsync", status); } TestCommon::TestSession::WriteInfo(TraceComponent, "Data written...."); ILogicalLogReadStream::SPtr rsStream; Common::Stopwatch rTime; Common::Stopwatch sTime; Common::Random r; KBuffer::SPtr buffer2; PUCHAR buffer2Ptr; AllocBuffer(10000, buffer2, buffer2Ptr); // // Verify random faster for random access // status = logicalLog->CreateReadStream(rsStream, 1024 * 1024); VERIFY_STATUS_SUCCESS("CreateReadStream", status); sTime.Start(); for (int i = 0; i < 1000; i++) { LONGLONG offset = r.Next(999 * 1000); rsStream->SetPosition(offset); ULONG bytesRead; status = SyncAwait(rsStream->ReadAsync(*buffer2, bytesRead, 0, buffer2->QuerySize())); VERIFY_STATUS_SUCCESS("ReadAsync", status); } sTime.Stop(); logicalLog->SetSequentialAccessReadSize(*rsStream, 0); rsStream->SetPosition(0); rTime.Start(); for (int i = 0; i < 1000; i++) { LONGLONG offset = r.Next(999 * 1000); rsStream->SetPosition(offset); ULONG bytesRead; status = SyncAwait(rsStream->ReadAsync(*buffer2, bytesRead, 0, buffer2->QuerySize())); VERIFY_STATUS_SUCCESS("ReadAsync", status); } rTime.Stop(); TestCommon::TestSession::WriteInfo(TraceComponent, "Sequential Time: {0} Random Time: {1}", sTime.ElapsedMilliseconds, rTime.ElapsedMilliseconds); VERIFY_IS_TRUE(rTime.ElapsedMilliseconds < sTime.ElapsedMilliseconds); status = SyncAwait(logicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); logicalLog = nullptr; status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } ktl::Awaitable<NTSTATUS> LogTestBase::TruncateLogicalLogs( __in ILogicalLog::SPtr logicalLogs[], __in int numLogicalLogs) { static KAsyncEvent truncateLock(FALSE, TRUE); AsyncLockBlock(truncateLock) { for (int i = 0; i < numLogicalLogs; i++) { ILogicalLog& logicalLog = *logicalLogs[i]; LONGLONG toTruncate = logicalLog.GetWritePosition(); NTSTATUS status = co_await logicalLog.TruncateHead(toTruncate); if (status == K_STATUS_API_CLOSED) { TestCommon::TestSession::WriteInfo(TraceComponent, "TruncateHead failure (already closed) {0}", status); } else if (!NT_SUCCESS(status)) { TestCommon::TestSession::WriteInfo(TraceComponent, "TruncateHead failure. toTruncate: {0}, status: {1}", toTruncate, status); KInvariant(FALSE); } else { TestCommon::TestSession::WriteInfo(TraceComponent, "TruncateHead success. toTruncate: {0}", toTruncate); } } } co_return STATUS_SUCCESS; } ktl::Awaitable<void> LogTestBase::ReadWriteCloseRaceWorker( __in ILogicalLog& logicalLog, __in int maxSize, __in ILogicalLog::SPtr logicalLogs[], __in int numLogicalLogs, __inout volatile LONGLONG & amountWritten, __inout volatile ULONGLONG & numTruncates, __in int fileSize, __in int taskId, __in CancellationToken const & cancellationToken) { LONGLONG bytes = 0; Common::Random rnd; NTSTATUS status; KFinally([taskId, &bytes] { TestCommon::TestSession::WriteInfo(TraceComponent, "Exit task {0} bytes {1}", taskId, bytes); }); do { KBuffer::SPtr recordBuffer; auto toWrite = rnd.Next(80, maxSize); status = KBuffer::Create(toWrite, recordBuffer, GetThisAllocator(), GetThisAllocationTag()); VERIFY_STATUS_SUCCESS("KBuffer::Create", status); status = co_await logicalLog.AppendAsync(*recordBuffer, 0, recordBuffer->QuerySize(), CancellationToken::None); if (status == K_STATUS_API_CLOSED) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} AppendAsync failure (already closed) {1}", taskId, status); co_return; } else if (!NT_SUCCESS(status)) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} AppendAsync failure {1}", taskId, status); KInvariant(FALSE); } bytes += toWrite; InterlockedAdd64(&amountWritten, max(toWrite, 4 * 1024)); // small writes will still reserve 4k status = co_await logicalLog.FlushWithMarkerAsync(CancellationToken::None); if (status == K_STATUS_API_CLOSED) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} FlushWithMarkerAsync failure (already closed) {1}", taskId, status); co_return; } else if (!NT_SUCCESS(status)) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} FlushWithMarkerAsync failure {1}", taskId, status); KInvariant(FALSE); } LONGLONG snapAmountWritten; while ((snapAmountWritten = amountWritten) >= (fileSize / 2)) { LONGLONG trySwap = InterlockedCompareExchange64(&amountWritten, 0, snapAmountWritten); if (trySwap == snapAmountWritten) { ULONGLONG currentTruncateIteration = InterlockedIncrement64((volatile LONGLONG*) &numTruncates); status = co_await TruncateLogicalLogs(logicalLogs, numLogicalLogs); if (!NT_SUCCESS(status)) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} TruncateLogicalLogs iteration {1} failure {2}", taskId, currentTruncateIteration, status); KInvariant(FALSE); } else { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} TruncateLogicalLogs iteration {1} success.", taskId, currentTruncateIteration); } } } LONG bytesRead; status = co_await logicalLog.ReadAsync(bytesRead, *recordBuffer, 0, recordBuffer->QuerySize(), 0, CancellationToken::None); if (status == K_STATUS_API_CLOSED) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} ReadAsync failure (already closed) {1}", taskId, status); co_return; } else if (status == STATUS_NOT_FOUND) { KInvariant(numTruncates > 0); TestCommon::TestSession::WriteWarning(TraceComponent, "Task {0} ReadAsync failure (not found) {1}. Expected when the logs were just fully truncated by this (or another) thread.", taskId, status); } else if (!NT_SUCCESS(status)) { TestCommon::TestSession::WriteInfo(TraceComponent, "Task {0} ReadAsync failure {1}", taskId, status); KInvariant(FALSE); } } while (!cancellationToken.IsCancellationRequested); co_return; } VOID LogTestBase::ReadWriteCloseRaceTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); const int NumAwaitables = 16; const int NumCloseAwaitables = NumAwaitables / 2; const int MaxLogBlockSize = 128 * 1024; CancellationTokenSource::SPtr cts; status = CancellationTokenSource::Create(GetThisAllocator(), GetThisAllocationTag(), cts); VERIFY_STATUS_SUCCESS("CancellationTokenSource::Create", status); Awaitable<void> awaitables[NumAwaitables]; ILogicalLog::SPtr logicalLogs[NumAwaitables]; for (int i = 0; i < NumAwaitables; i++) { KGuid logicalLogId; logicalLogId.CreateNew(); TestCommon::TestSession::WriteInfo(TraceComponent, "Log {0} is {1}", i, Common::Guid(logicalLogId).ToString().c_str()); KString::SPtr logFilename; GenerateUniqueFilename(logFilename); status = CreateLogicalLog(*physicalLog, logicalLogId, *logFilename, logicalLogs[i]); // todo: override other params VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); status = SyncAwait(logicalLogs[i]->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("CloseAsync", status); logicalLogs[i] = nullptr; status = OpenLogicalLog(*physicalLog, logicalLogId, *logFilename, logicalLogs[i]); VERIFY_STATUS_SUCCESS("OpenLogicalLog", status); } const int fileSize = 1024 * 1024 * 100; // todo: define this in a single place volatile LONGLONG amountWritten = 0; volatile ULONGLONG numTruncates = 0; for (int i = 0; i < NumAwaitables; i++) { ILogicalLog::SPtr log = logicalLogs[i]; CancellationToken token = cts->Token; awaitables[i] = ReadWriteCloseRaceWorker( *log, MaxLogBlockSize, logicalLogs, NumAwaitables, amountWritten, numTruncates, fileSize, i, token); } KNt::Sleep(15 * 1000); TestCommon::TestSession::WriteInfo(TraceComponent, "Closing logs"); Awaitable<NTSTATUS> closeAwaitables[NumCloseAwaitables]; for (int i = 0; i < NumCloseAwaitables; i++) { TestCommon::TestSession::WriteInfo(TraceComponent, "Async closing log {0}", i); closeAwaitables[i] = logicalLogs[i]->CloseAsync(CancellationToken::None); } for (int i = 0; i < NumCloseAwaitables; i++) { status = SyncAwait(closeAwaitables[i]); std::string msg("error closing task " + std::to_string(i)); VERIFY_STATUS_SUCCESS(msg.c_str(), status); } TestCommon::TestSession::WriteInfo(TraceComponent, "Finished async closing logs"); for (int i = NumCloseAwaitables; i < NumAwaitables; i++) { TestCommon::TestSession::WriteInfo(TraceComponent, "Sync closing log {0}", i); SyncAwait(logicalLogs[i]->CloseAsync(CancellationToken::None)); } TestCommon::TestSession::WriteInfo(TraceComponent, "Finished sync closing logs"); for (int i = 0; i < NumAwaitables; i++) { VERIFY_IS_FALSE(logicalLogs[i]->IsFunctional); VERIFY_IS_FALSE(dynamic_cast<LogicalLog*>(logicalLogs[i].RawPtr()) == nullptr ? FALSE : static_cast<LogicalLog*>(logicalLogs[i].RawPtr())->IsOpen()); logicalLogs[i] = nullptr; } KNt::Sleep(250); // todo: is this necessary? All tasks should have errored out by now or will on the next iteration. TestCommon::TestSession::WriteInfo(TraceComponent, "Canceling tokens"); cts->Cancel(); TestCommon::TestSession::WriteInfo(TraceComponent, "Wait for tasks"); for (int i = 0; i < NumAwaitables; i++) { SyncAwait(awaitables[i]); } TestCommon::TestSession::WriteInfo(TraceComponent, "Tasks completed"); status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } VOID LogTestBase::UPassthroughErrorsTest(__in KtlLoggerMode) { NTSTATUS status; ILogManagerHandle::SPtr logManager; status = CreateAndOpenLogManager(logManager); VERIFY_STATUS_SUCCESS("CreateAndOpenLogManager", status); LogManager* logManagerService = nullptr; { LogManagerHandle* logManagerServiceHandle = dynamic_cast<LogManagerHandle*>(logManager.RawPtr()); if (logManagerServiceHandle != nullptr) { logManagerService = logManagerServiceHandle->owner_.RawPtr(); } } VerifyState( logManagerService, 1, 0, TRUE); KString::SPtr physicalLogName; GenerateUniqueFilename(physicalLogName); KGuid physicalLogId; physicalLogId.CreateNew(); // Don't care if this fails SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); IPhysicalLogHandle::SPtr physicalLog; status = CreatePhysicalLog(*logManager, physicalLogId, *physicalLogName, physicalLog); VERIFY_STATUS_SUCCESS("CreatePhysicalLog", status); VerifyState(logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 0, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE); KGuid logicalLogId; logicalLogId.CreateNew(); KString::SPtr logicalLogFileName; GenerateUniqueFilename(logicalLogFileName); ILogicalLog::SPtr logicalLog; status = CreateLogicalLog(*physicalLog, logicalLogId, *logicalLogFileName, logicalLog); VERIFY_STATUS_SUCCESS("CreateLogicalLog", status); VerifyState( logManagerService, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()) != nullptr ? &(static_cast<PhysicalLogHandle&>(*physicalLog).Owner) : nullptr, 1, 1, TRUE, dynamic_cast<PhysicalLogHandle*>(physicalLog.RawPtr()), TRUE, nullptr, -1, -1, FALSE, nullptr, FALSE, FALSE, dynamic_cast<LogicalLog*>(logicalLog.RawPtr()), TRUE); VERIFY_IS_TRUE(logicalLog->IsFunctional); VERIFY_ARE_EQUAL(0, logicalLog->Length); VERIFY_ARE_EQUAL(0, logicalLog->ReadPosition); VERIFY_ARE_EQUAL(0, logicalLog->WritePosition); VERIFY_ARE_EQUAL(-1, logicalLog->HeadTruncationPosition); // Delete the logical log, then close it status = SyncAwait(physicalLog->DeleteLogicalLogOnlyAsync(logicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("IPhysicalLogHandle::DeleteLogicalLogOnlyAsync", status); status = SyncAwait(logicalLog->CloseAsync()); VERIFY_STATUS_SUCCESS("LogicalLog::CloseAsync", status); // cleanup status = SyncAwait(physicalLog->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("PhysicalLog::CloseAsync", status); physicalLog = nullptr; status = SyncAwait(logManager->DeletePhysicalLogAsync(*physicalLogName, physicalLogId, CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::DeletePhysicalLogAsync", status); status = SyncAwait(logManager->CloseAsync(CancellationToken::None)); VERIFY_STATUS_SUCCESS("LogManager::CloseAsync", status); logManager = nullptr; } }
40.758786
224
0.600231
vishnuk007
db80378e00d14e968e514b1bc2ca346c5b166404
947
cpp
C++
game/server/entities/items/CItemLongJump.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/server/entities/items/CItemLongJump.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/server/entities/items/CItemLongJump.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
#include "extdll.h" #include "util.h" #include "cbase.h" #include "CBasePlayer.h" #include "WeaponsConst.h" #include "CItem.h" #include "CItemLongJump.h" LINK_ENTITY_TO_CLASS( item_longjump, CItemLongJump ); void CItemLongJump::Spawn( void ) { Precache(); SetModel( "models/w_longjump.mdl" ); CItem::Spawn(); } void CItemLongJump::Precache( void ) { PRECACHE_MODEL( "models/w_longjump.mdl" ); } bool CItemLongJump::MyTouch( CBasePlayer *pPlayer ) { if( pPlayer->m_fLongJump ) { return false; } if( ( pPlayer->GetWeapons().Any( 1 << WEAPON_SUIT ) ) ) { pPlayer->m_fLongJump = true;// player now has longjump module g_engfuncs.pfnSetPhysicsKeyValue( pPlayer->edict(), "slj", "1" ); MESSAGE_BEGIN( MSG_ONE, gmsgItemPickup, NULL, pPlayer ); WRITE_STRING( GetClassname() ); MESSAGE_END(); EMIT_SOUND_SUIT( pPlayer, "!HEV_A1" ); // Play the longjump sound UNDONE: Kelly? correct sound? return true; } return false; }
20.586957
97
0.702218
xalalau
db82b2491f7f739a5ba5c3a15bd4ee5c8ce123d0
512
cpp
C++
ymp/src/ymp/core/GameWindow.cpp
haukkagu/ymp
2094ae4426931dc44b1a0d43253fa2581253dfd4
[ "MIT" ]
1
2021-02-26T17:34:51.000Z
2021-02-26T17:34:51.000Z
ymp/src/ymp/core/GameWindow.cpp
haukkagu/ymp
2094ae4426931dc44b1a0d43253fa2581253dfd4
[ "MIT" ]
null
null
null
ymp/src/ymp/core/GameWindow.cpp
haukkagu/ymp
2094ae4426931dc44b1a0d43253fa2581253dfd4
[ "MIT" ]
null
null
null
#include "ymp/core/GameWindow.h" #include "ymp/opengl.h" namespace ymp { GameWindow::GameWindow(const char* title, unsigned int width, unsigned int height) { m_Window = nullptr; m_Title = title; m_Width = width; m_Height = height; } GameWindow::~GameWindow() { glfwDestroyWindow(m_Window); } void GameWindow::init() { m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, nullptr, nullptr); glfwMakeContextCurrent(m_Window); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } }
21.333333
85
0.728516
haukkagu
db82d9ac10545f66127736d82c74c56ba48b8706
26,905
cpp
C++
src/StepReadFromRedis.cpp
Bwar/NebulaMydis
103c736c487671649e50e75e9eaace5df95f1597
[ "Apache-2.0" ]
1
2019-06-17T12:16:05.000Z
2019-06-17T12:16:05.000Z
src/StepReadFromRedis.cpp
Bwar/NebulaMydis
103c736c487671649e50e75e9eaace5df95f1597
[ "Apache-2.0" ]
null
null
null
src/StepReadFromRedis.cpp
Bwar/NebulaMydis
103c736c487671649e50e75e9eaace5df95f1597
[ "Apache-2.0" ]
1
2019-12-03T01:19:58.000Z
2019-12-03T01:19:58.000Z
/******************************************************************************* * Project: NebulaMydis * @file StepReadFromRedis.cpp * @brief * @author Bwar * @date: 2018年3月1日 * @note * Modify history: ******************************************************************************/ #include <google/protobuf/io/zero_copy_stream_impl.h> #include "StepReadFromRedis.hpp" namespace mydis { StepReadFromRedis::StepReadFromRedis( const neb::Mydis::RedisOperate& oRedisOperate, SessionRedisNode* pNodeSession, bool bIsDataSet, const neb::CJsonObject* pTableFields, const std::string& strKeyField, std::shared_ptr<neb::Step> pNextStep) : RedisStorageStep(pNextStep), m_oRedisOperate(oRedisOperate), m_bIsDataSet(bIsDataSet), m_oTableFields(pTableFields), m_strKeyField(strKeyField), m_iReadNum(0), m_iTableFieldNum(0), m_pNodeSession(pNodeSession), m_pNextStep(pNextStep) { m_iTableFieldNum = m_oTableFields.GetArraySize(); } StepReadFromRedis::~StepReadFromRedis() { } neb::E_CMD_STATUS StepReadFromRedis::Emit(int iErrno, const std::string& strErrMsg, void* data) { LOG4_TRACE("%s()", __FUNCTION__); if (!m_pNodeSession) { return(neb::CMD_STATUS_FAULT); } if (0 == m_iReadNum) { bool bGetRedisNode; if (m_oRedisOperate.hash_key().size() > 0) { bGetRedisNode = m_pNodeSession->GetRedisNode(m_oRedisOperate.hash_key(), m_strMasterNode, m_strSlaveNode); } else { bGetRedisNode = m_pNodeSession->GetRedisNode(m_oRedisOperate.key_name(), m_strMasterNode, m_strSlaveNode); } if (!bGetRedisNode) { Response(neb::ERR_REDIS_NODE_NOT_FOUND, "redis node not found!"); return(neb::CMD_STATUS_FAULT); } } SetCmd(m_oRedisOperate.redis_cmd_read()); Append(m_oRedisOperate.key_name()); for (int i = 0; i < m_oRedisOperate.fields_size(); ++i) { if (m_oRedisOperate.fields(i).col_name().size() > 0) { Append(m_oRedisOperate.fields(i).col_name()); } if (m_oRedisOperate.fields(i).col_value().size() > 0) { Append(m_oRedisOperate.fields(i).col_value()); } } if (0 == m_iReadNum) // 从备Redis节点读取 { if (SendTo(m_strSlaveNode)) { ++m_iReadNum; return(neb::CMD_STATUS_RUNNING); } } else // 从主Redis节点读取(说明第一次从备Redis节点读取失败) { if (SendTo(m_strMasterNode)) { ++m_iReadNum; return(neb::CMD_STATUS_RUNNING); } } return(neb::CMD_STATUS_FAULT); } neb::E_CMD_STATUS StepReadFromRedis::Callback(const redisAsyncContext *c, int status, redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; if (REDIS_OK != status) { if (0 == m_iReadNum) { LOG4_WARNING("redis %s cmd status %d!", m_strSlaveNode.c_str(), status); return(Emit(neb::ERR_OK)); } snprintf(szErrMsg, sizeof(szErrMsg), "redis %s cmd status %d!", m_strMasterNode.c_str(), status); Response(neb::ERR_REDIS_CMD, szErrMsg); return(neb::CMD_STATUS_FAULT); } if (NULL == pReply) { if (0 == m_iReadNum) { LOG4_WARNING("redis %s error %d: %s!", m_strSlaveNode.c_str(), c->err, c->errstr); return(Emit(neb::ERR_OK)); } snprintf(szErrMsg, sizeof(szErrMsg), "redis %s error %d: %s!", m_strMasterNode.c_str(), c->err, c->errstr); Response(neb::ERR_REDIS_CMD, szErrMsg); return(neb::CMD_STATUS_FAULT); } LOG4_TRACE("redis reply->type = %d", pReply->type); if (REDIS_REPLY_ERROR == pReply->type) { snprintf(szErrMsg, sizeof(szErrMsg), "redis %s error %d: %s!", m_strSlaveNode.c_str(), pReply->type, pReply->str); Response(neb::ERR_REDIS_CMD, szErrMsg); return(neb::CMD_STATUS_FAULT); } if (REDIS_REPLY_NIL == pReply->type) { if (m_pNextStep) // redis中数据为空,有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(neb::CMD_STATUS_FAULT); } return(neb::CMD_STATUS_COMPLETED); } else // 只读redis,redis的结果又为空 { Response(neb::ERR_OK, "OK"); // 操作是正常的,但结果集为空 return(neb::CMD_STATUS_COMPLETED); } } // 从redis中读到数据 neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); if (REDIS_REPLY_STRING == pReply->type) { if (m_bIsDataSet) { neb::Record* pRecord = oRsp.add_record_data(); if (!pRecord->ParseFromArray(pReply->str, pReply->len)) // 解析出错表明redis中数据有问题,需从db中读并覆盖redis中数据 { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(neb::CMD_STATUS_FAULT); } return(neb::CMD_STATUS_COMPLETED); } Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "pRecord->ParseFromArray(pReply->element[i]->str, pReply->element[i]->len) failed!"); return(neb::CMD_STATUS_FAULT); } if (m_iTableFieldNum > 0 && m_iTableFieldNum != pRecord->field_info_size()) // 字段数量不匹配表明redis中数据有问题,需从db中读并覆盖redis中数据 { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(neb::CMD_STATUS_FAULT); } return(neb::CMD_STATUS_COMPLETED); } Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "the field of redis dataset record not match the db table field num!"); return(neb::CMD_STATUS_FAULT); } } else { neb::Record* pRecord = oRsp.add_record_data(); neb::Field* pField = pRecord->add_field_info(); pField->set_col_value(pReply->str, pReply->len); } } else if(REDIS_REPLY_INTEGER == pReply->type) { neb::Record* pRecord = oRsp.add_record_data(); neb::Field* pField = pRecord->add_field_info(); char szValue[32] = {0}; snprintf(szValue, 32, "%lld", pReply->integer); pField->set_col_value(szValue); } else if(REDIS_REPLY_ARRAY == pReply->type) { LOG4_TRACE("pReply->type = %d, pReply->elements = %u", pReply->type, pReply->elements); if (0 == pReply->elements) { if (m_pNextStep) // redis中数据为空,有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(neb::CMD_STATUS_FAULT); } return(neb::CMD_STATUS_COMPLETED); } else // 只读redis,redis的结果又为空 { Response(neb::ERR_OK, "OK"); // 操作是正常的,但结果集为空 return(neb::CMD_STATUS_COMPLETED); } } if (REDIS_T_HASH == m_oRedisOperate.redis_structure()) { if (ReadReplyHash(pReply)) { return(neb::CMD_STATUS_COMPLETED); } return(neb::CMD_STATUS_FAULT); } else { if (ReadReplyArray(pReply)) { return(neb::CMD_STATUS_COMPLETED); } return(neb::CMD_STATUS_FAULT); } } else { snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d: %s!", pReply->type, pReply->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(neb::CMD_STATUS_FAULT); } if (Response(oRsp)) { return(neb::CMD_STATUS_COMPLETED); } return(neb::CMD_STATUS_FAULT); } bool StepReadFromRedis::ReadReplyArray(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); if (m_bIsDataSet) { if (ReadReplyArrayWithDataSet(pReply)) { return(true); } return(false); } else { if (ReadReplyArrayWithoutDataSet(pReply)) { return(true); } return(false); } } bool StepReadFromRedis::ReadReplyArrayWithDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); oRsp.set_total_count(pReply->elements); oRsp.mutable_record_data()->Reserve(pReply->elements); int iDataLen = oRsp.ByteSize(); for(size_t i = 0; i < pReply->elements; ++i) { if (pReply->element[i]->len > 1000000) // pb 最大限制 { Response(neb::ERR_RESULTSET_EXCEED, "hgetall result set exceed 1 MB!"); return(false); } if (iDataLen + pReply->element[i]->len > 1000000) // pb 最大限制 { oRsp.set_current_count(i + 1); if (Response(oRsp)) { oRsp.clear_record_data(); iDataLen = 0; } else { return(false); } } neb::Record* pRecord = oRsp.add_record_data(); //.mutable_record_data(i); if(REDIS_REPLY_STRING == pReply->element[i]->type) { // google::protobuf::io::ArrayInputStream oArrayInput(pReply->element[i]->str, pReply->element[i]->len); // pRecord->ParseFromZeroCopyStream(&oArrayInput); if (!pRecord->ParseFromArray(pReply->element[i]->str, pReply->element[i]->len)) // 解析出错表明redis中数据有问题,需从db中读并覆盖redis中数据 { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "pRecord->ParseFromArray(pReply->element[i]->str, pReply->element[i]->len) failed!"); return(false); } if (m_iTableFieldNum > 0 && m_iTableFieldNum != pRecord->field_info_size()) // 字段数量不匹配表明redis中数据有问题,需从db中读并覆盖redis中数据 { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "the field of redis dataset record not match the db table field num!"); return(false); } iDataLen += pReply->element[i]->len; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", i, pReply->element[i]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, i, pReply->element[i]->type, pReply->element[i]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } } oRsp.set_current_count(pReply->elements); if (Response(oRsp)) { return(true); } return(false); } bool StepReadFromRedis::ReadReplyArrayWithoutDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; char szValue[32] = {0}; neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); oRsp.set_total_count(pReply->elements); int iDataLen = oRsp.ByteSize(); for(size_t i = 0; i < pReply->elements; ++i) { if (pReply->element[i]->len > 1000000) // pb 最大限制 { Response(neb::ERR_RESULTSET_EXCEED, "hgetall result set exceed 1 MB!"); return(false); } if (iDataLen + pReply->element[i]->len > 1000000) // pb 最大限制 { oRsp.set_current_count(i + 1); if (Response(oRsp)) { oRsp.clear_record_data(); iDataLen = 0; } else { return(false); } } neb::Record* pRecord = oRsp.add_record_data(); neb::Field* pField = pRecord->add_field_info(); if(REDIS_REPLY_STRING == pReply->element[i]->type) { pField->set_col_value(pReply->element[i]->str, pReply->element[i]->len); iDataLen += pReply->element[i]->len; } else if(REDIS_REPLY_INTEGER == pReply->element[i]->type) { snprintf(szValue, 32, "%lld",pReply->element[i]->integer); pField->set_col_value(szValue); iDataLen += 20; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } else { pField->set_col_value(""); LOG4_WARNING("pReply->element[%d]->type == REDIS_REPLY_NIL", i); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", i, pReply->element[i]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, i, pReply->element[i]->type, pReply->element[i]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } } oRsp.set_current_count(pReply->elements); if (Response(oRsp)) { return(true); } return(false); } bool StepReadFromRedis::ReadReplyHash(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); if ("HGETALL" == m_oRedisOperate.redis_cmd_read()) { if (m_bIsDataSet) { if (ReadReplyArrayForHgetallWithDataSet(pReply)) { return(true); } return(false); } else { if (ReadReplyArrayForHgetallWithoutDataSet(pReply)) { return(true); } return(false); } } else { if (m_bIsDataSet) { if (ReadReplyArrayForHashWithDataSet(pReply)) { return(true); } return(false); } else { if (ReadReplyArrayForHashWithoutDataSet(pReply)) { return(true); } return(false); } } } bool StepReadFromRedis::ReadReplyArrayForHashWithDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); return(ReadReplyArrayWithDataSet(pReply)); } bool StepReadFromRedis::ReadReplyArrayForHashWithoutDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; char szValue[32] = {0}; neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); oRsp.set_total_count(1); int iDataLen = oRsp.ByteSize(); neb::Record* pRecord = oRsp.add_record_data(); for(size_t i = 0; i < pReply->elements; ++i) { neb::Field* pField = pRecord->add_field_info(); if(REDIS_REPLY_STRING == pReply->element[i]->type) { pField->set_col_value(pReply->element[i]->str, pReply->element[i]->len); iDataLen += pReply->element[i]->len; } else if(REDIS_REPLY_INTEGER == pReply->element[i]->type) { snprintf(szValue, 32, "%lld",pReply->element[i]->integer); pField->set_col_value(szValue); iDataLen += 20; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } else { pField->set_col_value(""); LOG4_WARNING("pReply->element[%d]->type == REDIS_REPLY_NIL", i); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", i, pReply->element[i]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, i, pReply->element[i]->type, pReply->element[i]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } if (iDataLen > 1000000) // pb 最大限制 { Response(neb::ERR_RESULTSET_EXCEED, "hash result set exceed 1 MB!"); return(false); } } oRsp.set_current_count(1); if (Response(oRsp)) { return(true); } return(false); } bool StepReadFromRedis::ReadReplyArrayForHgetallWithDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); int iDataLen = oRsp.ByteSize(); if ((pReply->elements % 2) != 0) { snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d elements num %lu not a even number for hgetall!", pReply->type, pReply->elements); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(neb::CMD_STATUS_FAULT); } oRsp.set_total_count(pReply->elements); neb::Record* pHashFieldNameRecord = oRsp.add_record_data(); neb::Record* pHashFieldValueRecord = oRsp.add_record_data(); for(size_t i = 0, j = 1; i < pReply->elements; i += 2, j = i + 1) { if (pReply->element[i]->len > 1000000) // pb 最大限制 { Response(neb::ERR_RESULTSET_EXCEED, "hgetall result set exceed 1 MB!"); return(false); } if (iDataLen + pReply->element[i]->len > 1000000) // pb 最大限制 { oRsp.set_current_count(i + 1); if (Response(oRsp)) { oRsp.clear_record_data(); iDataLen = 0; } else { return(false); } } neb::Field* pField = pHashFieldNameRecord->add_field_info(); if(REDIS_REPLY_STRING == pReply->element[i]->type) { pField->set_col_name(pReply->element[i]->str, pReply->element[i]->len); pField->set_col_value(pReply->element[i]->str, pReply->element[i]->len); iDataLen += pReply->element[i]->len * 2; } else { LOG4_ERROR("pReply->element[%d]->type = %d", i, pReply->element[i]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, i, pReply->element[i]->type, pReply->element[i]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } if(REDIS_REPLY_STRING == pReply->element[j]->type) { pHashFieldValueRecord->ParseFromArray(pReply->element[j]->str, pReply->element[j]->len); iDataLen += pReply->element[j]->len; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", j, pReply->element[j]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, j, pReply->element[j]->type, pReply->element[j]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } } oRsp.set_current_count(pReply->elements); if (Response(oRsp)) { return(true); } return(false); } bool StepReadFromRedis::ReadReplyArrayForHgetallWithoutDataSet(redisReply* pReply) { LOG4_TRACE("%s()", __FUNCTION__); char szErrMsg[256] = {0}; char szValue[32] = {0}; neb::Result oRsp; oRsp.set_err_no(neb::ERR_OK); oRsp.set_err_msg("OK"); oRsp.set_from(neb::Result::FROM_REDIS); int iDataLen = oRsp.ByteSize(); if ((pReply->elements % 2) != 0) { snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d elements num %lu not a even number for hgetall!", pReply->type, pReply->elements); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(neb::CMD_STATUS_FAULT); } oRsp.set_total_count(1); neb::Record* pRecord = oRsp.add_record_data(); for(size_t i = 0, j = 1; i < pReply->elements; i += 2, j = i + 1) { neb::Field* pField = pRecord->add_field_info(); if(REDIS_REPLY_STRING == pReply->element[i]->type) { pField->set_col_name(pReply->element[i]->str, pReply->element[i]->len); iDataLen += pReply->element[i]->len; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", i, pReply->element[i]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, i, pReply->element[i]->type, pReply->element[i]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } if(REDIS_REPLY_STRING == pReply->element[j]->type) { pField->set_col_value(pReply->element[j]->str, pReply->element[j]->len); iDataLen += pReply->element[j]->len; } else if(REDIS_REPLY_INTEGER == pReply->element[j]->type) { snprintf(szValue, 32, "%lld",pReply->element[j]->integer); pField->set_col_value(szValue); iDataLen += 20; } else if(REDIS_REPLY_NIL == pReply->element[i]->type) { if (m_pNextStep) // redis中hash的某个Field数据为空(说明数据不完整),有下一步(通常是再尝试从DB中读)则执行下一步 { if (!m_pNextStep->Emit()) { Response(neb::ERR_REDIS_NIL_AND_DB_FAILED, "redis result set is nil and send to dbagent failed!"); return(false); } return(true); } else { pField->set_col_value(""); LOG4_WARNING("pReply->element[%d]->type == REDIS_REPLY_NIL", i); } } else { LOG4_ERROR("pReply->element[%d]->type = %d", j, pReply->element[j]->type); snprintf(szErrMsg, sizeof(szErrMsg), "unexprected redis reply type %d and element[%lu] type %d: %s!", pReply->type, j, pReply->element[j]->type, pReply->element[j]->str); Response(neb::ERR_UNEXPECTED_REDIS_REPLY, szErrMsg); return(false); } if (iDataLen > 1000000) // pb 最大限制 { Response(neb::ERR_RESULTSET_EXCEED, "hgetall result set exceed 1 MB!"); return(false); } } oRsp.set_current_count(1); if (Response(oRsp)) { return(true); } return(false); } } /* namespace mydis */
35.032552
132
0.525293
Bwar
db82df35dc24052ee19476319b059c0a8455b1b6
1,712
cpp
C++
src/tools/LibLoading.cpp
CapRat/APAL
a08f4bc6ee6299e8e370ef99750262ad23c87d58
[ "MIT" ]
2
2020-09-21T12:30:05.000Z
2020-10-14T19:43:51.000Z
src/tools/LibLoading.cpp
CapRat/APAL
a08f4bc6ee6299e8e370ef99750262ad23c87d58
[ "MIT" ]
null
null
null
src/tools/LibLoading.cpp
CapRat/APAL
a08f4bc6ee6299e8e370ef99750262ad23c87d58
[ "MIT" ]
null
null
null
#include "tools/LibLoading.hpp" namespace APAL { std::string GetErrorStr() { const char* errStr = GetError(); return errStr == nullptr ? std::string() : errStr; } } #ifdef _WIN32 #include <windows.h> namespace APAL { char* lastError = nullptr; char* lastErrorReturnCopy = nullptr; library_t LoadLib(const char* libName) { HMODULE lastLib = LoadLibraryA(libName); if (lastLib == NULL) { static const char NO_LIB_LOAD_MSG[] = "Could not load library: "; free((void*)lastError); lastError = (char*)malloc(sizeof(NO_LIB_LOAD_MSG) + strlen(libName)); strcpy(lastError, NO_LIB_LOAD_MSG); strcat(lastError, libName); } return lastLib; } void* LoadFuncRaw(library_t lib, const char* fncName) { FARPROC lastFunc = GetProcAddress(static_cast<HMODULE>(lib), fncName); if (lastFunc == NULL) { static const char NO_FNC_LOAD_MSG[] = "Could not load function: "; free((void*)lastError); lastError = (char*)malloc(sizeof(NO_FNC_LOAD_MSG) + strlen(fncName)); strcpy(lastError, NO_FNC_LOAD_MSG); strcat(lastError, fncName); } return reinterpret_cast<void*>(lastFunc); } const char* GetError() { free(lastErrorReturnCopy); lastErrorReturnCopy = lastError; lastError = NULL; return lastErrorReturnCopy; } void UnloadLib(library_t lib) { free(lastError); free(lastErrorReturnCopy); FreeLibrary(static_cast<HMODULE>(lib)); } } #else #include <dlfcn.h> namespace APAL { library_t LoadLib(const char* libName) { return dlopen(libName, RTLD_LAZY); } void* LoadFuncRaw(library_t lib, const char* fncName) { return dlsym(lib, fncName); } const char* GetError() { return dlerror(); } void UnloadLib(library_t lib) { dlclose(lib); } } #endif //!_WIN32
19.235955
73
0.709696
CapRat
db842967130eac807ff42a396771682025765efe
30,630
cpp
C++
_src_/Core/BMD.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
16
2021-07-15T04:00:38.000Z
2022-02-27T02:37:23.000Z
_src_/Core/BMD.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
6
2021-08-05T05:01:35.000Z
2021-10-22T02:01:33.000Z
_src_/Core/BMD.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
16
2021-07-18T02:40:12.000Z
2022-02-09T05:25:07.000Z
#include "BMD.h" //#define _DEBUG_BMD_ #ifdef _DEBUG_BMD_ #define DEBUG_BMD 1 #define PRINT_DEBUG_BMD(msg) std::cout << msg << std::endl #else #define DEBUG_BMD 0 #define PRINT_DEBUG_BMD(msg) #endif vec3_t DUMMY_VEC3{ 0.0f, 0.0f,0.0f }; BoneMatrix_t DUMMY_BONE_MATRIX{ &DUMMY_VEC3 , &DUMMY_VEC3 }; //======================================================================================== BOOL BMD::Unpack(const char* szSrc, const char* szDest) { if (!szSrc) return FALSE; auto CheckBmd = [](const char* szInputPath)->BOOL { std::ifstream is(szInputPath, std::ios::in | std::ios::binary); if (!is.is_open()) return FALSE; char BMD[3]{}; for (int i = 0; i < 3 && !is.eof(); i++) is >> BMD[i]; is.close(); return (BMD[0] == 'B' && BMD[1] == 'M' && BMD[2] == 'D'); }; if(!CheckBmd(szSrc)) return FALSE; PRINT_DEBUG("Unpacking " << szSrc); if (!szDest) { std::string sName = fs::path(szSrc).filename().replace_extension("").string(); szDest = fs::path(szSrc).parent_path().append(sName + "_model").append(sName + ".smd").string().c_str(); } return LoadBmd(szSrc) && SaveSmd(szDest); } BOOL BMD::Pack(const char* szSrc, const char* szDest) { if (!szSrc) return FALSE; PRINT_DEBUG("Packing " << szSrc); if (!szDest) { std::string sName = fs::path(szSrc).filename().replace_extension(".bmd").string(); szDest = fs::path(szSrc).parent_path().parent_path().append(sName).string().c_str(); } return LoadSmd(szSrc) && SaveBmd(szDest); } //======================================================================================== BOOL BMD::LoadLockPostionData(const char* fname) { LockPositionData.clear(); LockPositionData_FileName = fname; if (!fs::exists(fname)) { std::ofstream os(fname); if (!os.is_open()) return FALSE; os << "//action (tab) bmd_name" << std::endl; os.close(); return TRUE; } std::ifstream is(fname); if (!is.is_open()) return FALSE; std::string line; while (std::getline(is, line)) { if (line.length() >= 2 && line[0] == '/' && line[1] == '/') continue; short action; char buf[256]; sscanf_s(line.c_str(), "%hd\t%s", &action, buf, 256); std::string bmd_name(buf); std::transform(bmd_name.begin(), bmd_name.end(), bmd_name.begin(), ::tolower); if (action > 0 && !bmd_name.empty()) { LockPositionData.insert(std::make_pair(bmd_name, action)); //PRINT_DEBUG(bmd_name << " " << action); } } is.close(); return TRUE; } BOOL BMD::GetLockPosition(std::string& name, short action) { auto range = LockPositionData.equal_range(name); for (auto& it = range.first; it != range.second; it++) { if (it->second == action) return TRUE; } return FALSE; } BOOL BMD::SetLockPosition(std::string& name, short action) { auto range = LockPositionData.equal_range(name); for (auto& it = range.first; it != range.second; it++) { if (it->second == action) return FALSE; } std::ofstream os(LockPositionData_FileName, std::ofstream::app); if (!os.is_open()) return FALSE; LockPositionData.insert(std::make_pair(name, action)); os << action << "\t" << name << std::endl; os.close(); return TRUE; } //======================================================================================== BOOL BMD::Release() { Temp_Bone_Pos.clear(); Temp_Bone_Rot.clear(); Temp_Lock_Pos.clear(); Temp_Vertex.clear(); Temp_Normal.clear(); Temp_TexCoord.clear(); Temp_Triangle.clear(); m_data.clear(); _buf.clear(); return TRUE; } BOOL BMD::FixUpBones() { for (int i = 0; i < m_data.NumBones; i++) { Bone_t* b = &m_data.Bones[i]; vec3_t Angle; vec3_t Pos; BoneMatrix_t* bm = &b->BoneMatrixes[0]; Angle[0] = bm->Rotation[0][0] * (180.0f / Q_PI); Angle[1] = bm->Rotation[0][1] * (180.0f / Q_PI); Angle[2] = bm->Rotation[0][2] * (180.0f / Q_PI); Pos[0] = bm->Position[0][0]; Pos[1] = bm->Position[0][1]; Pos[2] = bm->Position[0][2]; // calc true world coord. if (b->Parent >= 0 && b->Parent < m_data.NumBones) { BoneMatrix_t* bm = &b->BoneMatrixes[0]; float m[3][4]; vec3_t p; AngleMatrix(Angle, m); R_ConcatTransforms(BoneFixup[b->Parent].m, m, BoneFixup[i].m); AngleIMatrix(Angle, m); R_ConcatTransforms(m, BoneFixup[b->Parent].im, BoneFixup[i].im); VectorTransform(Pos, BoneFixup[b->Parent].m, p); VectorAdd(p, BoneFixup[b->Parent].WorldOrg, BoneFixup[i].WorldOrg); } else { AngleMatrix(Angle, BoneFixup[i].m); AngleIMatrix(Angle, BoneFixup[i].im); VectorCopy(Pos, BoneFixup[i].WorldOrg); } } return TRUE; } //======================================================================================== BOOL BMD::Encrypt() { if (_buf.empty()) return FALSE; BYTE ver = m_data.Version; if (ver == 0xC) { size_t size = _buf.size(); MapFileEncrypt(&_buf[0], size); _buf.insert(_buf.begin(), 8, 0); *(size_t*)&_buf[4] = size; } else if (ver == 0xE) { size_t size = _buf.size(); ModulusEncrypt(_buf); _buf.insert(_buf.begin(), 8, 0); *(size_t*)&_buf[4] = size; } else if (ver = 0xA) { _buf.insert(_buf.begin(), 4, 0); } else { PRINT_DEBUG("[ERROR] Unknown BMD version : " << ((int)ver)); return FALSE; } _buf[0] = 'B'; _buf[1] = 'M'; _buf[2] = 'D'; _buf[3] = ver; return TRUE; } BOOL BMD::Decrypt() { if (_buf.size() < 8) return FALSE; if (_buf[0] != 'B' || _buf[1] != 'M' || _buf[2] != 'D') return FALSE; BYTE ver = _buf[3]; if (ver == 0xC) { size_t size = *(size_t*)&_buf[4]; _buf.erase(_buf.begin(), _buf.begin() + 8); if (_buf.size() < size) return FALSE; ////(_buf.size() == size) MapFileDecrypt(&_buf[0], size); } else if (ver == 0xE) { size_t size = *(size_t*)&_buf[4]; _buf.erase(_buf.begin(), _buf.begin() + 8); if (_buf.size() < size) return FALSE; //(_buf.size() == size) ModulusDecrypt(_buf); } else if (ver == 0xA) { _buf.erase(_buf.begin(), _buf.begin() + 4); } else { PRINT_DEBUG("[ERROR] Unknown BMD version : " << ((int)ver)); return FALSE; } m_data.Version = ver; return TRUE; } //======================================================================================== BOOL BMD::LoadBmd(const char* szSrc) { Release(); m_data.Name = fs::path(szSrc).filename().replace_extension("").string(); return FileOpen(szSrc) && Decrypt() && ReadBmd(); } BOOL BMD::ReadBmd() { if (_buf.size() < 38) return FALSE; size_t pos = 0; //m_data.Name = std::string((const char*)&_buf[pos], min(32, strlen((const char*)&_buf[pos]))); pos += 32; pos += 32; m_data.NumMeshs = *(short*)&_buf[pos]; pos += 2; if (m_data.NumMeshs < 0 || m_data.NumMeshs > MAX_MESH) { PRINT_DEBUG("[ERROR] m_data.NumMeshs < 0 || m_data.NumMeshs > MAX_MESH"); return FALSE; } m_data.NumBones = *(short*)&_buf[pos]; pos += 2; if (m_data.NumBones < 0 || m_data.NumBones > MAX_BONES) { PRINT_DEBUG("[ERROR] m_data.NumBones < 0 || m_data.NumBones > MAX_BONES"); return FALSE; } m_data.NumActions = *(short*)&_buf[pos]; pos += 2; if (m_data.NumActions < 1) { PRINT_DEBUG("[ERROR] m_data.NumActions < 1"); return FALSE; } m_data.Meshs.resize(m_data.NumMeshs); m_data.Bones.resize(m_data.NumBones); m_data.Actions.resize(m_data.NumActions); m_data.Textures.resize(m_data.NumMeshs); //m_data.IndexTexture.resize(m_data.NumMeshs); if (DEBUG_BMD) { PRINT_DEBUG_BMD("[BMD] : " << m_data.Name); PRINT_DEBUG_BMD("\tNumMeshs : " << m_data.NumMeshs); PRINT_DEBUG_BMD("\tNumBones : " << m_data.NumBones); PRINT_DEBUG_BMD("\tNumActions : " << m_data.NumActions); PRINT_DEBUG_BMD("========================================"); } for (int i = 0; i < m_data.NumMeshs; i++) { Mesh_t* m = &m_data.Meshs[i]; m->NumVertices = *(short*)&_buf[pos]; pos += 2; m->NumNormals = *(short*)&_buf[pos]; pos += 2; m->NumTexCoords = *(short*)&_buf[pos]; pos += 2; m->NumTriangles = *(short*)&_buf[pos]; pos += 2; m->Texture = *(short*)&_buf[pos]; pos += 2; m->NoneBlendMesh = false; if (m->NumVertices < 0) m->NumVertices = 0; if (m->NumNormals < 0) m->NumNormals = 0; if (m->NumTexCoords < 0) m->NumTexCoords = 0; if (m->NumTriangles < 0) m->NumTriangles = 0; //don't need to copy, pointing to data in _buf instead m->Vertices = (Vertex_t*)&_buf[pos]; pos += (m->NumVertices * sizeof(Vertex_t)); m->Normals = (Normal_t*)&_buf[pos]; pos += (m->NumNormals * sizeof(Normal_t)); m->TexCoords = (TexCoord_t*)&_buf[pos]; pos += (m->NumTexCoords * sizeof(TexCoord_t)); m->Triangles = (Triangle_t*)&_buf[pos]; pos += (m->NumTriangles * sizeof(Triangle_t)); //TextureScriptParsing skip if (_buf.size() < pos) { PRINT_DEBUG("[ERROR] Corrupted Bmd File"); return FALSE; } m_data.Textures[i].FileName = std::string((const char*)&_buf[pos], min(32, strlen((const char*)&_buf[pos]))); pos += 32; if (DEBUG_BMD) { PRINT_DEBUG_BMD("[Mesh] : " << i); PRINT_DEBUG_BMD("\tNumVertices: " << m->NumVertices); PRINT_DEBUG_BMD("\tNumNormals: " << m->NumNormals); PRINT_DEBUG_BMD("\tNumTexCoords: " << m->NumTexCoords); PRINT_DEBUG_BMD("\tNumTriangles: " << m->NumTriangles); PRINT_DEBUG_BMD("\tTexture: " << m->Texture); PRINT_DEBUG_BMD("\tTexture Name: " << m_data.Textures[i].FileName); PRINT_DEBUG_BMD("========================================"); PRINT_DEBUG_BMD("[Vertices] Mesh : " << i); PRINT_DEBUG_BMD("\tNumVertices: " << m->NumVertices); for (int ii = 0; ii < m->NumVertices; ii++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << m->Vertices[ii].Node << "\t" << m->Vertices[ii].Position[0] << "\t" << m->Vertices[ii].Position[1] << "\t" << m->Vertices[ii].Position[2]); } PRINT_DEBUG_BMD("________________________________________"); PRINT_DEBUG_BMD("[Normals] Mesh : " << i); PRINT_DEBUG_BMD("\tNumNormals: " << m->NumNormals); for (int ii = 0; ii < m->NumNormals; ii++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << m->Normals[ii].Node << "\t" << m->Normals[ii].BindVertex << "\t" << m->Normals[ii].Normal[0] << "\t" << m->Normals[ii].Normal[1] << "\t" << m->Normals[ii].Normal[2]); } PRINT_DEBUG_BMD("________________________________________"); PRINT_DEBUG_BMD("[TexCoords] Mesh : " << i); PRINT_DEBUG_BMD("\tNumTexCoords: " << m->NumTexCoords); for (int ii = 0; ii < m->NumTexCoords; ii++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << m->TexCoords[ii].TexCoordU << "\t" << m->TexCoords[ii].TexCoordV); } PRINT_DEBUG_BMD("________________________________________"); PRINT_DEBUG_BMD("[Triangles] Mesh : " << i); PRINT_DEBUG_BMD("\tNumTriangles: " << m->NumTriangles); for (int ii = 0; ii < m->NumTriangles; ii++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << m->Triangles[ii].VertexIndex[0] << "\t" << m->Triangles[ii].VertexIndex[1] << "\t" << m->Triangles[ii].VertexIndex[2] << "\t|" << "\t" << m->Triangles[ii].NormalIndex[0] << "\t" << m->Triangles[ii].NormalIndex[1] << "\t" << m->Triangles[ii].NormalIndex[2] << "\t|" << "\t" << m->Triangles[ii].TexCoordIndex[0] << "\t" << m->Triangles[ii].TexCoordIndex[1] << "\t" << m->Triangles[ii].TexCoordIndex[2] << std::endl); } PRINT_DEBUG_BMD("========================================"); } } for (int i = 0; i < m_data.NumActions; i++) { Action_t* a = &m_data.Actions[i]; //a->Loop = false; a->NumAnimationKeys = *(short*)&_buf[pos]; pos += 2; if (a->NumAnimationKeys < 0) a->NumAnimationKeys = 0; a->LockPositions = *(bool*)&_buf[pos]; pos += 1; if (a->LockPositions) { //don't need to copy, pointing to data in _buf instead a->Positions = (vec3_t*)&_buf[pos]; pos += (a->NumAnimationKeys * sizeof(vec3_t)); BMD::SetLockPosition(m_data.Name + ".bmd", i); } else { a->Positions = NULL; } if (_buf.size() < pos) { PRINT_DEBUG("[ERROR] Corrupted Bmd File"); return FALSE; } if (m_data.Actions[0].NumAnimationKeys <= 0) { PRINT_DEBUG("[ERROR] m_data.Actions[0].NumAnimationKeys <= 0"); return FALSE; } if (DEBUG_BMD) { PRINT_DEBUG_BMD("[Actions] : " << i); PRINT_DEBUG_BMD("\tNumAnimationKeys : " << a->NumAnimationKeys); PRINT_DEBUG_BMD("\tLockPositions : " << a->LockPositions); if (a->LockPositions) { for (int ii = 0; ii < a->NumAnimationKeys; ii++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << a->Positions[ii][0] << "\t" << a->Positions[ii][1] << "\t" << a->Positions[ii][2]); } } PRINT_DEBUG_BMD("========================================"); } } if (_buf.size() < pos) { PRINT_DEBUG("[ERROR] Corrupted Bmd File"); return FALSE; } for (int i = 0; i < m_data.NumBones; i++) { Bone_t* b = &m_data.Bones[i]; b->Dummy = *(char*)&_buf[pos]; pos += 1; if (!b->Dummy) { b->Name = std::string((const char*)&_buf[pos], min(32, strlen((const char*)&_buf[pos]))); pos += 32; b->Parent = *(short*)&_buf[pos]; pos += 2; b->BoneMatrixes.resize(m_data.NumActions); for (int j = 0; j < m_data.NumActions; j++) { BoneMatrix_t* bm = &b->BoneMatrixes[j]; //don't need to copy, pointing to data in _buf instead bm->Position = (vec3_t*)&_buf[pos]; pos += (m_data.Actions[j].NumAnimationKeys * sizeof(vec3_t)); bm->Rotation = (vec3_t*)&_buf[pos]; pos += (m_data.Actions[j].NumAnimationKeys * sizeof(vec3_t)); //AngleQuaternion skip } } else { b->Name = "Null " + std::to_string(i); b->Parent = -1; //for (int j = 0; j < m_data.NumActions; j++) b->BoneMatrixes.push_back(DUMMY_BONE_MATRIX); } if (_buf.size() < pos) { PRINT_DEBUG("[ERROR] Corrupted Bmd File"); return FALSE; } if (DEBUG_BMD) { PRINT_DEBUG_BMD("[Bones] : " << i); PRINT_DEBUG_BMD("\tDummy : " << ((int)b->Dummy)); if (!b->Dummy) { PRINT_DEBUG_BMD("\tName : " << b->Name); PRINT_DEBUG_BMD("\tParent : " << b->Parent); for (int ii = 0; ii < m_data.NumActions; ii++) { for (int jj = 0; jj < m_data.Actions[ii].NumAnimationKeys; jj++) { PRINT_DEBUG_BMD(std::fixed << "\t\t" << b->BoneMatrixes[ii].Position[jj][0] << "\t" << b->BoneMatrixes[ii].Position[jj][1] << "\t" << b->BoneMatrixes[ii].Position[jj][2] << "\t" << b->BoneMatrixes[ii].Rotation[jj][0] << "\t" << b->BoneMatrixes[ii].Rotation[jj][1] << "\t" << b->BoneMatrixes[ii].Rotation[jj][2]); } } } PRINT_DEBUG_BMD("========================================"); } } FixUpBones(); return TRUE; } BOOL BMD::SaveSmd(const char* szDest) { fs::path pFileName = fs::path(szDest).filename().replace_extension(""); fs::path pFile(szDest); Utls::CreateParentDir(pFile); fs::path pAnimDir(pFile); pAnimDir = pAnimDir.parent_path().append("anims"); //if (m_data.NumMeshs > 0) player.bmd has no mesh (only animations) { std::ofstream os1(pFile); Bmd2Smd(os1, SMD_REFERENCE); os1.close(); } if (m_data.NumActions == 1 && m_data.Actions[0].NumAnimationKeys == 1) { return TRUE; } for (short action = 0; action < m_data.NumActions; action++) { fs::path pFileAnim(pAnimDir); pFileAnim.append(pFileName.string()); // ./example_anims -> ./example_anims/example pFileAnim += "_" + std::to_string(action + 1) + ".smd"; // ./example_anims/example -> ./example_anims/example_1.smd Utls::CreateParentDir(pFileAnim); std::ofstream os2(pFileAnim); if (!os2.is_open()) { PRINT_DEBUG("[ERROR] Failed to write the smd file : " << pFileAnim); continue; } Bmd2Smd(os2, action); os2.close(); } return TRUE; } BOOL BMD::Bmd2Smd(std::ofstream& os, short action) { assert(action >= SMD_REFERENCE && action < m_data.NumActions); SMD_TYPE SmdType; if (action == SMD_REFERENCE) { SmdType = SMD_REFERENCE; action = 0; } else { SmdType = SMD_ANIMATION; } Action_t* a = &m_data.Actions[action]; os << "version 1" << std::endl; //================nodes===================== // [Index Name Parent] os << "nodes" << std::endl; for (int i = 0; i < m_data.Bones.size(); i++) { Bone_t* b = &m_data.Bones[i]; os << i << " \"" << b->Name << "\" " << b->Parent << std::endl; } os << "end" << std::endl; //================skeleton===================== // [time x] // [Node Position[3] Rotation[3]] os << "skeleton" << std::endl; for (int i = 0; i < a->NumAnimationKeys; i++) { //Only include 1 frame of animation to define the default pose in smd reference if (SmdType == SMD_REFERENCE && i > 0) break; os << "time " << i << std::endl; for (int j = 0; j < m_data.Bones.size(); j++) { Bone_t* b = &m_data.Bones[j]; if (!b->Dummy) { BoneMatrix_t* bm = &b->BoneMatrixes[action]; os << j << ' ' << std::fixed; os << bm->Position[i][0] << ' '; os << bm->Position[i][1] << ' '; os << bm->Position[i][2] << ' '; os << bm->Rotation[i][0] << ' '; os << bm->Rotation[i][1] << ' '; os << bm->Rotation[i][2] << std::endl; } else { os << j << ' ' << std::fixed; os << 0.0f << ' '; os << 0.0f << ' '; os << 0.0f << ' '; os << 0.0f << ' '; os << 0.0f << ' '; os << 0.0f << std::endl; } } } os << "end" << std::endl; if (SmdType == SMD_ANIMATION) return TRUE; //================triangles===================== // [TextureName] // [Node Position[3] Normal[3] TexCoord[2]] os << "triangles" << std::endl; assert(m_data.NumMeshs == m_data.Meshs.size() && m_data.NumMeshs == m_data.Textures.size()); for (int i = 0; i < m_data.NumMeshs; i++) { Mesh_t* m = &m_data.Meshs[i]; for (int j = 0; j < m->NumTriangles; j++) { os << m_data.Textures[i].FileName << std::endl; Triangle_t* t = &m->Triangles[j]; for (int k = 0; k < 3; k++) // k < t->Polygon { vec3_t p; short vertex_index = t->VertexIndex[k]; short vertex_node = m->Vertices[vertex_index].Node; short normal_index = t->NormalIndex[k]; short normal_node = m->Normals[normal_index].Node; short texcoord_index = t->TexCoordIndex[k]; short node = vertex_node; if (vertex_index < 0 || vertex_index >= m->NumVertices) { PRINT_DEBUG("[ERROR] vertex_index < 0 || vertex_index >= m->NumVertices"); return FALSE; } if (normal_index < 0 || normal_index >= m->NumNormals) { PRINT_DEBUG("[ERROR] normal_index < 0 || normal_index >= m->NumNormals"); return FALSE; } if (texcoord_index < 0 || texcoord_index >= m->NumTexCoords) { PRINT_DEBUG("[ERROR] texcoord_index < 0 || texcoord_index >= m->NumTexCoords"); return FALSE; } if (vertex_node < 0 || vertex_node >= m_data.NumBones) { PRINT_DEBUG("[ERROR] vertex_node < 0 || vertex_node >= m_data.NumBones"); return FALSE; } if (normal_node < 0 || normal_node >= m_data.NumBones) { PRINT_DEBUG("[ERROR] normal_index < 0 || normal_index >= m_data.NumBones"); return FALSE; } os << std::fixed << node << ' '; VectorTransform(m->Vertices[vertex_index].Position, BoneFixup[vertex_node].m, p); VectorAdd(p, BoneFixup[vertex_node].WorldOrg, p); os << p[0] << ' ' << p[1] << ' ' << p[2] << ' '; VectorTransform(m->Normals[normal_index].Normal, BoneFixup[normal_node].m, p); VectorNormalize(p); os << p[0] << ' ' << p[1] << ' ' << p[2] << ' '; os << m->TexCoords[texcoord_index].TexCoordU << ' ' << 1.0f - m->TexCoords[texcoord_index].TexCoordV << std::endl; } } } os << "end" << std::endl; return TRUE; } //======================================================================================== BOOL BMD::LoadSmd(const char* szSrc) { fs::path p(szSrc); std::string sName = p.filename().replace_extension("").string(); fs::path pAnimDir = p.parent_path().append("anims"); std::ifstream is(szSrc); if (!is.is_open()) { PRINT_DEBUG("[ERROR] Failed to read the smd file : " << szSrc); return FALSE; } Release(); m_data.Name = sName; BMD::ReadSmd(is, SMD_REFERENCE); is.close(); for (short action = 0; ; action++) { fs::path pFileAnim(pAnimDir); pFileAnim.append(sName + "_" + std::to_string(action + 1) + ".smd"); if (!fs::exists(pFileAnim)) break; std::ifstream is2(pFileAnim); BMD::ReadSmd(is2, action); is2.close(); } return Smd2Bmd(); } BOOL BMD::ReadSmd(std::ifstream& is, short action) { SMD_TYPE SmdType; if (action == SMD_REFERENCE) { SmdType = SMD_REFERENCE; action = 0; } else { if (action == 0) { //clear the 1st frame obtained from ref smd Temp_Bone_Pos.clear(); Temp_Bone_Rot.clear(); } SmdType = SMD_ANIMATION; } m_data.Actions.resize(action + 1); m_data.NumActions = m_data.Actions.size(); Action_t* a = &m_data.Actions[action]; a->NumAnimationKeys = 0; std::string bmd_name = m_data.Name + ".bmd"; std::transform(bmd_name.begin(), bmd_name.end(), bmd_name.begin(), ::tolower); a->LockPositions = BMD::GetLockPosition(bmd_name, action); std::string line; //================nodes===================== if (SmdType == SMD_REFERENCE) { while (std::getline(is, line)) { if (line == "nodes") break; } while (std::getline(is, line)) { if (line == "end") break; short node; short parent; char name[256]; sscanf(line.c_str(), "%hd \"%[^\"]%*c %hd", &node, name, &parent); Bone_t b; b.Dummy = (parent == -1 && node != 0) ? 1 : 0; b.Parent = parent; b.Name = std::string(name, min(32, strlen(name))); assert(node == m_data.Bones.size()); m_data.Bones.push_back(b); m_data.NumBones = m_data.Bones.size(); } } //================skeleton===================== while (std::getline(is, line)) { if (line == "skeleton") break; } Temp_Bone_Pos.resize(m_data.Bones.size()); Temp_Bone_Rot.resize(m_data.Bones.size()); for (int i = 0; i < m_data.Bones.size(); i++) { m_data.Bones[i].BoneMatrixes.resize(action + 1); Temp_Bone_Pos[i].resize(m_data.NumActions); Temp_Bone_Rot[i].resize(m_data.NumActions); } while (std::getline(is, line)) { if (line == "end") break; if (line[0] == 't' && line[1] == 'i' && line[2] == 'm' && line[3] == 'e') //time x { short key; sscanf(line.c_str(), "time %hd", &key); assert(key == a->NumAnimationKeys); a->NumAnimationKeys++; } else { short node; vec3_t pos; vec3_t rot; sscanf(line.c_str(), "%hd %f %f %f %f %f %f", &node, &pos[0], &pos[1], &pos[2], &rot[0], &rot[1], &rot[2]); if (node >= 0 && node < m_data.Bones.size()) { Temp_Bone_Pos[node][action].push_back(pos[0]); Temp_Bone_Pos[node][action].push_back(pos[1]); Temp_Bone_Pos[node][action].push_back(pos[2]); Temp_Bone_Rot[node][action].push_back(rot[0]); Temp_Bone_Rot[node][action].push_back(rot[1]); Temp_Bone_Rot[node][action].push_back(rot[2]); m_data.Bones[node].BoneMatrixes[action].Position = (vec3_t*) Temp_Bone_Pos[node][action].data(); m_data.Bones[node].BoneMatrixes[action].Rotation = (vec3_t*) Temp_Bone_Rot[node][action].data(); } } } if (a->LockPositions) { Temp_Lock_Pos.resize(action + 1); Temp_Lock_Pos[action].clear(); Bone_t* b = &m_data.Bones[0]; for (int i = 0; i < a->NumAnimationKeys; i++) { BoneMatrix_t* bm = &b->BoneMatrixes[action]; int j = i + 1; if (j > a->NumAnimationKeys - 1) j = a->NumAnimationKeys - 1; vec3_t p; VectorSubtract(bm->Position[j], bm->Position[i], p); Temp_Lock_Pos[action].push_back(p[0]); Temp_Lock_Pos[action].push_back(p[1]); Temp_Lock_Pos[action].push_back(p[2]); } a->Positions = (vec3_t*)Temp_Lock_Pos[action].data(); } else { a->Positions = NULL; } if (SmdType == SMD_REFERENCE) { FixUpBones(); } //================Triangles===================== if (SmdType == SMD_REFERENCE) { while (std::getline(is, line)) { if (line == "triangles") break; } while (std::getline(is, line)) { if (line == "end") break; char buffer[256]; sscanf(line.c_str(), "%s", &buffer); //texture name, no space ' ' std::string texture(buffer, min(32, strlen(buffer))); short texture_index = -1; for (int i = 0; i < m_data.Textures.size(); i++) { if (texture == m_data.Textures[i].FileName) { texture_index = i; break; } } if (texture_index == -1) { texture_index = m_data.Textures.size(); m_data.Textures.emplace_back(); m_data.Textures[m_data.Textures.size() - 1].FileName = texture; m_data.Meshs.emplace_back(); m_data.Meshs[m_data.Meshs.size()-1].Texture = texture_index; m_data.NumMeshs++; Temp_Vertex.emplace_back(); Temp_Normal.emplace_back(); Temp_TexCoord.emplace_back(); Temp_Triangle.emplace_back(); } Mesh_t* m = NULL; short mesh_index = -1; for (int i = 0; i < m_data.Meshs.size(); i++) { if (m_data.Meshs[i].Texture == texture_index) { m = &m_data.Meshs[i]; mesh_index = i; break; } } assert(m != NULL && mesh_index != -1); Triangle_t triangle; for (int k = 0; k < 3; k++) { std::getline(is, line); short node; //bone_index Vertex_t v; Normal_t n; TexCoord_t t; sscanf(line.c_str(), "%hd %f %f %f %f %f %f %f %f", &node, &v.Position[0], &v.Position[1], &v.Position[2], &n.Normal[0], &n.Normal[1], &n.Normal[2], &t.TexCoordU, &t.TexCoordV); t.TexCoordV = 1.0f - t.TexCoordV; vec3_t p; // move vertex position to object space. VectorSubtract(v.Position, BoneFixup[node].WorldOrg, p); VectorTransform(p, BoneFixup[node].im, v.Position); // move normal to object space. VectorCopy(n.Normal, p); VectorTransform(p, BoneFixup[node].im, n.Normal); VectorNormalize(n.Normal); short vertex_index = -1; for (int i = Temp_Vertex[mesh_index].size() - 1; i >= 0; i--) { if (VectorCompare(v.Position, Temp_Vertex[mesh_index][i].Position)) //&& node == Temp_Vertex[mesh_index][i].Node { vertex_index = i; break; } } if (vertex_index == -1) { vertex_index = Temp_Vertex[mesh_index].size(); v.Node = node; Temp_Vertex[mesh_index].push_back(v); } short normal_index = -1; for (int i = Temp_Normal[mesh_index].size() - 1; i >= 0 ; i--) { if (VectorCompare(n.Normal, Temp_Normal[mesh_index][i].Normal))// && node == Temp_Normal[mesh_index][i].Node { normal_index = i; break; } } if (normal_index == -1) { normal_index = Temp_Normal[mesh_index].size(); n.Node = node; Temp_Normal[mesh_index].push_back(n); } short texcoord_index = -1; for (int i = Temp_TexCoord[mesh_index].size() - 1; i >= 0; i--) { if (fabs(t.TexCoordU - Temp_TexCoord[mesh_index][i].TexCoordU) < EQUAL_EPSILON && fabs(t.TexCoordV - Temp_TexCoord[mesh_index][i].TexCoordV) < EQUAL_EPSILON) { texcoord_index = i; break; } } if (texcoord_index == -1) { texcoord_index = Temp_TexCoord[mesh_index].size(); Temp_TexCoord[mesh_index].push_back(t); } triangle.VertexIndex[k] = vertex_index; triangle.NormalIndex[k] = normal_index; triangle.TexCoordIndex[k] = texcoord_index; } triangle.Polygon = 3; Temp_Triangle[mesh_index].push_back(triangle); m->NumVertices = Temp_Vertex[mesh_index].size(); m->NumNormals = Temp_Normal[mesh_index].size(); m->NumTexCoords = Temp_TexCoord[mesh_index].size(); m->NumTriangles = Temp_Triangle[mesh_index].size(); m->Vertices = Temp_Vertex[mesh_index].data(); m->Normals = Temp_Normal[mesh_index].data(); m->TexCoords = Temp_TexCoord[mesh_index].data(); m->Triangles = Temp_Triangle[mesh_index].data(); } } return TRUE; } BOOL BMD::SaveBmd(const char* szDest) { Utls::CreateParentDir(szDest); return Encrypt() && FileWrite(szDest); } BOOL BMD::Smd2Bmd(BYTE version) { m_data.Version = version; //default version = 0xA (no crypt) size_t size = 0; size += 38; //header for (int i = 0; i < m_data.NumMeshs; i++) { Mesh_t* m = &m_data.Meshs[i]; size += 10; size += m->NumVertices * sizeof(Vertex_t); size += m->NumNormals * sizeof(Normal_t); size += m->NumTexCoords * sizeof(TexCoord_t); size += m->NumTriangles * sizeof(Triangle_t); size += 32; } for (int i = 0; i < m_data.NumActions; i++) { Action_t* a = &m_data.Actions[i]; size += 3; if (a->LockPositions) size += a->NumAnimationKeys * sizeof(vec3_t); } for (int i = 0; i < m_data.NumBones; i++) { Bone_t* b = &m_data.Bones[i]; size += 1; if (!b->Dummy) { size += 32; size += 2; for (int j = 0; j < m_data.NumActions; j++) { size += 2 * m_data.Actions[j].NumAnimationKeys * sizeof(vec3_t); } } } _buf.resize(size); size_t pos = 0; size_t sz = 0; //header memcpy(&_buf[pos], m_data.Name.data(), min(32, 1 + m_data.Name.length())); pos += 32; *(short*)&_buf[pos] = m_data.NumMeshs; pos += 2; *(short*)&_buf[pos] = m_data.NumBones; pos += 2; *(short*)&_buf[pos] = m_data.NumActions; pos += 2; for (int i = 0; i < m_data.NumMeshs; i++) { Mesh_t* m = &m_data.Meshs[i]; *(short*)&_buf[pos] = m->NumVertices; pos += 2; *(short*)&_buf[pos] = m->NumNormals; pos += 2; *(short*)&_buf[pos] = m->NumTexCoords; pos += 2; *(short*)&_buf[pos] = m->NumTriangles; pos += 2; *(short*)&_buf[pos] = m->Texture; pos += 2; sz = m->NumVertices * sizeof(Vertex_t); memcpy(&_buf[pos], m->Vertices, sz); pos += sz; sz = m->NumNormals * sizeof(Normal_t); memcpy(&_buf[pos], m->Normals, sz); pos += sz; sz = m->NumTexCoords * sizeof(TexCoord_t); memcpy(&_buf[pos], m->TexCoords, sz); pos += sz; sz = m->NumTriangles * sizeof(Triangle_t); memcpy(&_buf[pos], m->Triangles, sz); pos += sz; memcpy(&_buf[pos], m_data.Textures[i].FileName.data(), min(32, 1 + m_data.Textures[i].FileName.length())); pos += 32; } for (int i = 0; i < m_data.NumActions; i++) { Action_t* a = &m_data.Actions[i]; *(short*)&_buf[pos] = a->NumAnimationKeys; pos += 2; *(bool*)&_buf[pos] = a->LockPositions; pos += 1; if (a->LockPositions && a->Positions) { sz = a->NumAnimationKeys * sizeof(vec3_t); memcpy(&_buf[pos], a->Positions, sz); pos += sz; } } for (int i = 0; i < m_data.NumBones; i++) { Bone_t* b = &m_data.Bones[i]; *(char*)&_buf[pos] = b->Dummy; pos += 1; if (!b->Dummy) { memcpy(&_buf[pos], b->Name.data(), min(32, 1 + b->Name.length())); pos += 32; *(short*)&_buf[pos] = b->Parent; pos += 2; for (int j = 0; j < m_data.NumActions; j++) { BoneMatrix_t* bm = &b->BoneMatrixes[j]; sz = m_data.Actions[j].NumAnimationKeys * sizeof(vec3_t); memcpy(&_buf[pos], bm->Position, sz); pos += sz; memcpy(&_buf[pos], bm->Rotation, sz); pos += sz; } } } return TRUE; }
25.272277
181
0.582305
daldegam
db84794d9131cc2a77c2c8c9a6a61d4ef637befe
6,111
cpp
C++
export/windows/obj/src/openfl/display/Window.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/display/Window.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/display/Window.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_lime_app_Application #include <lime/app/Application.h> #endif #ifndef INCLUDED_lime_app_IModule #include <lime/app/IModule.h> #endif #ifndef INCLUDED_lime_app_Module #include <lime/app/Module.h> #endif #ifndef INCLUDED_lime_ui_Window #include <lime/ui/Window.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectContainer #include <openfl/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_LoaderInfo #include <openfl/display/LoaderInfo.h> #endif #ifndef INCLUDED_openfl_display_Stage #include <openfl/display/Stage.h> #endif #ifndef INCLUDED_openfl_display_Window #include <openfl/display/Window.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_a9a8b88d3857954c_27_new,"openfl.display.Window","new",0x253949cc,"openfl.display.Window.new","openfl/display/Window.hx",27,0x156e59e2) namespace openfl{ namespace display{ void Window_obj::__construct( ::lime::app::Application application, ::Dynamic attributes){ HX_GC_STACKFRAME(&_hx_pos_a9a8b88d3857954c_27_new) HXLINE( 29) super::__construct(application,attributes); HXLINE( 42) ::Dynamic _hx_tmp; HXDLIN( 42) if (::Reflect_obj::hasField( ::Dynamic(attributes->__Field(HX_("context",ef,95,77,19),hx::paccDynamic)),HX_("background",ee,93,1d,26))) { HXLINE( 42) _hx_tmp = ::Dynamic(attributes->__Field(HX_("context",ef,95,77,19),hx::paccDynamic))->__Field(HX_("background",ee,93,1d,26),hx::paccDynamic); } else { HXLINE( 42) _hx_tmp = (int)16777215; } HXDLIN( 42) this->stage = ::openfl::display::Stage_obj::__alloc( HX_CTX ,hx::ObjectPtr<OBJ_>(this),_hx_tmp); HXLINE( 44) if (::Reflect_obj::hasField(attributes,HX_("parameters",aa,be,7e,51))) { HXLINE( 46) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 48) this->stage->get_loaderInfo()->parameters = ::Dynamic(attributes->__Field(HX_("parameters",aa,be,7e,51),hx::paccDynamic)); } catch( ::Dynamic _hx_e){ if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic e = _hx_e; } else { HX_STACK_DO_THROW(_hx_e); } } } HXLINE( 54) bool _hx_tmp1; HXDLIN( 54) if (::Reflect_obj::hasField(attributes,HX_("resizable",6b,37,50,a9))) { HXLINE( 54) _hx_tmp1 = !(( (bool)(attributes->__Field(HX_("resizable",6b,37,50,a9),hx::paccDynamic)) )); } else { HXLINE( 54) _hx_tmp1 = false; } HXDLIN( 54) if (_hx_tmp1) { HXLINE( 56) this->stage->_hx___setLogicalSize(( (int)(attributes->__Field(HX_("width",06,b6,62,ca),hx::paccDynamic)) ),( (int)(attributes->__Field(HX_("height",e7,07,4c,02),hx::paccDynamic)) )); } HXLINE( 60) application->addModule(this->stage); } Dynamic Window_obj::__CreateEmpty() { return new Window_obj; } void *Window_obj::_hx_vtable = 0; Dynamic Window_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Window_obj > _hx_result = new Window_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool Window_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x1abdb2dd) { return inClassId==(int)0x00000001 || inClassId==(int)0x1abdb2dd; } else { return inClassId==(int)0x2c659efa; } } hx::ObjectPtr< Window_obj > Window_obj::__new( ::lime::app::Application application, ::Dynamic attributes) { hx::ObjectPtr< Window_obj > __this = new Window_obj(); __this->__construct(application,attributes); return __this; } hx::ObjectPtr< Window_obj > Window_obj::__alloc(hx::Ctx *_hx_ctx, ::lime::app::Application application, ::Dynamic attributes) { Window_obj *__this = (Window_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Window_obj), true, "openfl.display.Window")); *(void **)__this = Window_obj::_hx_vtable; __this->__construct(application,attributes); return __this; } Window_obj::Window_obj() { } #if HXCPP_SCRIPTABLE static hx::StorageInfo *Window_obj_sMemberStorageInfo = 0; static hx::StaticInfo *Window_obj_sStaticStorageInfo = 0; #endif static void Window_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Window_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void Window_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Window_obj::__mClass,"__mClass"); }; #endif hx::Class Window_obj::__mClass; void Window_obj::__register() { hx::Object *dummy = new Window_obj; Window_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.display.Window","\xda","\xb3","\xcd","\xdc"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = Window_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< Window_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Window_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Window_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Window_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace display
35.12069
197
0.720831
seanbashaw
db8851780d0b9024971f12eefcb23dcbfcdefa55
4,558
cpp
C++
src/brew/video/Frustum.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
1
2018-02-09T16:20:50.000Z
2018-02-09T16:20:50.000Z
src/brew/video/Frustum.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
src/brew/video/Frustum.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
/** * * |_ _ _ * |_)| (/_VV * * Copyright 2015-2018 Marcus v. Keil * * Created on: 02.01.2015 * */ #include <brew/video/Frustum.h> #include <brew/math/BoundingBox.h> namespace brew { const Vec3 Frustum::clipSpacePlanePoints[8] = { /* near clip plane */ Vec3(-1, -1, -1), Vec3(1, -1, -1), Vec3(1, 1, -1), Vec3(-1, 1, -1), /* far clip plane */ Vec3(-1, -1, 1), Vec3(1, -1, 1), Vec3(1, 1, 1), Vec3(-1, 1, 1), }; Frustum::Frustum() { for (u8 i = 0; i < 6; i++) { planes[i] = Plane(Vec3::ZERO, 0); } } void Frustum::update(const Matrix4& inverseProjectionView) { for (SizeT i = 0; i < 8; ++i) { Vec3& v = planePoints[i]; v = clipSpacePlanePoints[i]; v = inverseProjectionView * v; } planes[0].set(planePoints[1], planePoints[0], planePoints[2]); planes[1].set(planePoints[4], planePoints[5], planePoints[7]); planes[2].set(planePoints[0], planePoints[4], planePoints[3]); planes[3].set(planePoints[5], planePoints[1], planePoints[6]); planes[4].set(planePoints[2], planePoints[3], planePoints[6]); planes[5].set(planePoints[4], planePoints[0], planePoints[1]); } bool Frustum::pointInFrustum(Real x, Real y, Real z) const { for (u8 i = 0; i < 6; i++) { Plane::PlaneSide result = planes[i].getFacingSide(x, y, z); if (result == Plane::PlaneSide::Back) return false; } return true; } inline bool checkBoundsInFrustumExclusive(const Plane* planes, const BoundingBox& bounds) { for (u8 i = 0; i < 6; i++) { if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xyz)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xyZ)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xYz)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xYZ)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::Xyz)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XyZ)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XYz)) == Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XYZ)) == Plane::PlaneSide::Back) continue; /** * At least one theoretically visible point is sufficient for non-inclusive tests. */ return true; } // None of the points are visible. return false; } inline bool checkBoundsInFrustumInclusive(const Plane* planes, const BoundingBox& bounds) { for (u8 i = 0; i < 6; i++) { if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xyz)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xyZ)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xYz)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::xYZ)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::Xyz)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XyZ)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XYz)) != Plane::PlaneSide::Back) continue; if (planes[i].getFacingSide(bounds.getCorner(BoundingBox::Corner::XYZ)) != Plane::PlaneSide::Back) continue; /** * At least one invisible point is found, so this box cannot be inclusive. */ return false; } // All points are visible. return true; } bool Frustum::boundsInFrustum(const BoundingBox& bounds, bool inclusive) const { return inclusive ? checkBoundsInFrustumInclusive(planes, bounds) : checkBoundsInFrustumExclusive(planes, bounds); } } /* namespace brew */
36.174603
118
0.595217
grrrrunz
db8d4d497e7db2d4dac2087794c56ce6206150e6
3,963
hpp
C++
src/mlpack/core/util/param_data_impl.hpp
17minutes/mlpack
8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-09-22T18:12:40.000Z
2021-11-17T10:39:58.000Z
src/mlpack/core/util/param_data_impl.hpp
kosmaz/Mlpack
62100ddca45880a57e7abb0432df72d285e5728b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/core/util/param_data_impl.hpp
kosmaz/Mlpack
62100ddca45880a57e7abb0432df72d285e5728b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file param_data_impl.hpp * @author Ryan Curtin * * Implementation of utility functions for ParamData structures. */ #ifndef MLPACK_CORE_UTIL_PARAM_DATA_IMPL_HPP #define MLPACK_CORE_UTIL_PARAM_DATA_IMPL_HPP #include "param_data.hpp" #include <mlpack/core/data/load.hpp> namespace mlpack { namespace util { //! This overload is called when nothing special needs to happen to the name of //! the parameter. template<typename T> std::string MapParameterName( const std::string& identifier, const typename boost::disable_if<arma::is_arma_type<T>>::type* /* junk */, const typename boost::disable_if<data::HasSerialize<T>>::type* /* junk */, const typename boost::disable_if<std::is_same<T, std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* /* junk */) { return identifier; } //! This is called for matrices, DatasetInfo objects, and serializable objects, //! which have a different boost name. template<typename T> std::string MapParameterName( const std::string& identifier, const typename boost::enable_if_c< arma::is_arma_type<T>::value || std::is_same<T, std::tuple<mlpack::data::DatasetInfo, arma::mat>>::value || data::HasSerialize<T>::value>::type* /* junk */) { return identifier + "_file"; } //! This overload is called when T == ParameterType<T>::value. template<typename T> T& HandleParameter( typename ParameterType<T>::type& value, ParamData& /* d */, const typename boost::disable_if<arma::is_arma_type<T>>::type* /* junk */, const typename boost::disable_if<data::HasSerialize<T>>::type* /* junk */, const typename boost::disable_if<std::is_same<T, std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* /* junk */) { return value; } //! This overload is called for matrices, which return a different type. template<typename T> T& HandleParameter( typename ParameterType<T>::type& value, ParamData& d, const typename boost::enable_if<arma::is_arma_type<T>>::type* /* junk */) { // If the matrix is an input matrix, we have to load the matrix. 'value' // contains the filename. It's possible we could load empty matrices many // times, but I am not bothered by that---it shouldn't be something that // happens. T& matrix = *boost::any_cast<T>(&d.mappedValue); if (d.input && !d.loaded) { // call correct data::Load() function if (arma::is_Row<T>::value || arma::is_Col<T>::value) data::Load(value, matrix, true); else data::Load(value, matrix, true, !d.noTranspose); d.loaded = true; } return matrix; } //! This must be overloaded for matrices and dataset info objects. template<typename T> T& HandleParameter( typename util::ParameterType<T>::type& value, util::ParamData& d, const typename boost::enable_if<std::is_same<T, std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* /* junk */) { // If this is an input parameter, we need to load both the matrix and the // dataset info. std::tuple<mlpack::data::DatasetInfo, arma::mat>& tuple = *boost::any_cast<std::tuple<mlpack::data::DatasetInfo, arma::mat>>(&d.mappedValue); if (d.input && !d.loaded) { data::Load(value, std::get<1>(tuple), std::get<0>(tuple), true, !d.noTranspose); d.loaded = true; } return tuple; } //! This is called for serializable mlpack objects, which have a different boost //! name. template<typename T> T& HandleParameter( typename ParameterType<T>::type& value, ParamData& d, const typename boost::enable_if<data::HasSerialize<T>>::type* /* junk */) { // If the model is an input model, we have to load it from file. 'value' // contains the filename. T& model = *boost::any_cast<T>(&d.mappedValue); if (d.input && !d.loaded) { data::Load(value, "model", model, true); d.loaded = true; } return model; } } // namespace util } // namespace mlpack #endif
30.960938
80
0.66591
17minutes
db8de7de063c936aae6fb334e44d2be5f63a20f5
958
hpp
C++
source/backend/opencl/execution/image/MultiInputDWDeconvExecution.hpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
6,958
2019-05-06T02:38:02.000Z
2022-03-31T18:08:48.000Z
source/backend/opencl/execution/image/MultiInputDWDeconvExecution.hpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
1,775
2019-05-06T04:40:19.000Z
2022-03-30T15:39:24.000Z
source/backend/opencl/execution/image/MultiInputDWDeconvExecution.hpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
1,511
2019-05-06T02:38:05.000Z
2022-03-31T16:59:39.000Z
// // MultiInputDWDeconvExecution.hpp // MNN // // Created by MNN on 2019/10/25. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef MultiInputDWDeconvExecution_hpp #define MultiInputDWDeconvExecution_hpp #include "backend/opencl/execution/image/CommonExecution.hpp" #include "backend/opencl/core/OpenCLRunningUtils.hpp" namespace MNN { namespace OpenCL { class MultiInputDWDeconvExecution : public CommonExecution { public: MultiInputDWDeconvExecution(const MNN::Op *op, Backend *backend); virtual ~MultiInputDWDeconvExecution(); virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; private: std::vector<int> mStrides; std::vector<int> mPaddings; std::vector<int> mDilations; std::shared_ptr<Tensor> mFilter; bool isRelu = false; bool isRelu6 = false; }; } // namespace OpenCL } // namespace MNN #endif /* MultiInputDWDeconvExecution_hpp */
25.891892
115
0.744259
foreverlms
db8f5dba0549f94dca4b9c9841bccc4f465c9d19
569
hpp
C++
concepts/is_lvalue_reference.hpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
2
2020-11-05T07:39:05.000Z
2021-01-07T18:29:56.000Z
concepts/is_lvalue_reference.hpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
null
null
null
concepts/is_lvalue_reference.hpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
null
null
null
#pragma once namespace lux { namespace concepts { template<class T> class is_lvalue_reference_class { public: constexpr static bool value = false; }; template<class T> class is_lvalue_reference_class<T&> { public: constexpr static bool value = true; }; ///Returns at compile-time if T is an lvalue reference type template<class T> concept is_lvalue_reference = is_lvalue_reference_class<T>::value; } } /** @example concepts/is_lvalue_reference.cpp */
24.73913
92
0.616872
SamuelAlonsoDev
db97ec8245f1f34cd415fc6a0832bf385d873a5c
1,448
cpp
C++
code/libImmExporter/src/document/layerModel3d.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
33
2021-09-16T18:37:08.000Z
2022-03-22T23:02:44.000Z
code/libImmExporter/src/document/layerModel3d.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
5
2021-09-17T10:10:07.000Z
2022-03-28T12:33:29.000Z
code/libImmExporter/src/document/layerModel3d.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
5
2021-09-19T07:49:01.000Z
2021-12-12T21:25:35.000Z
#include "libImmCore/src/libBasics/piFile.h" #include "layerModel3d.h" using namespace ImmCore; namespace ImmExporter { LayerModel::LayerModel() {} LayerModel::~LayerModel() {} bool LayerModel::Init(uint32_t version) { //mMesh.Init(); mVersion = version; mRenderWireFrame = false; mShadingModel = ShadingModel::Unlit; mHasAsset = false; return true; } void LayerModel::Deinit() { if(mHasAsset) mMesh.DeInit(); } bool LayerModel::AssignAsset(const piMesh *asset, bool move) { if (move) mMesh.InitMove(asset); else asset->Clone(&mMesh); mHasAsset = true; return true; } const LayerModel::ShadingModel LayerModel::GetShadingModel(void) const { return mShadingModel; } void LayerModel::SetShadingModel(const ShadingModel shadingModel) { mShadingModel = shadingModel; } const bool LayerModel::GetRenderWireframe(void) const { return mRenderWireFrame; } void LayerModel::SetRenderWireframe(bool renderWireFrame) { mRenderWireFrame = renderWireFrame; } const bool LayerModel::HasBBox(void) const { return true; } const bound3 & LayerModel::GetBBox(void) const { return mMesh.mBBox; } piMesh *LayerModel::GetMesh(void) { if (!mHasAsset) return nullptr; return &mMesh; } }
18.564103
74
0.620856
andybak
db9bb243976612cdc0e7a3b4228d540e6a47366f
5,211
cpp
C++
instdrv/instdrvDlg.cpp
berkut126/Drivers
a615e874a222d89020818edca5693907cc9b3b20
[ "BSD-2-Clause" ]
9
2020-12-27T16:55:47.000Z
2020-12-28T17:11:12.000Z
instdrv/instdrvDlg.cpp
berkut126/Drivers
a615e874a222d89020818edca5693907cc9b3b20
[ "BSD-2-Clause" ]
1
2020-11-01T15:59:48.000Z
2020-11-01T15:59:48.000Z
instdrv/instdrvDlg.cpp
berkut126/Drivers
a615e874a222d89020818edca5693907cc9b3b20
[ "BSD-2-Clause" ]
1
2021-06-01T23:20:17.000Z
2021-06-01T23:20:17.000Z
/* * This is a personal academic project. Dear PVS-Studio, please check it. * PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com */ // instdrvDlg.cpp : implementation file // // ReSharper disable CppMemberFunctionMayBeConst // ReSharper disable CppMemberFunctionMayBeStatic #include "pch.h" #include "framework.h" #include "instdrv.h" #include "instdrvDlg.h" #include "afxdialogex.h" #include "CScMgr.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CinstdrvDlg dialog CinstdrvDlg::CinstdrvDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_INSTDRV_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CinstdrvDlg::DoDataExchange(CDataExchange* p_dx) { CDialogEx::DoDataExchange(p_dx); // DDX_Control(pDX, IDB_ADD, m_butAdd); // DDX_Control(pDX, IDB_CLOSE, m_butClose); // DDX_Control(pDX, IDB_OPEN, m_butOpen); // DDX_Control(pDX, IDB_PATH, m_butPath); // DDX_Control(pDX, IDB_REMOVE, m_butRemove); // DDX_Control(pDX, IDB_START, m_butStart); // DDX_Control(pDX, IDB_STOP, m_butStop); DDX_Control(p_dx, IDC_LOG, m_edt_log); DDX_Control(p_dx, IDC_PATH, m_edt_path); DDX_Control(p_dx, IDC_SER, m_edt_ser); DDX_Control(p_dx, IDC_SYM, m_edt_sym); } BEGIN_MESSAGE_MAP(CinstdrvDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDB_ADD, &CinstdrvDlg::on_clicked_idb_add) ON_BN_CLICKED(IDB_CLOSE, &CinstdrvDlg::on_clicked_idb_close) ON_BN_CLICKED(IDB_OPEN, &CinstdrvDlg::on_clicked_idb_open) ON_BN_CLICKED(IDB_PATH, &CinstdrvDlg::on_clicked_idb_path) ON_BN_CLICKED(IDB_REMOVE, &CinstdrvDlg::on_clicked_idb_remove) ON_BN_CLICKED(IDB_START, &CinstdrvDlg::on_clicked_idb_start) ON_BN_CLICKED(IDB_STOP, &CinstdrvDlg::on_clicked_idb_stop) END_MESSAGE_MAP() // CinstdrvDlg message handlers BOOL CinstdrvDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here m_edt_path.SetWindowText(L"C:\\Users\\WDKRemoteUser\\Desktop\\simple3\\simple3.sys"); m_edt_ser.SetWindowText(L"Service3"); m_edt_sym.SetWindowText(L"\\\\.\\\\Simple3Link"); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CinstdrvDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle const auto cx_icon = GetSystemMetrics(SM_CXICON); const auto cy_icon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); const auto x = (rect.Width() - cx_icon + 1) / 2; const auto y = (rect.Height() - cy_icon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CinstdrvDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CinstdrvDlg::on_clicked_idb_add() { c_sc_mgr manager; CString path, name; m_edt_path.GetWindowText(path); m_edt_ser.GetWindowText(name); if(manager.install_driver(path, name)) { print(L"Driver added"); } else { print(L"Driver not added"); } } void CinstdrvDlg::on_clicked_idb_close() { c_sc_mgr manager; CString symlink; m_edt_sym.GetWindowText(symlink); if(manager.close_device(symlink)) { print(L"Device closed"); } else { print(L"Device not closed"); } } void CinstdrvDlg::on_clicked_idb_open() { c_sc_mgr manager; CString symlinkPath; m_edt_sym.GetWindowText(symlinkPath); if(manager.open_device(symlinkPath)) { print(L"Device opened"); } else { print(L"Device not opened"); } } void CinstdrvDlg::on_clicked_idb_path() { CFileDialog open_dialog(TRUE); if (open_dialog.DoModal() == IDOK) { m_edt_path.SetWindowText(open_dialog.GetPathName()); } } void CinstdrvDlg::on_clicked_idb_remove() { c_sc_mgr manager; CString name; m_edt_ser.GetWindowText(name); if(manager.delete_driver(name)) { print(L"Driver removed"); } else { print(L"Driver not removed"); } } void CinstdrvDlg::on_clicked_idb_start() { c_sc_mgr manager; CString name; m_edt_ser.GetWindowText(name); if(manager.run_driver(name)) { print(L"Driver started"); } else { print(L"Driver not started"); } } void CinstdrvDlg::on_clicked_idb_stop() { c_sc_mgr manager; CString name; m_edt_ser.GetWindowText(name); if(manager.stop_driver(name)) { print(L"Driver stopped"); } else { print(L"Driver not stopped"); } } void CinstdrvDlg::print(const std::wstring& message) { CString cur_text; m_edt_log.GetWindowText(cur_text); cur_text = cur_text + (message + L"\r\n").c_str(); m_edt_log.SetWindowText(cur_text); } void CinstdrvDlg::print_success(const std::wstring& error) { m_edt_log.ReplaceSel((error + L"\r\n").c_str()); }
21.622407
86
0.734984
berkut126
db9bf2fcd966d603e4983b8dbef78ad528e73407
18,840
cpp
C++
DKPlugins/DKVncServer/DKVncServer.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
29
2015-05-03T06:23:22.000Z
2022-02-10T15:16:26.000Z
DKPlugins/DKVncServer/DKVncServer.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
125
2016-02-28T06:13:49.000Z
2022-01-04T11:50:08.000Z
DKPlugins/DKVncServer/DKVncServer.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
8
2016-12-04T02:29:34.000Z
2022-01-04T01:11:25.000Z
#include "DK/stdafx.h" #include "DK/DKFile.h" #include "DKVncServer.h" #ifdef WIN32 #define sleep Sleep #include <WS2tcpip.h> #endif #ifdef LINUX #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> Display* DKVncServer::disp; Window DKVncServer::root; XImage* DKVncServer::image; #endif #ifdef MAC CGImageRef DKVncServer::image_ref; CGDataProviderRef DKVncServer::provider; CFDataRef DKVncServer::dataref; #endif #ifdef __IRIX__ #include <netdb.h> #endif #include <rfb/keysym.h> #include "radon.h" static rfbScreenInfoPtr rfbScreen; static int bpp = 4; /* rfbPixelFormat pixfmt = { 32, //U8 bitsPerPixel; 32, //U8 depth; 0, //U8 bigEndianFlag; 1, //U8 trueColourFlag; 255, //U16 redMax; 255, //U16 greenMax; 255, //U16 blueMax; 16, //U8 redShift; 8, //U8 greenShift; 0, //U8 blueShift; 0, //U8 pad 1; 0 //U8 pad 2 }; */ const rfbPixelFormat vnc8bitFormat = { 8, 8, 0, 1, 7, 7, 3, 0, 3, 6, 0, 0 }; const rfbPixelFormat vnc16bitFormat = { 16, 16, 0, 1, 63, 31, 31, 0, 6, 11, 0, 0 }; const rfbPixelFormat vnc24bitFormat = { 32, 24, 0, 1, 255, 255, 255, 16, 8, 0, 0, 0 }; ///////////////////////// typedef struct ClientData { //int key = 0; int buttonMask = 0; DKString ipaddress; } ClientData; std::vector<ClientLog> DKVncServer::clientLog; DKString DKVncServer::capture; //////////////////////// bool DKVncServer::Init() { DKDEBUGFUNC(); DKFile::GetSetting(DKFile::local_assets + "settings.txt", "[VNC_CAPTURE]", capture); if(capture.empty()){ capture = "GDI"; } //DIRECT X static DKString password; DKFile::GetSetting(DKFile::local_assets + "settings.txt", "[VNC_PASSWORD]", password); if(password.empty()){ DKWARN("WARNING! No password set in settings file!\n"); } int desktopWidth; int desktopHeight; DKUtil::GetScreenWidth(desktopWidth); DKUtil::GetScreenHeight(desktopHeight); /* #ifdef MAC image_ref = CGDisplayCreateImage(CGMainDisplayID()); provider = CGImageGetDataProvider(image_ref); dataref = CGDataProviderCopyData(provider); #endif */ #ifdef LINUX disp = XOpenDisplay(NULL); root = XDefaultRootWindow(disp); #endif rfbScreen = rfbGetScreen(&DKApp::argc, DKApp::argv, desktopWidth, desktopHeight, 8, 3, bpp); if(!rfbScreen){ DKERROR("DKVncServer::Init(): rfbScreen is invalid\n"); return false; } rfbScreen->desktopName = "DKVncServer"; rfbScreen->frameBuffer = (char*)malloc(desktopHeight * desktopWidth * bpp); rfbScreen->alwaysShared = TRUE; rfbScreen->ptrAddEvent = mouseevent; rfbScreen->kbdAddEvent = keyevent; rfbScreen->newClientHook = newclient; rfbScreen->httpDir = (char*)DKFile::local_assets.c_str(); //+"DKVncServer"; rfbScreen->httpEnableProxyConnect = TRUE; rfbScreen->serverFormat = vnc24bitFormat; if(!password.empty()){ static const char* pass = password.c_str(); static const char* passwords[2]={pass, 0}; rfbScreen->authPasswdData = (void*)passwords; rfbScreen->passwordCheck = rfbCheckPasswordByList2; } rfbInitServer(rfbScreen); DKApp::AppendLoopFunc(&DKVncServer::Loop, this); return true; } /////////////////////// bool DKVncServer::End() { DKDEBUGFUNC(); return true; } /////////////////////////////////////////////////////////////// enum rfbNewClientAction DKVncServer::newclient(rfbClientPtr cl) { DKDEBUGFUNC(cl); cl->clientData = (void*)calloc(sizeof(ClientData), 1); cl->clientGoneHook = clientgone; //Get client ip address struct sockaddr_in addr; socklen_t len = sizeof(addr); unsigned int ip; getpeername(cl->sock, (struct sockaddr*)&addr, &len); ip = ntohl(addr.sin_addr.s_addr); ClientData* cd = (ClientData*)cl->clientData; cd->ipaddress = toString((ip>>24)&0xff)+"."+toString((ip>>16)&0xff)+"."+toString((ip>>8)&0xff)+"."+toString(ip&0xff); DKINFO("Client ip address: "+cd->ipaddress+"\n"); for(unsigned int i=0; i<clientLog.size(); i++){ if(same(cd->ipaddress, clientLog[i].ipaddress)){ if(clientLog[i].failed_attempts > 2){ DKWARN(cd->ipaddress+" is banned from this server\n"); return RFB_CLIENT_REFUSE; } } } return RFB_CLIENT_ACCEPT; } ///////////////////////////////////////////// void DKVncServer::clientgone(rfbClientPtr cl) { DKDEBUGFUNC(cl); free(cl->clientData); cl->clientData = NULL; } //////////////////////// void DKVncServer::Loop() { //DKDEBUGFUNC(); if(rfbProcessEvents(rfbScreen, 1)){ DrawBuffer(); } } //////////////////////////////////////////////////////////////////////////////////////////// rfbBool DKVncServer::rfbCheckPasswordByList2(rfbClientPtr cl, const char* response, int len) { DKDEBUGFUNC(cl, response, len); char **passwds; int i=0; //search for ipaddress in clientLog or add new ClientData* cd = (ClientData*)cl->clientData; int current_client = -1; for(unsigned int i=0; i<clientLog.size(); i++){ if(same(cd->ipaddress, clientLog[i].ipaddress)){ current_client = i; continue; } } if(current_client == -1){ ClientLog cl; cl.ipaddress = cd->ipaddress; clientLog.push_back(cl); current_client = clientLog.size()-1; } for(passwds=(char**)cl->screen->authPasswdData; *passwds; passwds++,i++){ uint8_t auth_tmp[CHALLENGESIZE]; memcpy((char *)auth_tmp, (char *)cl->authChallenge, CHALLENGESIZE); rfbEncryptBytes(auth_tmp, *passwds); if(memcmp(auth_tmp, response, len) == 0){ if(i >= cl->screen->authPasswdFirstViewOnly) cl->viewOnly=TRUE; clientLog[current_client].failed_attempts = 0; return(TRUE); } } rfbErr("authProcessClientMessage: authentication failed from %s\n", cl->host); clientLog[current_client].failed_attempts++; return(FALSE); } ////////////////////////////// void DKVncServer::DrawBuffer() { //DKDEBUGFUNC(); #ifdef WIN32 //Capture Desktop with DirectX if(capture == "DIRECTX"){ //DKINFO("DIRECTX\n"); //https://stackoverflow.com/questions/30021274/capture-screen-using-directx HRESULT hr = S_OK; IDirect3D9 *d3d = nullptr; IDirect3DDevice9 *device = nullptr; IDirect3DSurface9 *surface = nullptr; D3DPRESENT_PARAMETERS parameters = { 0 }; D3DDISPLAYMODE mode; D3DLOCKED_RECT rc; UINT pitch; UINT adapter = D3DADAPTER_DEFAULT; // init D3D and get screen size d3d = Direct3DCreate9(D3D_SDK_VERSION); if(!d3d){ DKERROR("DKVncServer::DrawBuffer(): Direct3DCreate9() failed\n"); return; } HRCHECK(d3d->GetAdapterDisplayMode(adapter, &mode)); parameters.Windowed = TRUE; parameters.BackBufferCount = 1; parameters.BackBufferHeight = mode.Height; parameters.BackBufferWidth = mode.Width; parameters.SwapEffect = D3DSWAPEFFECT_DISCARD; parameters.hDeviceWindow = NULL; // create device & capture surface //HRCHECK(d3d->CreateDevice(adapter, D3DDEVTYPE_HAL, NULL, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &parameters, &device)); HRCHECK(d3d->CreateDevice(adapter, D3DDEVTYPE_REF, NULL, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &parameters, &device)); HRCHECK(device->CreateOffscreenPlainSurface(mode.Width, mode.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &surface, nullptr)); // compute the required buffer size HRCHECK(surface->LockRect(&rc, NULL, 0)); pitch = rc.Pitch; HRCHECK(surface->UnlockRect()); HRCHECK(device->GetFrontBufferData(0, surface)); // copy it into our buffers HRCHECK(surface->LockRect(&rc, NULL, 0)); CopyMemory(rfbScreen->frameBuffer, rc.pBits, mode.Height * mode.Width * bpp); HRCHECK(surface->UnlockRect()); rfbMarkRectAsModified(rfbScreen, 0, 0, rfbScreen->width, rfbScreen->height); RELEASE(surface); RELEASE(device); RELEASE(d3d); } //Capture Desktop with GDI if(capture == "GDI"){ //https://pastebin.com/r3CZpWDs HWND desktop = GetDesktopWindow(); BITMAPINFO info = {0}; info.bmiHeader.biSize = sizeof(info.bmiHeader); info.bmiHeader.biWidth = rfbScreen->width; info.bmiHeader.biHeight = rfbScreen->height* -1; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = 32; info.bmiHeader.biCompression = BI_RGB; BYTE* pbBitmap; HDC src_dc = GetDC(desktop); HDC buffer_dc = CreateCompatibleDC(src_dc); HBITMAP dest_dc = CreateDIBSection(buffer_dc, &info, DIB_RGB_COLORS, (void**)&pbBitmap, NULL, 0); BITMAP bmp; SelectObject(buffer_dc, dest_dc); GetObject(dest_dc, sizeof(BITMAP), &bmp); int res = BitBlt(buffer_dc, 0, 0, rfbScreen->width, rfbScreen->height, src_dc, 0, 0, SRCCOPY); int go = GetObject(dest_dc, sizeof(BITMAP), &bmp); //Invert size_t n = rfbScreen->width * rfbScreen->height * bpp; int* buffer = (int*)malloc(n); int* dest = (int*)rfbScreen->frameBuffer; int* src = ((int*)bmp.bmBits); while(src != ((int*)bmp.bmBits) + (rfbScreen->width * rfbScreen->height - 1)){ char* c_dest = (char*)dest; char* c_src = (char*)src; c_dest[0] = c_src[0]; c_dest[1] = c_src[1]; c_dest[2] = c_src[2]; c_dest[3] = 0; src++; dest++; } rfbMarkRectAsModified(rfbScreen, 0, 0, rfbScreen->width, rfbScreen->height); ReleaseDC(desktop, src_dc); DeleteDC(src_dc); DeleteDC(buffer_dc); DeleteObject(dest_dc); delete buffer; } #endif #ifdef MAC image_ref = CGDisplayCreateImage(CGMainDisplayID()); provider = CGImageGetDataProvider(image_ref); dataref = CGDataProviderCopyData(provider); size_t width, height; width = CGImageGetWidth(image_ref); height = CGImageGetHeight(image_ref); size_t bpp = CGImageGetBitsPerPixel(image_ref) / 8; memcpy(rfbScreen->frameBuffer, CFDataGetBytePtr(dataref), width * height * bpp); rfbMarkRectAsModified(rfbScreen, 0 ,0, rfbScreen->width, rfbScreen->height); //CFRelease(dataref); //CGImageRelease(image_ref); #endif #ifdef LINUX image = XGetImage(disp, root, 0, 0, rfbScreen->width, rfbScreen->height, AllPlanes, ZPixmap); int w,h; for(h=0;h<rfbScreen->height;++h) { for(w=0;w<rfbScreen->width;++w) { unsigned long xpixel = XGetPixel(image, w, h); unsigned int red = (xpixel & 0x00ff0000) >> 16; unsigned int green = (xpixel & 0x0000ff00) >> 8; unsigned int blue = (xpixel & 0x000000ff); rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+0]=blue; rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+1]=green; rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+2]=red; } rfbScreen->frameBuffer[h*rfbScreen->width*bpp+0]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+1]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+2]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+3]=0xff; } rfbMarkRectAsModified(rfbScreen,0,0,rfbScreen->width,rfbScreen->height); //XDestroyImage(image); //image = NULL; #endif /* //Paint framebuffer solid white int w, h; for(h=0;h<rfbScreen->height;++h) { for(w=0;w<rfbScreen->width;++w) { rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+0]=0xff; rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+1]=0xff; rfbScreen->frameBuffer[(h*rfbScreen->width+w)*bpp+2]=0xff; } rfbScreen->frameBuffer[h*rfbScreen->width*bpp+0]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+1]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+2]=0xff; rfbScreen->frameBuffer[h*rfbScreen->width*bpp+3]=0xff; } rfbMarkRectAsModified(rfbScreen, 0, 0, rfbScreen->width, rfbScreen->height); */ //rfbFillRect(rfbScreen, 0, 0, rfbScreen->width, rfbScreen->height, 0xffffff); //rfbDrawString(rfbScreen, &radonFont, 10, 10, "DKVncServer", 0xffffff); } //////////////////////////////////////////////////////////////////////////////// void DKVncServer::newframebuffer(rfbScreenInfoPtr screen, int width, int height) { DKDEBUGFUNC(screen, width, height); char *oldfb, *newfb; oldfb = (char*)screen->frameBuffer; newfb = (char*)malloc(width * height * bpp); rfbNewFramebuffer(screen, (char*)newfb, width, height, 5, 3, bpp); free(oldfb); } /////////////////////////////////////////////////////////////////////////// void DKVncServer::mouseevent(int buttonMask, int x, int y, rfbClientPtr cl) { DKDEBUGFUNC(buttonMask, x, y, cl); ClientData* cd = (ClientData*)cl->clientData; if(same(cd->ipaddress,"127.0.0.1")){ return; } DKUtil::SetMousePos(x, y); if(buttonMask && !cd->buttonMask){ cd->buttonMask = buttonMask; if(cd->buttonMask == 1){ DKUtil::LeftPress(); } if(cd->buttonMask == 2){ DKUtil::MiddlePress(); } if(cd->buttonMask == 4){ DKUtil::RightPress(); } if(cd->buttonMask == 8){ DKUtil::WheelUp(); } if(cd->buttonMask == 16){ DKUtil::WheelDown(); } } if(!buttonMask && cd->buttonMask){ if(cd->buttonMask == 1){ DKUtil::LeftRelease(); } if(cd->buttonMask == 2){ DKUtil::MiddleRelease(); } if(cd->buttonMask == 4){ DKUtil::RightRelease(); } cd->buttonMask = 0; } rfbDefaultPtrAddEvent(buttonMask, x, y, cl); } //////////////////////////////////////////////////////////////////////// void DKVncServer::keyevent(rfbBool down, rfbKeySym key, rfbClientPtr cl) { DKDEBUGFUNC(down, key, cl); int k = key; switch(key){ case 65307: k = 27; break; //ESC case 65470: k = 112; break; //F1 case 65471: k = 113; break; //F2 case 65472: k = 114; break; //F3 case 65473: k = 115; break; //F4 case 65474: k = 116; break; //F5 case 65475: k = 117; break; //F6 case 65476: k = 118; break; //F7 case 65477: k = 119; break; //F8 case 65478: k = 120; break; //F9 case 65479: k = 121; break; //F10 case 65480: k = 122; break; //F11 case 65481: k = 123; break; //F12 //case : k = 0; break; //Print Screen //case : k = 0; break; //Scroll Lock case 65299: k = 19; break; //Pause case 96: k = 192; break; //` case 49: k = 49; break; //1 case 50: k = 50; break; //2 case 51: k = 51; break; //3 case 52: k = 52; break; //4 case 53: k = 53; break; //5 case 54: k = 54; break; //6 case 55: k = 55; break; //7 case 56: k = 56; break; //8 case 57: k = 57; break; //9 case 48: k = 48; break; //0 case 45: k = 189; break; //- case 61: k = 187; break; //= case 65288: k = 8; break; //Backspace case 65289: k = 9; break; //Tab case 113: k = 81; break; //q case 119: k = 87; break; //w case 101: k = 69; break; //e case 114: k = 82; break; //r case 116: k = 84; break; //t case 121: k = 89; break; //y case 117: k = 85; break; //u case 105: k = 73; break; //i case 111: k = 79; break; //o case 112: k = 80; break; //p case 91: k = 219; break; //[ case 93: k = 221; break; //] case 92: k = 220; break; //\ //case : k = 20; break; //CapsLock case 97: k = 65; break; //a case 115: k = 83; break; //s case 100: k = 68; break; //d case 102: k = 70; break; //f case 103: k = 71; break; //g case 104: k = 72; break; //h case 106: k = 74; break; //j case 107: k = 75; break; //k case 108: k = 76; break; //l case 59: k = 186; break; //; case 39: k = 222; break; //' case 65293: k = 13; break; //Enter case 65505: k = 16; break; //LShift case 122: k = 90; break; //z case 120: k = 88; break; //x case 99: k = 67; break; //c case 118: k = 86; break; //v case 98: k = 66; break; //b case 110: k = 78; break; //n case 109: k = 77; break; //m case 44: k = 188; break; //, case 46: k = 190; break; //. case 47: k = 191; break; /// //case 65505: k = 16; break; //RShift case 65507: k = 17; break; //LCtrl //case : k = 91; break; //LWinKey case 65513: k = 18; break; //LAlt case 32: k = 32; break; //Space case 65514: k = 18; break; //RAlt //case : k = 0; break; //RWinKey case 65383: k = 93; break; //Menu case 65508: k = 17; break; //RCtrl /* case 126: k = 0; break; //~ case 33: k = 0; break; //! case 64: k = 0; break; //@ case 35: k = 0; break; //# case 36: k = 0; break; //$ case 37: k = 0; break; //% case 94: k = 0; break; //^ case 38: k = 0; break; //& case 42: k = 0; break; //* case 40: k = 0; break; //( case 41: k = 0; break; //) case 95: k = 0; break; //_ case 43: k = 0; break; //+ case 81: k = 0; break; //Q case 87: k = 0; break; //W case 69: k = 0; break; //E case 82: k = 0; break; //R case 84: k = 0; break; //T case 89: k = 0; break; //Y case 85: k = 0; break; //U case 73: k = 0; break; //I case 79: k = 0; break; //O case 80: k = 0; break; //P case 123: k = 0; break; //{ case 125: k = 0; break; //} case 124: k = 0; break; //| case 65: k = 0; break; //A case 83: k = 0; break; //S case 68: k = 0; break; //D case 70: k = 0; break; //F case 71: k = 0; break; //G case 72: k = 0; break; //H case 74: k = 0; break; //J case 75: k = 0; break; //K case 76: k = 0; break; //L case 58: k = 0; break; //: case 34: k = 0; break; //" case 90: k = 0; break; //Z case 88: k = 0; break; //X case 67: k = 0; break; //C case 86: k = 0; break; //V case 66: k = 0; break; //B case 78: k = 0; break; //N case 77: k = 0; break; //M case 60: k = 0; break; //< case 62: k = 0; break; //> case 63: k = 0; break; //? */ case 65379: k = 45; break; //Insert case 65360: k = 36; break; //Home case 65365: k = 33; break; //PageUp case 65535: k = 46; break; //Delete case 65367: k = 35; break; //End case 65366: k = 34; break; //PageDown case 65362: k = 38; break; //Up case 65361: k = 37; break; //Left case 65364: k = 40; break; //Down case 65363: k = 39; break; //Right //case : k = 144; break; //NumLock case 65455: k = 111; break; /// case 65450: k = 106; break; //* case 65453: k = 109; break; //- case 65463: k = 103; break; //7 case 65464: k = 104; break; //8 case 65465: k = 105; break; //9 case 65451: k = 107; break; //+ case 65460: k = 100; break; //4 case 65461: k = 101; break; //5 case 65462: k = 102; break; //6 case 65457: k = 97; break; //1 case 65458: k = 98; break; //2 case 65459 : k = 99; break; //3 case 65421: k = 13; break; //Enter case 65456: k = 96; break; //0 case 65454: k = 110; break; //. default: break; } if(down){ DKUtil::PressKey(k); } else { DKUtil::ReleaseKey(k); } }
31.140496
127
0.592144
aquawicket
db9c4f2fce4a0a1d924eba6503e048de6a913d5e
275
cpp
C++
code/NodeOperationOR.cpp
Zer0-R/DoubleAntiAnalysis
39658230b18b2cb8c116230466a5d0a17eb5f5a2
[ "Apache-2.0" ]
1
2020-02-19T18:11:28.000Z
2020-02-19T18:11:28.000Z
code/NodeOperationOR.cpp
Zer0-R/DoubleAntiAnalysis
39658230b18b2cb8c116230466a5d0a17eb5f5a2
[ "Apache-2.0" ]
null
null
null
code/NodeOperationOR.cpp
Zer0-R/DoubleAntiAnalysis
39658230b18b2cb8c116230466a5d0a17eb5f5a2
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "NodeOperationOR.h" NodeOperationOR::NodeOperationOR(Node *nodeLeft, Node *nodeRight) : NodeOperation(nodeLeft, nodeRight) {} const bool NodeOperationOR::isActivate() const { return getNodeLeft()->isActivate() || getNodeRight()->isActivate(); }
27.5
105
0.752727
Zer0-R
db9ca9b7134ea0698595fde98c0b937fb7387a85
5,167
cpp
C++
examples/pppbayestree/gpstk/DCBDataReader.cpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
104
2019-06-23T14:45:20.000Z
2022-03-20T12:45:29.000Z
examples/pppbayestree/gpstk/DCBDataReader.cpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
2
2019-06-28T08:23:23.000Z
2019-07-17T02:37:08.000Z
examples/pppbayestree/gpstk/DCBDataReader.cpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
28
2019-06-23T14:45:19.000Z
2022-03-20T12:45:24.000Z
#pragma ident "$Id$" /** * @file DCBDataReader.cpp * Class to read DCB data from CODE. */ //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Wei Yan - Chinese Academy of Sciences 2009, 2010 // //============================================================================ #include "DCBDataReader.hpp" using namespace std; namespace gpstk { // Method to store load ocean tide harmonics data in this class' // data map void DCBDataReader::loadData() throw( FFStreamError, gpstk::StringUtils::StringException ) { try { allDCB.satDCB.clear(); allDCB.gpsDCB.clear(); allDCB.glonassDCB.clear(); // a buffer string line; // read first line formattedGetLine(line, true); // Let's skip 6 lines for(int i=0; i<6; i++) formattedGetLine(line, true); // Now, let's read data while(1) { formattedGetLine(line, true); if(line.length() < 46) continue; string sysFlag = line.substr(0,1); int satPRN = StringUtils::asInt(line.substr(1,2)); string station = StringUtils::strip(line.substr(6,4)); double dcbVal = StringUtils::asDouble(line.substr(26,9)); double dcbRMS = StringUtils::asDouble(line.substr(38,9)); #pragma unused(dcbRMS) if(station.length() < 4) // this is satellite DCB data { SatID sat; if(sysFlag == "G") { sat = SatID(satPRN,SatID::systemGPS); } else if(sysFlag == "R") { sat = SatID(satPRN,SatID::systemGlonass); } else { // Unexpected and we do nothing here } allDCB.satDCB[sat] = dcbVal; } else // this is receiver DCB data { if(sysFlag == "G") { allDCB.gpsDCB[station] = dcbVal; } else if(sysFlag == "R") { allDCB.glonassDCB[station] = dcbVal; } else { // Unexpected and we do nothing here } } } // End of 'while(1)' } // End of try block catch (EndOfFile& e) { // We should close this data stream before returning (*this).close(); return; } catch (...) { // We should close this data stream before returning (*this).close(); return; } } // End of 'DCBDataReader::loadData()' // Method to open AND load DCB data file. void DCBDataReader::open(const char* fn) { // We need to be sure current data stream is closed (*this).close(); // Open data stream FFTextStream::open(fn, std::ios::in); loadData(); return; } // End of method 'DCBDataReader::open()' // Method to open AND load DCB data file. It doesn't // clear data previously loaded. void DCBDataReader::open(const string& fn) { // We need to be sure current data stream is closed (*this).close(); // Open data stream FFTextStream::open(fn.c_str(), std::ios::in); loadData(); return; } // End of method 'DCBDataReader::open()' // return P1-P2 or P1-C1 depend what you have loaded double DCBDataReader::getDCB(const SatID& sat) { return allDCB.satDCB[sat]; } // Get DCB data of a satellite // return P1-P2 or P1-C1 depend what you have loaded double DCBDataReader::getDCB(const int& prn, const SatID::SatelliteSystem& system) { SatID sat(prn,system); return allDCB.satDCB[sat]; } // Get DCB data of aReceiver // it return P1-P2 double DCBDataReader::getDCB(const string& station, const SatID::SatelliteSystem& system) { if(system == SatID::systemGPS) { return allDCB.gpsDCB[station]; } else if(system == SatID::systemGlonass) { return allDCB.glonassDCB[station]; } else { // Unexpected and return 0 return 0.0; } } // End of 'double DCBDataReader::getDCB(const string& station...' } // End of namespace gpstk
23.81106
78
0.539772
shaolinbit
dba021780d4f3c05f2edff1364a3c99ff1d0ffab
2,808
cpp
C++
dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
6
2016-11-18T10:26:46.000Z
2021-11-01T12:29:05.000Z
dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
5
2020-07-15T11:30:49.000Z
2020-12-11T19:13:46.000Z
dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
7
2019-05-17T07:14:40.000Z
2021-05-24T07:25:26.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., 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. * */ // CLASS HEADER #include <dali/internal/vector-animation/common/vector-animation-renderer-impl.h> // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> // INTERNAL INCLUDES namespace Dali { namespace Internal { namespace Adaptor { namespace // unnamed namespace { // Type Registration Dali::BaseHandle Create() { return Dali::BaseHandle(); } Dali::TypeRegistration type(typeid(Dali::VectorAnimationRenderer), typeid(Dali::BaseHandle), Create); } // unnamed namespace VectorAnimationRendererPtr VectorAnimationRenderer::New() { VectorAnimationRendererPtr renderer = new VectorAnimationRenderer(); return renderer; } VectorAnimationRenderer::VectorAnimationRenderer() : mPlugin(std::string()) { } VectorAnimationRenderer::~VectorAnimationRenderer() { } void VectorAnimationRenderer::Finalize() { mPlugin.Finalize(); } bool VectorAnimationRenderer::Load(const std::string& url) { return mPlugin.Load(url); } void VectorAnimationRenderer::SetRenderer(Dali::Renderer renderer) { mPlugin.SetRenderer(renderer); } void VectorAnimationRenderer::SetSize(uint32_t width, uint32_t height) { mPlugin.SetSize(width, height); } bool VectorAnimationRenderer::Render(uint32_t frameNumber) { return mPlugin.Render(frameNumber); } uint32_t VectorAnimationRenderer::GetTotalFrameNumber() const { return mPlugin.GetTotalFrameNumber(); } float VectorAnimationRenderer::GetFrameRate() const { return mPlugin.GetFrameRate(); } void VectorAnimationRenderer::GetDefaultSize(uint32_t& width, uint32_t& height) const { mPlugin.GetDefaultSize(width, height); } void VectorAnimationRenderer::GetLayerInfo(Property::Map& map) const { mPlugin.GetLayerInfo(map); } bool VectorAnimationRenderer::GetMarkerInfo(const std::string& marker, uint32_t& startFrame, uint32_t& endFrame) const { return mPlugin.GetMarkerInfo(marker, startFrame, endFrame); } void VectorAnimationRenderer::IgnoreRenderedFrame() { mPlugin.IgnoreRenderedFrame(); } Dali::VectorAnimationRenderer::UploadCompletedSignalType& VectorAnimationRenderer::UploadCompletedSignal() { return mPlugin.UploadCompletedSignal(); } } // namespace Adaptor } // namespace Internal } // namespace Dali
22.645161
118
0.773504
dalihub
dba8924e50bc9971114867553c0afe8d0663484b
131
cpp
C++
test/llvm_test_code/TaintConfig/AttrConfig/data_member_01.cpp
janniclas/phasar
324302ae96795e6f0a065c14d4f7756b1addc2a4
[ "MIT" ]
581
2018-06-10T10:37:55.000Z
2022-03-30T14:56:53.000Z
test/llvm_test_code/TaintConfig/AttrConfig/data_member_01.cpp
meret-boe/phasar
2b394d5611b107e4fd3d8eec37f26abca8ef1e9a
[ "MIT" ]
172
2018-06-13T12:33:26.000Z
2022-03-26T07:21:41.000Z
test/llvm_test_code/TaintConfig/AttrConfig/data_member_01.cpp
meret-boe/phasar
2b394d5611b107e4fd3d8eec37f26abca8ef1e9a
[ "MIT" ]
137
2018-06-10T10:31:14.000Z
2022-03-06T11:53:56.000Z
struct X { [[clang::annotate("psr.source")]] int A = 13; int B = 0; }; int main() { X V; V.B = 42; return V.A + V.B; }
10.916667
47
0.480916
janniclas
dbae64c24dd3ae2d9b9678e4bb49d12d92462813
8,107
hpp
C++
include/HighLevel.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
null
null
null
include/HighLevel.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
1
2021-07-29T15:13:42.000Z
2021-07-29T15:13:42.000Z
include/HighLevel.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 Arthur Queffelec * * 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. */ #pragma once #include <list> #include <memory> #include <set> #include <map> #include <stack> #include <vector> #include <utility> #include <CTNOrderingStrategy.hpp> #include <ConflictSelectionStrategy.hpp> #include <ConstraintTreeNode.hpp> #include <Instance.hpp> #include <LowLevel.hpp> #include <Objective.hpp> #include <Solver.hpp> #include <boost/heap/fibonacci_heap.hpp> namespace decoupled { struct BypassException : public std::exception { std::shared_ptr<ConstraintTreeNode> child; }; template <class GraphMove, class GraphComm> class HighLevel : public Solver<GraphMove, GraphComm> { private: const CTNOrderingStrategy& ordering_strategy_; const ConflictSelectionStrategy& selection_strategy_; std::unique_ptr<LowLevel<GraphMove, GraphComm>> low_level_; using priority_queue = boost::heap::fibonacci_heap<std::shared_ptr<ConstraintTreeNode>, boost::heap::compare<CTNOrderingStrategy>>; priority_queue open_; virtual void Split(priority_queue*, std::shared_ptr<ConstraintTreeNode>, uint64_t) = 0; // TODO(arqueffe): Add support for edge collision. // TODO(arqueffe): Implement partial conflict computation void ComputeCollision(std::shared_ptr<ConstraintTreeNode> ctn, uint64_t time) { std::shared_ptr<CollisionConflict> conflict = std::make_shared<CollisionConflict>(); std::vector<bool> agent_treated = std::vector<bool>(this->instance_.nb_agents(), false); for (Agent a = 0; a < static_cast<Agent>(this->instance_.nb_agents()); a++) { if (std::find(agent_treated.begin(), agent_treated.end(), a) == agent_treated.end()) { std::set<Agent> cluster; cluster.insert(a); Node aPos = ctn->get_path(a)->GetAtTimeOrLast(time); for (Agent b = a + 1; b < static_cast<Agent>(this->instance_.nb_agents()); b++) { if (std::find(agent_treated.begin(), agent_treated.end(), b) == agent_treated.end()) { Node bPos = ctn->get_path(b)->GetAtTimeOrLast(time); if (aPos == bPos) cluster.insert(b); } } if (cluster.size() > 1) conflict->PushBack(cluster); } } if (conflict->size() == 0) ctn->remove_conflict(time); else ctn->set_conflict(time, conflict); } void ComputeDisconnection(std::shared_ptr<ConstraintTreeNode> ctn, uint64_t time) { std::shared_ptr<DisconnectionConflict> conflict = std::make_shared<DisconnectionConflict>(); std::vector<bool> agent_treated = std::vector<bool>(this->instance_.nb_agents(), false); std::stack<Agent> agent_stack; int agent_count = 0; std::vector<bool>::iterator it; while ((it = find(agent_treated.begin(), agent_treated.end(), false)) != agent_treated.end()) { agent_stack.push(distance(agent_treated.begin(), it)); conflict->PushBack(std::set<Agent>()); std::set<Agent>& cluster = conflict->back(); while (!agent_stack.empty()) { Agent a = agent_stack.top(); cluster.insert(a); agent_stack.pop(); if (agent_treated[a]) continue; agent_treated[a] = true; agent_count++; Node aPos = ctn->get_path(a)->GetAtTimeOrLast(time); for (Agent b = 0; b < static_cast<Agent>(this->instance_.nb_agents()); ++b) { if (a != b && !agent_treated[b]) { Node bPos = ctn->get_path(b)->GetAtTimeOrLast(b); const std::set<Node>& neighbors = this->instance_.graph().communication().get_neighbors(aPos); if (neighbors.find(bPos) != neighbors.end()) { agent_stack.push(b); } } } } } if (conflict->size() == 1) ctn->remove_conflict(time); else ctn->set_conflict(time, conflict); } void RecomputeConflicts(std::shared_ptr<ConstraintTreeNode> ctn, Agent agt) { /** WARNING: This function assumes that * - ctn.get_path(a) != ctn.get_parent().get_path(a) * - ctn.get_path(a).size() >= ctn.get_parent().get_path(a).size() */ auto prev_path = ctn->get_parent()->get_path(agt); auto new_path = ctn->get_path(agt); for (uint64_t i = 0; i < new_path->size(); i++) { if ((*prev_path)[i] == (*new_path)[i]) continue; ComputeCollision(ctn, i); ComputeDisconnection(ctn, i); } } void ComputeConflicts(std::shared_ptr<ConstraintTreeNode> root) { /** WARNING: This function assumes that * - root has no parent */ auto& exec = root->get_execution(); uint64_t max = 0; for (Agent i = 0; i < static_cast<Agent>(this->instance_.nb_agents()); i++) { if (max < exec.get_path(i)->size()) max = exec.get_path(i)->size(); } for (uint64_t i = 0; i < max; i++) { ComputeCollision(root, i); // ComputeDisconnection(root, i); } } protected: void CreateChild(priority_queue* children, std::shared_ptr<ConstraintTreeNode> parent, Agent agt, const Constraint& c) { std::map<uint64_t, std::list<Constraint>> agt_cons = parent->get_constraints(agt); Path new_path = low_level_->ComputeConstrainedPath(agt_cons, c, this->instance_.start()[agt], this->instance_.goal()[agt]); if (new_path.size() == 0) return; auto new_path_ptr = std::make_shared<const Path>(new_path); auto child = std::make_shared<ConstraintTreeNode>(parent, c, agt, new_path_ptr); RecomputeConflicts(child, agt); #ifdef BYPASS // TODO(arqueffe): Count conflicts size depending on the type if (child->get_path(agt)->size() == parent->get_path(agt)->size() && child->get_conflicts().size() < parent->get_conflicts().size()) { throw BypassException(child); } #endif children->push(child); } public: HighLevel(const Instance<GraphMove, GraphComm>& instance, const Objective& objective, const CTNOrderingStrategy& ordering_strategy, const ConflictSelectionStrategy& selection_strategy, std::unique_ptr<LowLevel<GraphMove, GraphComm>> low_level) : Solver<GraphMove, GraphComm>(instance, objective), ordering_strategy_(ordering_strategy), selection_strategy_(selection_strategy), low_level_(std::move(low_level)), open_(ordering_strategy) { Execution start_exec; for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) { Path p = low_level_->ComputeShortestPath(this->instance_.start()[agt], this->instance_.goal()[agt]); start_exec.PushBack(std::make_shared<const Path>(p)); } auto start_node = std::make_shared<ConstraintTreeNode>(start_exec); // ComputeConflicts(start_node); open_.push(start_node); } bool StepCompute() override { std::shared_ptr<ConstraintTreeNode> top = open_.top(); open_.pop(); if (top->get_conflicts().size() == 0) { this->execution_ = top->get_execution(); return true; } uint64_t conflict_time = selection_strategy_.SelectConflict(top->get_conflicts()); // Using fibo for storage of children as merge is O(1) priority_queue children(ordering_strategy_); try { Split(&children, top, conflict_time); } catch (const BypassException&) { // TODO(arqueffe): Implement Bypass } open_.merge(children); return false; } }; } // namespace decoupled
36.518018
116
0.648082
arqueffe
dbb8d64755dfb1e0b507cc6257c92bc170bdec80
3,334
cc
C++
src/mmutil_velocity.cc
causalpathlab/mmutilR
292a70f89336c7563b2fa9f1f62e59d219739e24
[ "MIT" ]
1
2021-07-23T07:49:10.000Z
2021-07-23T07:49:10.000Z
src/mmutil_velocity.cc
YPARK/mmutilR
ede9948fe9a0124b9f417d010b7a376dff64ebb9
[ "MIT" ]
2
2022-01-18T22:07:44.000Z
2022-03-10T16:58:34.000Z
src/mmutil_velocity.cc
YPARK/mmutilR
ede9948fe9a0124b9f417d010b7a376dff64ebb9
[ "MIT" ]
null
null
null
#include "mmutil_velocity.hh" namespace mmutil { namespace velocity { //////////////////////////////////////// // implementation for the data loader // //////////////////////////////////////// int data_loader_t::read(const Index j) { using namespace mmutil::bgzf; target_col = j; spliced_reader.data.setZero(); unspliced_reader.data.setZero(); set_mem_loc(spliced_idx_tab); CHK_RET_(visit_bgzf_block(spliced_file, lb, ub, spliced_reader), "unable to read spliced mtx file [" << j << "]"); set_mem_loc(unspliced_idx_tab); CHK_RET_(visit_bgzf_block(unspliced_file, lb, ub, unspliced_reader), "unable to read unspliced mtx file [" << j << "]"); return EXIT_SUCCESS; } const Mat & data_loader_t::spliced() const { return spliced_reader.data; } const Mat & data_loader_t::unspliced() const { return unspliced_reader.data; } void data_loader_t::set_mem_loc(const std::vector<Index> &_idx_tab) { lb = _idx_tab[target_col]; ub = 0; if ((target_col + 1) < _idx_tab.size()) ub = _idx_tab[target_col + 1]; }; ///////////////////////////////////////////// // implementations for the aggregated stat // ///////////////////////////////////////////// void aggregated_delta_model_t::update_phi_stat_bulk(const SpMat &uu, const SpMat &ss, const Mat &cc) { ASSERT(1 == 0, "Not implemented"); // for (Index j = 0; j < uu.cols(); ++j) { // phi_new_j = uu.col(j) + ss.col(j); // phi_old_j = uu.col(j) + ss.col(j); // PhiC += (phi_new_j.binaryExpr(delta * cc.col(j), update_phi_op) - // phi_old_j.binaryExpr(delta_old * cc.col(j), update_phi_op)) // * // cc.col(j).transpose(); // } } void aggregated_delta_model_t::add_stat_bulk(const SpMat &uu, const SpMat &ss, const Mat &cc) { ASSERT(1 == 0, "Not implemented"); // ASSERT(uu.cols() == ss.cols(), "cols(U) != cols(S)"); // UC += ((uu * cc.transpose()).array() + eps).matrix(); // for (Index j = 0; j < uu.cols(); ++j) { // phi_new_j = uu.col(j) + ss.col(j); // PhiC += (phi_new_j.binaryExpr(delta * cc.col(j), update_phi_op)) * // cc.col(j).transpose(); // } // n += uu.cols(); } Index aggregated_delta_model_t::nsample() const { return n; } Mat aggregated_delta_model_t::get_delta() const { return delta; } Mat aggregated_delta_model_t::get_sd_delta() const { return UC.binaryExpr(PhiC, rate_sd_op); } Mat aggregated_delta_model_t::get_ln_delta() const { return UC.binaryExpr(PhiC, rate_ln_op); } Mat aggregated_delta_model_t::get_sd_ln_delta() const { return UC.unaryExpr(rate_sd_ln_op); } void aggregated_delta_model_t::update_delta_stat() { delta_old = delta; delta = UC.binaryExpr(PhiC, update_delta_op); } Scalar aggregated_delta_model_t::update_diff() { Scalar denom = delta_old.unaryExpr(log1p_op).unaryExpr(abs_op).mean(); Scalar diff = (delta_old.unaryExpr(log1p_op) - delta.unaryExpr(log1p_op)) .unaryExpr(abs_op) .mean(); return diff / (denom + 1e-8); } }} // namespace mmutil::velocity
24.880597
79
0.568386
causalpathlab
dbbaf6a7efe85bd61fdaa9c52303344ed15fb96e
19,753
cpp
C++
maya/AbcExport/MayaMeshWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
maya/AbcExport/MayaMeshWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
maya/AbcExport/MayaMeshWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
//-***************************************************************************** // // Copyright (c) 2009-2011, // Sony Pictures Imageworks Inc. and // Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. // // 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 Sony Pictures Imageworks, nor // Industrial Light & Magic, nor the names of their 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 "MayaMeshWriter.h" #include "MayaUtility.h" // assumption is we don't support multiple uv sets as well as animated uvs void MayaMeshWriter::getUVs(std::vector<float> & uvs, std::vector<Alembic::Util::uint32_t> & indices) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } MString uvSetName = lMesh.currentUVSetName(&status); if (status == MS::kSuccess && uvSetName != MString("")) { MFloatArray uArray, vArray; status = lMesh.getUVs(uArray, vArray, &uvSetName); // convert the raw uv list into vector uvsvec.clear(); if ( uArray.length() != vArray.length() ) { MString msg = "uv Set" + uvSetName + "uArray and vArray not the same length"; MGlobal::displayError(msg); return; } unsigned int len = uArray.length(); uvs.clear(); uvs.reserve(len); for (unsigned int i = 0; i < len; i++) { uvs.push_back(uArray[i]); uvs.push_back(1-vArray[i]); } MIntArray uvCounts, uvIds; status = lMesh.getAssignedUVs(uvCounts, uvIds, &uvSetName); indices.clear(); indices.reserve(uvIds.length()); unsigned int faceCount = uvCounts.length(); unsigned int uvIndex = 0; for (unsigned int f = 0; f < faceCount; f++) { len = uvCounts[f]; for (int i = len-1; i >= 0; i--) indices.push_back(uvIds[uvIndex+i]); uvIndex += len; } } } MayaMeshWriter::MayaMeshWriter(MDagPath & iDag, Alembic::Abc::OObject & iParent, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs) : mNoNormals(iArgs.noNormals), mWriteUVs(iArgs.writeUVs), mIsGeometryAnimated(false), mDagPath(iDag) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } // intermediate objects aren't translated MObject surface = iDag.node(); if (iTimeIndex != 0 && util::isAnimated(surface)) mIsGeometryAnimated = true; std::vector<float> uvs; std::vector<Alembic::Util::uint32_t> indices; MString name = lMesh.name(); if (iArgs.stripNamespace) { name = util::stripNamespaces(name); } // check to see if this poly has been tagged as a SubD MPlug plug = lMesh.findPlug("SubDivisionMesh"); if ( !plug.isNull() && plug.asBool() ) { Alembic::AbcGeom::OSubD obj(iParent, name.asChar(), iTimeIndex); mSubDSchema = obj.getSchema(); Alembic::AbcGeom::OV2fGeomParam::Sample uvSamp; if ( mWriteUVs ) { getUVs(uvs, indices); if (!uvs.empty()) { uvSamp.setScope( Alembic::AbcGeom::kFacevaryingScope ); uvSamp.setVals(Alembic::AbcGeom::V2fArraySample( (const Imath::V2f *) &uvs.front(), uvs.size() / 2)); if (!indices.empty()) { uvSamp.setIndices(Alembic::Abc::UInt32ArraySample( &indices.front(), indices.size())); } } } Alembic::Abc::OCompoundProperty cp; if (AttributesWriter::hasAnyAttr(lMesh, iArgs)) { cp = mSubDSchema.getArbGeomParams(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, obj, lMesh, iTimeIndex, iArgs)); writeSubD(uvSamp); } else { Alembic::AbcGeom::OPolyMesh obj(iParent, name.asChar(), iTimeIndex); mPolySchema = obj.getSchema(); Alembic::AbcGeom::OV2fGeomParam::Sample uvSamp; if ( mWriteUVs ) { getUVs(uvs, indices); if (!uvs.empty()) { uvSamp.setScope( Alembic::AbcGeom::kFacevaryingScope ); uvSamp.setVals(Alembic::AbcGeom::V2fArraySample( (const Imath::V2f *) &uvs.front(), uvs.size() / 2)); if (!indices.empty()) { uvSamp.setIndices(Alembic::Abc::UInt32ArraySample( &indices.front(), indices.size())); } } } Alembic::Abc::OCompoundProperty cp; if (AttributesWriter::hasAnyAttr(lMesh, iArgs)) { cp = mPolySchema.getArbGeomParams(); } // set the rest of the props and write to the writer node mAttrs = AttributesWriterPtr(new AttributesWriter(cp, obj, lMesh, iTimeIndex, iArgs)); writePoly(uvSamp); } // look for facesets std::size_t attrCount = lMesh.attributeCount(); for (std::size_t i = 0; i < attrCount; ++i) { MObject attr = lMesh.attribute(i); MFnAttribute mfnAttr(attr); MPlug plug = lMesh.findPlug(attr, true); // if it is not readable, then bail without any more checking if (!mfnAttr.isReadable() || plug.isNull()) continue; MString propName = plug.partialName(0, 0, 0, 0, 0, 1); std::string propStr = propName.asChar(); if (propStr.substr(0, 8) == "FACESET_") { MStatus status; MFnIntArrayData arr(plug.asMObject(), &status); // not the correct kind of data if (status != MS::kSuccess) continue; std::string faceSetName = propStr.substr(8); std::size_t numData = arr.length(); std::vector<Alembic::Util::int32_t> faceVals(numData); for (std::size_t j = 0; j < numData; ++j) { faceVals[j] = arr[j]; } bool isVisible = true; MString visName = "FACESETVIS_"; visName += faceSetName.c_str(); MPlug visPlug = lMesh.findPlug(visName, true); if (!visPlug.isNull()) { isVisible = visPlug.asBool(); } Alembic::AbcGeom::OFaceSet faceSet; if (mPolySchema) { faceSet = mPolySchema.createFaceSet(faceSetName); } else { faceSet = mSubDSchema.createFaceSet(faceSetName); } Alembic::AbcGeom::OFaceSetSchema::Sample samp; samp.setFaces(Alembic::Abc::Int32ArraySample(faceVals)); if (!isVisible) { Alembic::AbcGeom::OVisibilityProperty visProp = Alembic::AbcGeom::CreateVisibilityProperty( faceSet, 0 ); Alembic::Abc::int8_t visVal = 0; visProp.set(visVal); } faceSet.getSchema().set(samp); } } } bool MayaMeshWriter::isSubD() { return mSubDSchema.valid(); } unsigned int MayaMeshWriter::getNumCVs() { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } return lMesh.numVertices(); } unsigned int MayaMeshWriter::getNumFaces() { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } return lMesh.numPolygons(); } void MayaMeshWriter::getPolyNormals(std::vector<float> & oNormals) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } // no normals bail early if (mNoNormals) { return; } MPlug plug = lMesh.findPlug("noNormals", true, &status); if (status == MS::kSuccess && plug.asBool() == true) { return; } // we need to check the locked state of the normals else if ( status != MS::kSuccess ) { bool userSetNormals = false; // go through all per face-vertex normals and verify if any of them // has been tweaked by users unsigned int numFaces = lMesh.numPolygons(); for (unsigned int faceIndex = 0; faceIndex < numFaces; faceIndex++) { MIntArray normals; lMesh.getFaceNormalIds(faceIndex, normals); unsigned int numNormals = normals.length(); for (unsigned int n = 0; n < numNormals; n++) { if (lMesh.isNormalLocked(normals[n])) { userSetNormals = true; break; } } } // we looped over all the normals and they were all calculated by Maya // so we won't write any of them out if (!userSetNormals) { return; } } bool flipNormals = false; plug = lMesh.findPlug("flipNormals", true, &status); if ( status == MS::kSuccess ) flipNormals = plug.asBool(); // get the per vertex per face normals (aka vertex) unsigned int numFaces = lMesh.numPolygons(); for (size_t faceIndex = 0; faceIndex < numFaces; faceIndex++ ) { MIntArray vertexList; lMesh.getPolygonVertices(faceIndex, vertexList); // re-pack the order of normals in this vector before writing into prop // so that Renderman can also use it unsigned int numVertices = vertexList.length(); for ( int v = numVertices-1; v >=0; v-- ) { unsigned int vertexIndex = vertexList[v]; MVector normal; lMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal); if (flipNormals) normal = -normal; oNormals.push_back(static_cast<float>(normal[0])); oNormals.push_back(static_cast<float>(normal[1])); oNormals.push_back(static_cast<float>(normal[2])); } } } void MayaMeshWriter::write() { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } Alembic::AbcGeom::OV2fGeomParam::Sample uvSamp; std::vector<float> uvs; std::vector<Alembic::Util::uint32_t> indices; if ( mWriteUVs ) { getUVs(uvs, indices); if (!uvs.empty()) { uvSamp.setScope( Alembic::AbcGeom::kFacevaryingScope ); uvSamp.setVals(Alembic::AbcGeom::V2fArraySample( (const Imath::V2f *) &uvs.front(), uvs.size() / 2)); if (!indices.empty()) { uvSamp.setIndices(Alembic::Abc::UInt32ArraySample( &indices.front(), indices.size())); } } } std::vector<float> points; std::vector<Alembic::Util::int32_t> facePoints; std::vector<Alembic::Util::int32_t> faceList; if (mPolySchema.valid()) { writePoly(uvSamp); } else if (mSubDSchema.valid()) { writeSubD(uvSamp); } } bool MayaMeshWriter::isAnimated() const { return mIsGeometryAnimated; } void MayaMeshWriter::writePoly( const Alembic::AbcGeom::OV2fGeomParam::Sample & iUVs) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } std::vector<float> points; std::vector<Alembic::Util::int32_t> facePoints; std::vector<Alembic::Util::int32_t> pointCounts; fillTopology(points, facePoints, pointCounts); Alembic::AbcGeom::ON3fGeomParam::Sample normalsSamp; std::vector<float> normals; getPolyNormals(normals); if (!normals.empty()) { normalsSamp.setScope( Alembic::AbcGeom::kFacevaryingScope ); normalsSamp.setVals(Alembic::AbcGeom::N3fArraySample( (const Imath::V3f *) &normals.front(), normals.size() / 3)); } Alembic::AbcGeom::OPolyMeshSchema::Sample samp( Alembic::Abc::V3fArraySample((const Imath::V3f *)&points.front(), points.size() / 3), Alembic::Abc::Int32ArraySample(facePoints), Alembic::Abc::Int32ArraySample(pointCounts), iUVs, normalsSamp); // if this mesh is animated, write out the animated geometry if (mIsGeometryAnimated) { mPolySchema.set(samp); } else { mPolySchema.set(samp); } } void MayaMeshWriter::writeSubD( const Alembic::AbcGeom::OV2fGeomParam::Sample & iUVs) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } std::vector<float> points; std::vector<Alembic::Util::int32_t> facePoints; std::vector<Alembic::Util::int32_t> pointCounts; fillTopology(points, facePoints, pointCounts); Alembic::AbcGeom::OSubDSchema::Sample samp( Alembic::AbcGeom::V3fArraySample((const Imath::V3f *)&points.front(), points.size() / 3), Alembic::Abc::Int32ArraySample(facePoints), Alembic::Abc::Int32ArraySample(pointCounts)); samp.setUVs( iUVs ); MPlug plug = lMesh.findPlug("facVaryingInterpolateBoundary"); if (!plug.isNull()) samp.setFaceVaryingInterpolateBoundary(plug.asInt()); plug = lMesh.findPlug("interpolateBoundary"); if (!plug.isNull()) samp.setInterpolateBoundary(plug.asInt()); plug = lMesh.findPlug("faceVaryingPropagateCorners"); if (!plug.isNull()) samp.setFaceVaryingPropagateCorners(plug.asInt()); std::vector <Alembic::Util::int32_t> creaseIndices; std::vector <Alembic::Util::int32_t> creaseLengths; std::vector <float> creaseSharpness; std::vector <Alembic::Util::int32_t> cornerIndices; std::vector <float> cornerSharpness; MUintArray edgeIds; MDoubleArray creaseData; if (lMesh.getCreaseEdges(edgeIds, creaseData) == MS::kSuccess) { unsigned int numCreases = creaseData.length(); creaseIndices.resize(numCreases * 2); creaseLengths.resize(numCreases, 2); creaseSharpness.resize(numCreases); for (unsigned int i = 0; i < numCreases; ++i) { int verts[2]; lMesh.getEdgeVertices(edgeIds[i], verts); creaseIndices[2 * i] = verts[0]; creaseIndices[2 * i + 1] = verts[1]; creaseSharpness[i] = static_cast<float>(creaseData[i]); } samp.setCreaseIndices(Alembic::Abc::Int32ArraySample(creaseIndices)); samp.setCreaseLengths(Alembic::Abc::Int32ArraySample(creaseLengths)); samp.setCreaseSharpnesses( Alembic::Abc::FloatArraySample(creaseSharpness)); } MUintArray cornerIds; MDoubleArray cornerData; if (lMesh.getCreaseVertices(cornerIds, cornerData) == MS::kSuccess) { unsigned int numCorners = cornerIds.length(); cornerIndices.resize(numCorners); cornerSharpness.resize(numCorners); for (unsigned int i = 0; i < numCorners; ++i) { cornerIndices[i] = cornerIds[i]; cornerSharpness[i] = static_cast<float>(cornerData[i]); } samp.setCornerSharpnesses( Alembic::Abc::FloatArraySample(cornerSharpness)); samp.setCornerIndices( Alembic::Abc::Int32ArraySample(cornerIndices)); } #if MAYA_API_VERSION >= 201100 MUintArray holes = lMesh.getInvisibleFaces(); unsigned int numHoles = holes.length(); std::vector <Alembic::Util::int32_t> holeIndices(numHoles); for (unsigned int i = 0; i < numHoles; ++i) { holeIndices[i] = holes[i]; } if (!holeIndices.empty()) { samp.setHoles(holeIndices); } #endif mSubDSchema.set(samp); } // the arrays being passed in are assumed to be empty void MayaMeshWriter::fillTopology( std::vector<float> & oPoints, std::vector<Alembic::Util::int32_t> & oFacePoints, std::vector<Alembic::Util::int32_t> & oPointCounts) { MStatus status = MS::kSuccess; MFnMesh lMesh( mDagPath, &status ); if ( !status ) { MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" ); } MFloatPointArray pts; lMesh.getPoints(pts); if (pts.length() < 3 && pts.length() > 0) { MString err = lMesh.fullPathName() + " is not a valid mesh, because it only has "; err += pts.length(); err += " points."; MGlobal::displayError(err); return; } unsigned int numPolys = lMesh.numPolygons(); if (numPolys == 0) { MGlobal::displayWarning(lMesh.fullPathName() + " has no polygons."); return; } unsigned int i; int j; oPoints.resize(pts.length() * 3); // repack the float for (i = 0; i < pts.length(); i++) { size_t local = i * 3; oPoints[local] = pts[i].x; oPoints[local+1] = pts[i].y; oPoints[local+2] = pts[i].z; } /* oPoints - oFacePoints - vertex list oPointCounts - number of points per polygon */ MIntArray faceArray; for (i = 0; i < numPolys; i++) { lMesh.getPolygonVertices(i, faceArray); if (faceArray.length() < 3) { MGlobal::displayWarning("Skipping degenerate polygon"); continue; } // write backwards cause polygons in Maya are in a different order // from Renderman (clockwise vs counter-clockwise?) int faceArrayLength = faceArray.length() - 1; for (j = faceArrayLength; j > -1; j--) { oFacePoints.push_back(faceArray[j]); } oPointCounts.push_back(faceArray.length()); } }
30.67236
80
0.58948
nebkor
dbbbbb8ff47810387129230e328d98f847ad6952
13,461
cpp
C++
src/qt/qtbase/src/corelib/itemmodels/qabstractproxymodel.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/corelib/itemmodels/qabstractproxymodel.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/corelib/itemmodels/qabstractproxymodel.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 QtGui module 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 "qabstractproxymodel.h" #ifndef QT_NO_PROXYMODEL #include "qitemselectionmodel.h" #include <private/qabstractproxymodel_p.h> #include <QtCore/QSize> #include <QtCore/QStringList> QT_BEGIN_NAMESPACE /*! \since 4.1 \class QAbstractProxyModel \brief The QAbstractProxyModel class provides a base class for proxy item models that can do sorting, filtering or other data processing tasks. \ingroup model-view \inmodule QtCore This class defines the standard interface that proxy models must use to be able to interoperate correctly with other model/view components. It is not supposed to be instantiated directly. All standard proxy models are derived from the QAbstractProxyModel class. If you need to create a new proxy model class, it is usually better to subclass an existing class that provides the closest behavior to the one you want to provide. Proxy models that filter or sort items of data from a source model should be created by using or subclassing QSortFilterProxyModel. To subclass QAbstractProxyModel, you need to implement mapFromSource() and mapToSource(). The mapSelectionFromSource() and mapSelectionToSource() functions only need to be reimplemented if you need a behavior different from the default behavior. \note If the source model is deleted or no source model is specified, the proxy model operates on a empty placeholder model. \sa QSortFilterProxyModel, QAbstractItemModel, {Model/View Programming} */ /*! \property QAbstractProxyModel::sourceModel \brief the source model this proxy model. */ //detects the deletion of the source model void QAbstractProxyModelPrivate::_q_sourceModelDestroyed() { invalidatePersistentIndexes(); model = QAbstractItemModelPrivate::staticEmptyModel(); } /*! Constructs a proxy model with the given \a parent. */ QAbstractProxyModel::QAbstractProxyModel(QObject *parent) :QAbstractItemModel(*new QAbstractProxyModelPrivate, parent) { setSourceModel(QAbstractItemModelPrivate::staticEmptyModel()); } /*! \internal */ QAbstractProxyModel::QAbstractProxyModel(QAbstractProxyModelPrivate &dd, QObject *parent) : QAbstractItemModel(dd, parent) { setSourceModel(QAbstractItemModelPrivate::staticEmptyModel()); } /*! Destroys the proxy model. */ QAbstractProxyModel::~QAbstractProxyModel() { } /*! Sets the given \a sourceModel to be processed by the proxy model. Subclasses should call beginResetModel() at the beginning of the method, disconnect from the old model, call this method, connect to the new model, and call endResetModel(). */ void QAbstractProxyModel::setSourceModel(QAbstractItemModel *sourceModel) { Q_D(QAbstractProxyModel); if (sourceModel != d->model) { if (d->model) disconnect(d->model, SIGNAL(destroyed()), this, SLOT(_q_sourceModelDestroyed())); if (sourceModel) { d->model = sourceModel; connect(d->model, SIGNAL(destroyed()), this, SLOT(_q_sourceModelDestroyed())); } else { d->model = QAbstractItemModelPrivate::staticEmptyModel(); } d->roleNames = d->model->roleNames(); emit sourceModelChanged(QPrivateSignal()); } } /*! Clears the roleNames of this proxy model. */ void QAbstractProxyModel::resetInternalData() { Q_D(QAbstractProxyModel); d->roleNames = d->model->roleNames(); } /*! Returns the model that contains the data that is available through the proxy model. */ QAbstractItemModel *QAbstractProxyModel::sourceModel() const { Q_D(const QAbstractProxyModel); if (d->model == QAbstractItemModelPrivate::staticEmptyModel()) return 0; return d->model; } /*! \reimp */ bool QAbstractProxyModel::submit() { Q_D(QAbstractProxyModel); return d->model->submit(); } /*! \reimp */ void QAbstractProxyModel::revert() { Q_D(QAbstractProxyModel); d->model->revert(); } /*! \fn QModelIndex QAbstractProxyModel::mapToSource(const QModelIndex &proxyIndex) const Reimplement this function to return the model index in the source model that corresponds to the \a proxyIndex in the proxy model. \sa mapFromSource() */ /*! \fn QModelIndex QAbstractProxyModel::mapFromSource(const QModelIndex &sourceIndex) const Reimplement this function to return the model index in the proxy model that corresponds to the \a sourceIndex from the source model. \sa mapToSource() */ /*! Returns a source selection mapped from the specified \a proxySelection. Reimplement this method to map proxy selections to source selections. */ QItemSelection QAbstractProxyModel::mapSelectionToSource(const QItemSelection &proxySelection) const { QModelIndexList proxyIndexes = proxySelection.indexes(); QItemSelection sourceSelection; for (int i = 0; i < proxyIndexes.size(); ++i) { const QModelIndex proxyIdx = mapToSource(proxyIndexes.at(i)); if (!proxyIdx.isValid()) continue; sourceSelection << QItemSelectionRange(proxyIdx); } return sourceSelection; } /*! Returns a proxy selection mapped from the specified \a sourceSelection. Reimplement this method to map source selections to proxy selections. */ QItemSelection QAbstractProxyModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const { QModelIndexList sourceIndexes = sourceSelection.indexes(); QItemSelection proxySelection; for (int i = 0; i < sourceIndexes.size(); ++i) { const QModelIndex srcIdx = mapFromSource(sourceIndexes.at(i)); if (!srcIdx.isValid()) continue; proxySelection << QItemSelectionRange(srcIdx); } return proxySelection; } /*! \reimp */ QVariant QAbstractProxyModel::data(const QModelIndex &proxyIndex, int role) const { Q_D(const QAbstractProxyModel); return d->model->data(mapToSource(proxyIndex), role); } /*! \reimp */ QVariant QAbstractProxyModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_D(const QAbstractProxyModel); int sourceSection; if (orientation == Qt::Horizontal) { const QModelIndex proxyIndex = index(0, section); sourceSection = mapToSource(proxyIndex).column(); } else { const QModelIndex proxyIndex = index(section, 0); sourceSection = mapToSource(proxyIndex).row(); } return d->model->headerData(sourceSection, orientation, role); } /*! \reimp */ QMap<int, QVariant> QAbstractProxyModel::itemData(const QModelIndex &proxyIndex) const { return QAbstractItemModel::itemData(proxyIndex); } /*! \reimp */ Qt::ItemFlags QAbstractProxyModel::flags(const QModelIndex &index) const { Q_D(const QAbstractProxyModel); return d->model->flags(mapToSource(index)); } /*! \reimp */ bool QAbstractProxyModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_D(QAbstractProxyModel); return d->model->setData(mapToSource(index), value, role); } /*! \reimp */ bool QAbstractProxyModel::setItemData(const QModelIndex &index, const QMap< int, QVariant >& roles) { return QAbstractItemModel::setItemData(index, roles); } /*! \reimp */ bool QAbstractProxyModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { Q_D(QAbstractProxyModel); int sourceSection; if (orientation == Qt::Horizontal) { const QModelIndex proxyIndex = index(0, section); sourceSection = mapToSource(proxyIndex).column(); } else { const QModelIndex proxyIndex = index(section, 0); sourceSection = mapToSource(proxyIndex).row(); } return d->model->setHeaderData(sourceSection, orientation, value, role); } /*! \reimp */ QModelIndex QAbstractProxyModel::buddy(const QModelIndex &index) const { Q_D(const QAbstractProxyModel); return mapFromSource(d->model->buddy(mapToSource(index))); } /*! \reimp */ bool QAbstractProxyModel::canFetchMore(const QModelIndex &parent) const { Q_D(const QAbstractProxyModel); return d->model->canFetchMore(mapToSource(parent)); } /*! \reimp */ void QAbstractProxyModel::fetchMore(const QModelIndex &parent) { Q_D(QAbstractProxyModel); d->model->fetchMore(mapToSource(parent)); } /*! \reimp */ void QAbstractProxyModel::sort(int column, Qt::SortOrder order) { Q_D(QAbstractProxyModel); d->model->sort(column, order); } /*! \reimp */ QSize QAbstractProxyModel::span(const QModelIndex &index) const { Q_D(const QAbstractProxyModel); return d->model->span(mapToSource(index)); } /*! \reimp */ bool QAbstractProxyModel::hasChildren(const QModelIndex &parent) const { Q_D(const QAbstractProxyModel); return d->model->hasChildren(mapToSource(parent)); } /*! \reimp */ QModelIndex QAbstractProxyModel::sibling(int row, int column, const QModelIndex &idx) const { return index(row, column, idx.parent()); } /*! \reimp */ QMimeData* QAbstractProxyModel::mimeData(const QModelIndexList &indexes) const { Q_D(const QAbstractProxyModel); QModelIndexList list; list.reserve(indexes.count()); foreach(const QModelIndex &index, indexes) list << mapToSource(index); return d->model->mimeData(list); } void QAbstractProxyModelPrivate::mapDropCoordinatesToSource(int row, int column, const QModelIndex &parent, int *sourceRow, int *sourceColumn, QModelIndex *sourceParent) const { Q_Q(const QAbstractProxyModel); *sourceRow = -1; *sourceColumn = -1; if (row == -1 && column == -1) { *sourceParent = q->mapToSource(parent); } else if (row == q->rowCount(parent)) { *sourceParent = q->mapToSource(parent); *sourceRow = model->rowCount(*sourceParent); } else { QModelIndex proxyIndex = q->index(row, column, parent); QModelIndex sourceIndex = q->mapToSource(proxyIndex); *sourceRow = sourceIndex.row(); *sourceColumn = sourceIndex.column(); *sourceParent = sourceIndex.parent(); } } /*! \reimp \since 5.4 */ bool QAbstractProxyModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_D(const QAbstractProxyModel); int sourceDestinationRow; int sourceDestinationColumn; QModelIndex sourceParent; d->mapDropCoordinatesToSource(row, column, parent, &sourceDestinationRow, &sourceDestinationColumn, &sourceParent); return d->model->canDropMimeData(data, action, sourceDestinationRow, sourceDestinationColumn, sourceParent); } /*! \reimp \since 5.4 */ bool QAbstractProxyModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { Q_D(QAbstractProxyModel); int sourceDestinationRow; int sourceDestinationColumn; QModelIndex sourceParent; d->mapDropCoordinatesToSource(row, column, parent, &sourceDestinationRow, &sourceDestinationColumn, &sourceParent); return d->model->dropMimeData(data, action, sourceDestinationRow, sourceDestinationColumn, sourceParent); } /*! \reimp */ QStringList QAbstractProxyModel::mimeTypes() const { Q_D(const QAbstractProxyModel); return d->model->mimeTypes(); } /*! \reimp */ Qt::DropActions QAbstractProxyModel::supportedDragActions() const { Q_D(const QAbstractProxyModel); return d->model->supportedDragActions(); } /*! \reimp */ Qt::DropActions QAbstractProxyModel::supportedDropActions() const { Q_D(const QAbstractProxyModel); return d->model->supportedDropActions(); } QT_END_NAMESPACE #include "moc_qabstractproxymodel.cpp" #endif // QT_NO_PROXYMODEL
28.640426
127
0.703291
power-electro
dbc127aa4ee961c4b5bb64757f7f25e592450c90
145
hpp
C++
Block1/BMI/BMI.hpp
andreadelprete/latex-cpp-exercises-simple
6e436b268e503d298e5ee642ed92095b5f6473c4
[ "Unlicense" ]
null
null
null
Block1/BMI/BMI.hpp
andreadelprete/latex-cpp-exercises-simple
6e436b268e503d298e5ee642ed92095b5f6473c4
[ "Unlicense" ]
null
null
null
Block1/BMI/BMI.hpp
andreadelprete/latex-cpp-exercises-simple
6e436b268e503d298e5ee642ed92095b5f6473c4
[ "Unlicense" ]
1
2021-09-02T07:02:52.000Z
2021-09-02T07:02:52.000Z
#ifndef BMI_H #define BMI_H float personPrompt(int personID); float computeBMI(float height, float weight); float classBMI(float BMI); #endif
14.5
45
0.77931
andreadelprete
3a78aab07f9e22a6e2e8a72a09d2a8f61c165068
633
hpp
C++
oxui/objects/dropdown.hpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
oxui/objects/dropdown.hpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
oxui/objects/dropdown.hpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
#ifndef OXUI_DROPDOWN_HPP #define OXUI_DROPDOWN_HPP #include <memory> #include <vector> #include <functional> #include "object.hpp" #include "../types/types.hpp" namespace oxui { class dropdown : public obj { int hovered_index; public: str label; std::vector< str > items; int value; bool opened; dropdown( const str& label, const std::vector< str >& items ) { this->hovered_index = 0; this->value = 0; this->opened = false; this->label = label; this->items = items; this->type = object_dropdown; } ~dropdown( ) {} void think( ); void draw( ) override; }; } #endif // OXUI_DROPDOWN_HPP
17.583333
65
0.658768
amizu03
3a7adc6e7e542cbb7977b1ef7fdd1c40235ca62a
1,073
cpp
C++
source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp
tgvarik/MaterialX
0f0c1f9934bfa3b2d54516672c0b26ef93f9f94e
[ "BSD-3-Clause" ]
8
2019-05-18T10:56:25.000Z
2022-03-08T21:00:24.000Z
source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp
tgvarik/MaterialX
0f0c1f9934bfa3b2d54516672c0b26ef93f9f94e
[ "BSD-3-Clause" ]
null
null
null
source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp
tgvarik/MaterialX
0f0c1f9934bfa3b2d54516672c0b26ef93f9f94e
[ "BSD-3-Clause" ]
1
2020-02-24T02:16:19.000Z
2020-02-24T02:16:19.000Z
// // TM & (c) 2019 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <PyMaterialX/PyMaterialX.h> #include <MaterialXRender/ExceptionShaderValidationError.h> namespace py = pybind11; namespace mx = MaterialX; void bindPyExceptionShaderValidationError(py::module& mod) { static py::exception<mx::ExceptionShaderValidationError> pyExceptionShaderValidationError(mod, "ExceptionShaderValidationError"); py::register_exception_translator( [](std::exception_ptr errPtr) { try { if (errPtr != NULL) std::rethrow_exception(errPtr); } catch (const mx::ExceptionShaderValidationError& err) { std::string errorMsg = err.what(); for (std::string error : err.errorLog()) { errorMsg += "\n" + error; } PyErr_SetString(PyExc_LookupError, errorMsg.c_str()); } } ); }
29
133
0.588071
tgvarik
3a8163305259a3672d2bd6cad67486d664b5ce37
96
cpp
C++
problem_solving/UVA/12478/16891780_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
2
2020-09-02T12:07:47.000Z
2020-11-17T11:17:16.000Z
problem_solving/UVA/12478/16891780_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
null
null
null
problem_solving/UVA/12478/16891780_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
4
2020-08-11T14:23:34.000Z
2020-11-17T10:52:31.000Z
#include <bits/stdc++.h> using namespace std; int main(){ printf("KABIR\n"); return 0; }
16
24
0.614583
cosmicray001
3a854ddda39a02b99c0fb9648640b041445a57da
525
hpp
C++
src/Graphics/PathDrawable.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
127
2018-12-09T18:40:02.000Z
2022-03-06T00:10:07.000Z
src/Graphics/PathDrawable.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
267
2019-02-26T22:16:48.000Z
2022-02-09T09:49:22.000Z
src/Graphics/PathDrawable.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
17
2019-02-26T20:45:34.000Z
2021-06-17T15:06:26.000Z
#pragma once #include <vector> #include <memory> #include <glm/vec2.hpp> #include <ngf/Graphics/Drawable.h> #include <ngf/Graphics/RenderTarget.h> #include <ngf/Graphics/RenderStates.h> namespace ng { class PathDrawable final : public ngf::Drawable { public: explicit PathDrawable(std::vector<glm::vec2> path); [[nodiscard]] const std::vector<glm::vec2> &getPath() const { return m_path; } void draw(ngf::RenderTarget &target, ngf::RenderStates states) const override; private: std::vector<glm::vec2> m_path; }; }
25
80
0.731429
scemino
3a85dfa7cbb610f785b2c268ed01962063c6f013
963
cpp
C++
Medusa/Medusa/Node/Template/SpriteTemplate.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
143
2015-11-18T01:06:03.000Z
2022-03-30T03:08:54.000Z
Medusa/Medusa/Node/Template/SpriteTemplate.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
1
2019-10-23T13:00:40.000Z
2019-10-23T13:00:40.000Z
Medusa/Medusa/Node/Template/SpriteTemplate.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
45
2015-11-18T01:17:59.000Z
2022-03-05T12:29:45.000Z
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #include "MedusaPreCompiled.h" #include "SpriteTemplate.h" #include "Node/INode.h" #include "Node/NodeFactory.h" #include "Node/Sprite/Sprite.h" #include "Rendering/RenderingObjectFactory.h" MEDUSA_BEGIN; Size2F SpriteTemplate::Measure(const FileId& data, const Size2F& limitSize /*= Size2F::Zero*/) const { auto obj= RenderingObjectFactory::Instance().CreateFromTexture(data); if (obj.IsValid()) { return obj.Mesh()->Size().To2D(); } return limitSize; } INode* SpriteTemplate::Load(const FileId& data, const Size2F& limitSize /*= Size2F::Zero*/,INode* reloadNode /*= nullptr*/)const { if (reloadNode==nullptr) { reloadNode= NodeFactory::Instance().CreateSprite(data); } else { reloadNode->SetRenderingObjectFile(data); } OnSetupNode(reloadNode); return reloadNode; } MEDUSA_END;
22.395349
128
0.731049
tony2u
3a86c1a74c400621281bbe708eb6dce5071108a1
5,275
cpp
C++
src/cpp-ethereum/aleth-bootnode/main.cpp
nccproject/ncc
068ccc82a73d28136546095261ad8ccef7e541a3
[ "MIT" ]
6
2021-08-02T21:35:10.000Z
2022-01-18T05:41:49.000Z
src/cpp-ethereum/aleth-bootnode/main.cpp
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
null
null
null
src/cpp-ethereum/aleth-bootnode/main.cpp
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
4
2021-08-14T13:12:43.000Z
2021-11-26T21:19:35.000Z
/* This file is part of aleth. aleth is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. aleth 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 aleth. If not, see <http://www.gnu.org/licenses/>. */ #include <libdevcore/FileSystem.h> #include <libdevcore/LoggingProgramOptions.h> #include <libethcore/Common.h> #include <libp2p/Host.h> #include <boost/program_options.hpp> #include <boost/program_options/options_description.hpp> #include <iostream> #include <thread> namespace po = boost::program_options; namespace fs = boost::filesystem; using namespace dev; using namespace dev::p2p; using namespace dev::eth; using namespace std; namespace { string const c_programName = "aleth-bootnode"; string const c_networkConfigFileName = c_programName + "-network.rlp"; } // namespace int main(int argc, char** argv) { setDefaultOrCLocale(); bool allowLocalDiscovery = false; po::options_description generalOptions("GENERAL OPTIONS", c_lineWidth); auto addGeneralOption = generalOptions.add_options(); addGeneralOption("help,h", "Show this help message and exit\n"); LoggingOptions loggingOptions; po::options_description loggingProgramOptions( createLoggingProgramOptions(c_lineWidth, loggingOptions)); po::options_description clientNetworking("NETWORKING", c_lineWidth); auto addNetworkingOption = clientNetworking.add_options(); #if ETH_MINIUPNPC addNetworkingOption( "upnp", po::value<string>()->value_name("<on/off>"), "Use UPnP for NAT (default: on)"); #endif addNetworkingOption("public-ip", po::value<string>()->value_name("<ip>"), "Force advertised public IP to the given IP (default: auto)"); addNetworkingOption("listen-ip", po::value<string>()->value_name("<ip>(:<port>)"), "Listen on the given IP for incoming connections (default: 0.0.0.0)"); addNetworkingOption("listen", po::value<unsigned short>()->value_name("<port>"), "Listen on the given port for incoming connections (default: 30303)"); addNetworkingOption("allow-local-discovery", po::bool_switch(&allowLocalDiscovery), "Include local addresses in the discovery process. Used for testing purposes."); po::options_description allowedOptions("Allowed options"); allowedOptions.add(generalOptions).add(loggingProgramOptions).add(clientNetworking); po::variables_map vm; try { po::parsed_options parsed = po::parse_command_line(argc, argv, allowedOptions); po::store(parsed, vm); po::notify(vm); } catch (po::error const& e) { cout << e.what() << "\n"; return AlethErrors::ArgumentProcessingFailure; } if (vm.count("help")) { cout << "NAME:\n" << " " << c_programName << "\n" << "USAGE:\n" << " " << c_programName << " [options]\n\n"; cout << generalOptions << clientNetworking << loggingProgramOptions; return AlethErrors::Success; } /// Networking params. string listenIP; unsigned short listenPort = c_defaultListenPort; string publicIP; bool upnp = true; #if ETH_MINIUPNPC if (vm.count("upnp")) { string m = vm["upnp"].as<string>(); if (isTrue(m)) upnp = true; else if (isFalse(m)) upnp = false; else { cerr << "Bad " << "--upnp" << " option: " << m << "\n"; return -1; } } #endif if (vm.count("public-ip")) publicIP = vm["public-ip"].as<string>(); if (vm.count("listen-ip")) listenIP = vm["listen-ip"].as<string>(); if (vm.count("listen")) listenPort = vm["listen"].as<unsigned short>(); setupLogging(loggingOptions); if (loggingOptions.verbosity > 0) cout << EthGrayBold << c_programName << ", a C++ Ethereum bootnode implementation" EthReset << "\n"; auto netPrefs = publicIP.empty() ? NetworkConfig(listenIP, listenPort, upnp) : NetworkConfig(publicIP, listenIP, listenPort, upnp); netPrefs.allowLocalDiscovery = allowLocalDiscovery; auto netData = contents(getDataDir() / fs::path(c_networkConfigFileName)); Host h(c_programName, netPrefs, &netData); h.start(); cout << "Node ID: " << h.enode() << endl; ExitHandler exitHandler; signal(SIGTERM, &ExitHandler::exitHandler); signal(SIGABRT, &ExitHandler::exitHandler); signal(SIGINT, &ExitHandler::exitHandler); while (!exitHandler.shouldExit()) this_thread::sleep_for(chrono::milliseconds(1000)); h.stop(); netData = h.saveNetwork(); if (!netData.empty()) writeFile(getDataDir() / fs::path(c_networkConfigFileName), &netData); return AlethErrors::Success; }
33.814103
99
0.652891
nccproject
3a8878aa8d8d23e201beb54acf86149bbc5fed5d
4,879
cpp
C++
fractalCartoon/fractalCartoon.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
fractalCartoon/fractalCartoon.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
fractalCartoon/fractalCartoon.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
#include "cinder/app/AppBasic.h" #include "cinder/ImageIo.h" #include "cinder/gl/Texture.h" #include "cinder/gl/GlslProg.h" #include "cinder/audio/Input.h" #include "cinder/audio/FftProcessor.h" #include "Resources.h" using namespace ci; using namespace ci::app; class circuitShaderApp : public AppBasic { public: void setup(); void keyDown( KeyEvent event ); void update(); void draw(); gl::TextureRef soundTexture, palletteTexture; gl::GlslProgRef mShader; audio::Input mInput; std::shared_ptr<float> mFftDataRef; audio::PcmBuffer32fRef mPcmBuffer; float volume; float speedMult; float zoom; bool wireFrame; }; void circuitShaderApp::setup() { setFrameRate(25.0); try { //gl::Texture::Format format; //format.setTargetRect(); palletteTexture = gl::Texture::create( loadImage( loadResource( RES_IMAGE_JPG ) )); } catch( ... ) { std::cout << "unable to load the texture file!" << std::endl; } try { mShader = gl::GlslProg::create( loadResource( RES_PASSTHRU_VERT ), loadResource( RES_BLUR_FRAG ) ); } catch( gl::GlslProgCompileExc &exc ) { std::cout << "Shader compile error: " << std::endl; std::cout << exc.what(); } catch( ... ) { std::cout << "Unable to load shader" << std::endl; } const std::vector<audio::InputDeviceRef>& devices = audio::Input::getDevices(); for( std::vector<audio::InputDeviceRef>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter ) { console() << (*iter)->getName() << std::endl; } mInput = audio::Input(); mInput.start(); zoom = 0.244; volume = 0.0f; speedMult = 0.1; wireFrame = true; } void circuitShaderApp::keyDown( KeyEvent event ) { int code = event.getCode(); if( code == app::KeyEvent::KEY_f ) { setFullScreen( ! isFullScreen() ); } if (code == app::KeyEvent::KEY_RIGHT){ speedMult += 1.; } if (code == app::KeyEvent::KEY_LEFT){ speedMult -= 1.; } if (code == app::KeyEvent::KEY_SPACE){ wireFrame = !wireFrame; } zoom = math<float>::clamp( zoom, 0., 1.0 ); std::cout<<speedMult<<std::endl; } void circuitShaderApp::update() { mPcmBuffer = mInput.getPcmBuffer(); if( ! mPcmBuffer ) { return; } /* shadertoy: The FFT signal, which is 512 pixels/frequencies long, gets normalized to 0..1 and mapped to 0..255. The wave form, which is also 512 pixels/sampled long, gets renormalized too from -16387..16384 to 0..1. (and then to 0..255???) FFT goes in the first row, waveform in the second row. So this is a 512x2 gray scale 8 bit texture. */ uint16_t bandCount = 512; mFftDataRef = audio::calculateFft( mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ), bandCount ); float * fftBuffer = mFftDataRef.get(); if (!fftBuffer) return; //create a sound texture as 512x2 unsigned char signal[1024]; //the first row is the spectrum (shadertoy) float max = 0.; for(int i=0;i<512;++i){ if (fftBuffer[i] > max) max = fftBuffer[i]; } float ht = 255.0/max; float volumeAcc = 0.0f; for(int i=0;i<512;++i){ signal[i] = (unsigned char) (fftBuffer[i] * ht); volumeAcc += fftBuffer[i] * ht; } volume = volumeAcc/(512.0*255); //waveform uint32_t bufferSamples = mPcmBuffer->getSampleCount(); audio::Buffer32fRef leftBuffer = mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ); int endIdx = bufferSamples; //only use the last 1024 samples or less int32_t startIdx = ( endIdx - 1024 ); startIdx = math<int32_t>::clamp( startIdx, 0, endIdx ); float mx = -FLT_MAX,mn = FLT_MAX, val; for( uint32_t i = startIdx; i < endIdx; i++) { val = leftBuffer->mData[i]; if (val > mx) mx = val; if (val < mn) mn = val; } float scale = 1.0/(mx - mn); for( uint32_t i = startIdx, c = 512; c < 1024; i++, c++ ) { signal[c] = (unsigned char) ((leftBuffer->mData[i]-mn)*scale); } // store it as a 512x2 texture soundTexture = std::make_shared<gl::Texture>( signal, GL_LUMINANCE, 512, 2 ); } void circuitShaderApp::draw() { gl::clear(); if (soundTexture) soundTexture->enableAndBind(); palletteTexture->enableAndBind(); mShader->bind(); mShader->uniform( "iChannel0", soundTexture ? 0 : 1 ); mShader->uniform( "iChannel1", 1 ); mShader->uniform( "iResolution", Vec3f( getWindowWidth(), getWindowHeight(), 0.0f ) ); mShader->uniform( "iGlobalTime", float( getElapsedSeconds() ) ); mShader->uniform("zoomm", zoom*volume); mShader->uniform("speedMult", speedMult); mShader->uniform("isWireFrame", wireFrame); gl::drawSolidRect( getWindowBounds() ); if (soundTexture) soundTexture->unbind(); palletteTexture->unbind(); } CINDER_APP_BASIC( circuitShaderApp, RendererGl )
25.411458
132
0.632917
eighteight
3a8c260852997736ad7e299581101a3e05af4834
194
cpp
C++
senha.cpp
guilherme9718/monitoria-rapida
20ea8f2e1afbc498de5deb3b3972fd6b523fbab1
[ "Apache-2.0" ]
1
2021-09-03T04:08:22.000Z
2021-09-03T04:08:22.000Z
senha.cpp
vitorrutfpr/monitoria-rapida
20ea8f2e1afbc498de5deb3b3972fd6b523fbab1
[ "Apache-2.0" ]
null
null
null
senha.cpp
vitorrutfpr/monitoria-rapida
20ea8f2e1afbc498de5deb3b3972fd6b523fbab1
[ "Apache-2.0" ]
3
2021-07-06T17:19:08.000Z
2021-09-01T19:45:59.000Z
#include "senha.h" #include "ui_senha.h" Senha::Senha(QWidget *parent) : QDialog(parent), ui(new Ui::Senha) { ui->setupUi(this); } Senha::~Senha() { delete ui; }
12.933333
32
0.556701
guilherme9718
3a8df78a401be31ff80d913bad76971fe4125f91
2,963
cpp
C++
lzma/lzma920/CPP/7zip/Compress/PpmdEncoder.cpp
LiveMirror/uncompression
2cdef0ed9c6281b2c0542a9d17441dd0f551ed4d
[ "Apache-2.0" ]
3
2019-06-10T18:04:14.000Z
2020-12-05T18:11:40.000Z
lzma/lzma920/CPP/7zip/Compress/PpmdEncoder.cpp
LiveMirror/uncompression
2cdef0ed9c6281b2c0542a9d17441dd0f551ed4d
[ "Apache-2.0" ]
null
null
null
lzma/lzma920/CPP/7zip/Compress/PpmdEncoder.cpp
LiveMirror/uncompression
2cdef0ed9c6281b2c0542a9d17441dd0f551ed4d
[ "Apache-2.0" ]
2
2020-09-24T19:04:14.000Z
2020-12-05T18:11:43.000Z
// PpmdEncoder.cpp // 2009-03-11 : Igor Pavlov : Public domain #include "StdAfx.h" #include "../../../C/Alloc.h" #include "../../../C/CpuArch.h" #include "../Common/StreamUtils.h" #include "PpmdEncoder.h" namespace NCompress { namespace NPpmd { static const UInt32 kBufSize = (1 << 20); static void *SzBigAlloc(void *, size_t size) { return BigAlloc(size); } static void SzBigFree(void *, void *address) { BigFree(address); } static ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; CEncoder::CEncoder(): _inBuf(NULL), _usedMemSize(1 << 24), _order(6) { _rangeEnc.Stream = &_outStream.p; Ppmd7_Construct(&_ppmd); } CEncoder::~CEncoder() { ::MidFree(_inBuf); Ppmd7_Free(&_ppmd, &g_BigAlloc); } STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) { for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = props[i]; if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 v = (UInt32)prop.ulVal; switch(propIDs[i]) { case NCoderPropID::kUsedMemorySize: if (v < (1 << 16) || v > PPMD7_MAX_MEM_SIZE || (v & 3) != 0) return E_INVALIDARG; _usedMemSize = v; break; case NCoderPropID::kOrder: if (v < 2 || v > 32) return E_INVALIDARG; _order = (Byte)v; break; default: return E_INVALIDARG; } } return S_OK; } STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) { const UInt32 kPropSize = 5; Byte props[kPropSize]; props[0] = _order; SetUi32(props + 1, _usedMemSize); return WriteStream(outStream, props, kPropSize); } HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) { if (!_inBuf) { _inBuf = (Byte *)::MidAlloc(kBufSize); if (!_inBuf) return E_OUTOFMEMORY; } if (!_outStream.Alloc(1 << 20)) return E_OUTOFMEMORY; if (!Ppmd7_Alloc(&_ppmd, _usedMemSize, &g_BigAlloc)) return E_OUTOFMEMORY; _outStream.Stream = outStream; _outStream.Init(); Ppmd7z_RangeEnc_Init(&_rangeEnc); Ppmd7_Init(&_ppmd, _order); UInt64 processed = 0; for (;;) { UInt32 size; RINOK(inStream->Read(_inBuf, kBufSize, &size)); if (size == 0) { // We don't write EndMark in PPMD-7z. // Ppmd7_EncodeSymbol(&_ppmd, &_rangeEnc, -1); Ppmd7z_RangeEnc_FlushData(&_rangeEnc); return _outStream.Flush(); } for (UInt32 i = 0; i < size; i++) { Ppmd7_EncodeSymbol(&_ppmd, &_rangeEnc, _inBuf[i]); RINOK(_outStream.Res); } processed += size; if (progress) { UInt64 outSize = _outStream.GetProcessed(); RINOK(progress->SetRatioInfo(&processed, &outSize)); } } } }}
24.691667
108
0.611542
LiveMirror
3a9378c2d71e659701d679829c5225f441a5d81a
560
cpp
C++
app/midso_main.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
app/midso_main.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
app/midso_main.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
/** Copyright (c) 2015 <wataro> This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #include "easylogging/easylogging++.h" #include "midso/midso.h" INITIALIZE_EASYLOGGINGPP using namespace midso; int main(const int argc, const char ** argv) { LOG(INFO) << "Make It Deep, Simple, Open!"; SharedPointer<Vector<Int>> p_values; const Vector<String> args(argv, argv + argc); LOG(INFO) << args[0]; auto runner = RunnerFactory::create(args); runner->run(); return 0; }
20.740741
52
0.664286
wataro
3a93cc4384489efaa405300689d9ac876b8b4dc7
2,622
cpp
C++
src/server/game/Battlegrounds/Zones/BattlegroundRB.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/game/Battlegrounds/Zones/BattlegroundRB.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/game/Battlegrounds/Zones/BattlegroundRB.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gamePCH.h" #include "Player.h" #include "Battleground.h" #include "BattlegroundRB.h" #include "Language.h" BattlegroundRB::BattlegroundRB() { //TODO FIX ME! m_StartMessageIds[BG_STARTING_EVENT_FIRST] = 0; m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_WS_START_ONE_MINUTE; m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_WS_START_HALF_MINUTE; m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_WS_HAS_BEGUN; } BattlegroundRB::~BattlegroundRB() { } void BattlegroundRB::Update(uint32 diff) { Battleground::Update(diff); } void BattlegroundRB::StartingEventCloseDoors() { } void BattlegroundRB::StartingEventOpenDoors() { } void BattlegroundRB::AddPlayer(Player *plr) { Battleground::AddPlayer(plr); //create score and add it to map, default values are set in constructor BattlegroundRBScore* sc = new BattlegroundRBScore; m_PlayerScores[plr->GetGUID()] = sc; } void BattlegroundRB::RemovePlayer(Player* /*plr*/, uint64 /*guid*/) { } void BattlegroundRB::HandleAreaTrigger(Player * /*Source*/, uint32 /*Trigger*/) { // this is wrong way to implement these things. On official it done by gameobject spell cast. if (GetStatus() != STATUS_IN_PROGRESS) return; } void BattlegroundRB::UpdatePlayerScore(Player* Source, uint32 type, uint32 value, bool doAddHonor) { std::map<uint64, BattlegroundScore*>::iterator itr = m_PlayerScores.find(Source->GetGUID()); if (itr == m_PlayerScores.end()) // player not found... return; Battleground::UpdatePlayerScore(Source, type, value, doAddHonor); }
30.847059
98
0.725782
forgottenlands
3a948e90f7374038645bb8632497c1360b6c45d1
1,517
cpp
C++
Dynamic Programming/TravellingSaleman.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
1
2022-02-15T12:53:00.000Z
2022-02-15T12:53:00.000Z
Dynamic Programming/TravellingSaleman.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
Dynamic Programming/TravellingSaleman.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int arr[20][20], completed[20], n, cost = 0; void takeInput() { int i, j; cout << "Enter the number of city: "; cin >> n; cout << "\nEnter the Cost Matrix\n"; for (i = 0; i < n; i++) { cout << "\nEnter Elements of Row: " << i + 1 << "\n"; for (j = 0; j < n; j++) cin >> arr[i][j]; completed[i] = 0; } cout << "\n\nThe cost list is:"; for (i = 0; i < n; i++) { cout << "\n"; for (j = 0; j < n; j++) cout << "\t" << arr[i][j]; } } int least(int c) { int i, nc = 999; int min = 999, kmin; for (i = 0; i < n; i++) { if ((arr[c][i] != 0) && (completed[i] == 0)) if (arr[c][i] + arr[i][c] < min) { min = arr[i][0] + arr[c][i]; kmin = arr[c][i]; nc = i; } } if (min != 999) cost += kmin; return nc; } void mincost(int city) { int i, ncity; completed[city] = 1; cout << city + 1 << "--->"; ncity = least(city); if (ncity == 999) { ncity = 0; cout << ncity + 1; cost += arr[city][ncity]; return; } mincost(ncity); } int main() { takeInput(); cout << "\n\nThe Path is:\n"; mincost(0); //passing 0 because starting vertex cout << "\n\nMinimum cost is " << cost << endl; cout << "Program developed by Gaurav Gupta Scholar No. 20U03030" << endl; return 0; }
20.5
77
0.42584
gaurav147-star
3a9538fa9c81c1a38941ab9f05f410511bbb2320
9,294
hpp
C++
tmath.hpp
uekstrom/libtaylor
88709f03efda5b81ff460ccef67d4fd0e7d050cc
[ "MIT" ]
4
2015-10-20T13:16:35.000Z
2019-02-14T12:46:10.000Z
tmath.hpp
uekstrom/libtaylor
88709f03efda5b81ff460ccef67d4fd0e7d050cc
[ "MIT" ]
7
2017-02-07T16:13:14.000Z
2018-12-12T13:49:40.000Z
tmath.hpp
uekstrom/libtaylor
88709f03efda5b81ff460ccef67d4fd0e7d050cc
[ "MIT" ]
3
2016-11-02T18:12:41.000Z
2019-06-21T08:01:03.000Z
/* Copyright (c) 2009-2017 Ulf Ekstrom <uekstrom@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once /* Taylor expansions of the intrinsic functions Ulf Ekstrom December 2010. Currently supported: 1/x (inv) exp log pow sqrt cbrt (cube root) atan gauss (exp(-x^2)) erf sin cos asin acos asinh */ #include <cassert> #include <cmath> // Taylor math, template style // N is always the order of the polynomial template <typename T, int N> struct tfuns { static void mul(T * z, const T * x, const T * y) { for (int i = 0; i <= N; i++) { z[i] = x[0] * y[i]; for (int j = 1; j <= i; j++) z[i] += x[j] * y[i - j]; } } // z *= x static void multo(T * z, const T * x) { for (int i = N; i >= 0; i--) { z[i] = x[0] * z[i]; for (int j = 1; j <= i; j++) z[i] += x[j] * z[i - j]; } } // Integrates termwise, leaves x[0] undefined! static void integrate(T * x) { for (int i = N; i >= 1; i--) x[i] = x[i - 1] / i; } static void differentiate(T * x) { for (int i = 1; i <= N; i++) x[i - 1] = i * x[i]; x[N] = 0; } // Set z = z + d static void shift(T * x, T d) { T dn[N + 1]; dn[0] = 1; for (int i = 1; i <= N; i++) dn[i] = d * dn[i - 1]; // Contributions to x[n] for (int n = 0; n < N; n++) { int fac = n + 1; for (int m = n + 1; m < N; m++) { x[n] += fac * dn[m - n] * x[m]; fac *= m + 1; fac /= m - n + 1; } x[n] += fac * dn[N - n] * x[N]; } } // assuming x[0] = 0, put sum_i f[i]x^i in f static void compose(T * f, const T * x) { switch (N) { case 6: f[6] = f[1] * x[6] + 2 * f[2] * x[5] * x[1] + 2 * f[2] * x[4] * x[2] + f[2] * x[3] * x[3] + 3 * f[3] * x[4] * x[1] * x[1] + 6 * f[3] * x[3] * x[2] * x[1] + f[3] * x[2] * x[2] * x[2] + 4 * f[4] * x[3] * x[1] * x[1] * x[1] + 6 * f[4] * x[2] * x[2] * x[1] * x[1] + 5 * f[5] * x[2] * x[1] * x[1] * x[1] * x[1] + f[6] * x[1] * x[1] * x[1] * x[1] * x[1] * x[1]; case 5: f[5] = f[1] * x[5] + x[1] * (2 * f[2] * x[4] + x[1] * (3 * f[3] * x[3] + x[1] * (4 * f[4] * x[2] + f[5] * x[1] * x[1])) + 3 * f[3] * x[2] * x[2]) + 2 * f[2] * x[2] * x[3]; case 4: f[4] = f[1] * x[4] + x[1] * (2 * f[2] * x[3] + x[1] * (3 * f[3] * x[2] + f[4] * x[1] * x[1])) + f[2] * x[2] * x[2]; case 3: f[3] = f[1] * x[3] + x[1] * (2 * f[2] * x[2] + f[3] * x[1] * x[1]); case 2: f[2] = f[1] * x[2] + f[2] * x[1] * x[1]; case 1: f[1] = f[1] * x[1]; case 0: break; default: assert(0 && "Unsupported order in compose()"); } } static void stretch(T * t, T a) { T an = a; for (int i = 1; i <= N; i++) { t[i] *= an; an *= a; } } }; // Taylor series of 1/(a+x) template <typename T, int N> static void inv_expand(T * t, const T & a) { assert(a != 0 && "1/(a+x) not analytic at a = 0"); t[0] = 1 / a; for (int i = 1; i <= N; i++) t[i] = -t[i - 1] * t[0]; } // Evaluate the taylor series of exp(x0+x)=exp(x0)*exp(x) template <typename T, int Ndeg> static void exp_expand(T * t, const T & x0) { T ifac = 1; t[0] = exp(x0); for (int i = 1; i <= Ndeg; i++) { ifac *= i; t[i] = t[0] / ifac; } } // Log series log(a+x) = log(1+x/a) + log(a) template <typename T, int N> static void log_expand(T * t, const T & x0) { assert(x0 > 0 && "log(x) not real analytic at x <= 0"); t[0] = log(x0); T x0inv = 1 / x0; T xn = x0inv; for (int i = 1; i <= N; i++) { t[i] = (xn / double(i)) * (2 * (i & 1) - 1); xn *= x0inv; } } /* Use that (x0+x)^a=x0^a*(1+x/x0)^a */ template <typename T, int N> static void pow_expand(T * t, T x0, T a) { if (x0 <= 0) assert(x0 > 0 && "pow(x,a) not real analytic at x <= 0"); t[0] = pow(x0, a); T x0inv = 1 / x0; for (int i = 1; i <= N; i++) t[i] = t[i - 1] * x0inv * (a - i + 1) / i; } /* Use that (x0+x)^a=x0^a*(1+x/x0)^a */ template <typename T, int N> static void sqrt_expand(T * t, const T & x0) { assert(x0 > 0 && "sqrt(x) not real analytic at x <= 0"); t[0] = sqrt(x0); T x0inv = 1 / x0; for (int i = 1; i <= N; i++) t[i] = t[i - 1] * ((3 * x0inv) / (2 * i) - x0inv); } template <typename T, int N> static void cbrt_expand(T * t, const T & x0) { assert(x0 > 0 && "pow(x,a) not real analytic at x <= 0"); t[0] = cbrt(x0); T x0inv = 1 / x0; for (int i = 1; i <= N; i++) t[i] = t[i - 1] * ((4 * x0inv) / (3 * i) - x0inv); } // Use that d/dx atan(x) = 1/(1 + x^2), // Taylor expand in x^2 and integrate. template <typename T, int Ndeg> static void atan_expand(T * t, T a) { // Calculate taylor expansion of 1/(1+a^2+x) T x[Ndeg + 1]; inv_expand<T, Ndeg>(t, 1 + a * a); // insert x = 2*a*x + x^2 x[0] = 0; if (Ndeg > 0) x[1] = 2 * a; if (Ndeg > 1) x[2] = 1; for (int i = 3; i <= Ndeg; i++) x[i] = 0; tfuns<T, Ndeg>::compose(t, x); // Integrate each term and set the constant tfuns<T, Ndeg>::integrate(t); t[0] = atan(a); } /* Taylor expansion of exp(-(a+x)^2) = exp(-a^2-2a*x)*exp(-x^2) Just doing a composition is unstable near 0. */ template <typename T, int Ndeg> static void gauss_expand(T * t, const T & a) { exp_expand<T, Ndeg>(t, -a * a); tfuns<T, Ndeg>::stretch(t, -2 * a); T g[Ndeg + 1]; g[0] = 1; for (int i = 1; i <= Ndeg; i += 2) g[i] = 0; for (int i = 1; i <= Ndeg / 2; i++) g[2 * i] = -g[2 * (i - 1)] / i; tfuns<T, Ndeg>::multo(t, g); } // Use that d/dx erf(x) = 2/sqrt(pi)*exp(-x^2), // Taylor expand in x^2 and integrate. template <typename T, int Ndeg> static void erf_expand(T * t, const T & a) { gauss_expand<T, Ndeg>(t, a); for (int i = 0; i <= Ndeg; i++) t[i] *= 2 / sqrt(M_PI); tfuns<T, Ndeg>::integrate(t); t[0] = erf(a); } template <typename T, int Ndeg> static void sin_expand(T * t, const T & a) { if (Ndeg > 0) { T s = sin(a), c = cos(a), fac = 1; for (int i = 0; 2 * i < Ndeg; i++) { t[2 * i] = fac * s; fac /= (2 * i + 1); t[2 * i + 1] = fac * c; fac /= -(2 * i + 2); } if (Ndeg % 2 == 0) t[Ndeg] = s * fac; } else { t[0] = sin(a); } } template <typename T, int Ndeg> static void cos_expand(T * t, const T & a) { if (Ndeg > 0) { T s = sin(a), c = cos(a), fac = 1; for (int i = 0; 2 * i < Ndeg; i++) { t[2 * i] = fac * c; fac /= -(2 * i + 1); t[2 * i + 1] = fac * s; fac /= (2 * i + 2); } if (Ndeg % 2 == 0) t[Ndeg] = c * fac; } else { t[0] = cos(a); } } // hyperbolic arcsin function. d/dx asinh(x) = 1/sqrt(1+x^2) // 1 + (a+x)^2 = 1+a^2 + 2ax + x^2 template <typename T, int Ndeg> static void asinh_expand(T * t, const T & a) { T tmp[Ndeg + 1]; tmp[0] = 1 + a * a; if (Ndeg > 0) tmp[1] = 2 * a; if (Ndeg > 1) tmp[2] = 1; for (int i = 3; i <= Ndeg; i++) tmp[i] = 0; pow_expand<T, Ndeg>(t, tmp[0], -0.5); tfuns<T, Ndeg>::compose(t, tmp); tfuns<T, Ndeg>::integrate(t); t[0] = asinh(a); } // arcsin function. d/dx asin(x) = 1/sqrt(1-x^2) // 1 - (a+x)^2 = 1-a^2 - 2ax - x^2 template <typename T, int Ndeg> static void asin_expand(T * t, const T & a) { T tmp[Ndeg + 1]; tmp[0] = 1 - a * a; if (Ndeg > 0) tmp[1] = -2 * a; if (Ndeg > 1) tmp[2] = -1; for (int i = 3; i <= Ndeg; i++) tmp[i] = 0; pow_expand<T, Ndeg>(t, tmp[0], -0.5); tfuns<T, Ndeg>::compose(t, tmp); tfuns<T, Ndeg>::integrate(t); t[0] = asinh(a); } template <typename T, int Ndeg> static void acosh_expand(T * t, const T & a) { asinh_expand(t, a); for (int i = 0; i < Ndeg + 1; i++) t[i] *= -1; } template <typename T, int Ndeg> static void acos_expand(T * t, const T & a) { T tmp[Ndeg + 1]; tmp[0] = 1 - a * a; if (Ndeg > 0) tmp[1] = -2 * a; if (Ndeg > 1) tmp[2] = -1; for (int i = 3; i <= Ndeg; i++) tmp[i] = 0; pow_expand<T, Ndeg>(t, tmp[0], -0.5); tfuns<T, Ndeg>::compose(t, tmp); tfuns<T, Ndeg>::integrate(t); for (int i = 1; i < Ndeg; i++) t[i] *= -1; t[0] = asinh(a); }
27.993976
79
0.48343
uekstrom
3a99ede677208ae57389ce80b9f26d084512adc0
18,131
cpp
C++
srcAmiga/modeler/MUIutility.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
2
2016-04-03T23:57:54.000Z
2019-12-05T17:50:37.000Z
srcAmiga/modeler/MUIutility.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
null
null
null
srcAmiga/modeler/MUIutility.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
2
2015-06-20T19:22:47.000Z
2021-11-15T15:22:14.000Z
/*************** * PROGRAM: Modeler * NAME: MUIutility.cpp * DESCRIPTION: MUI utility functions * AUTHORS: Andreas Heumann * HISTORY: * DATE NAME COMMENT * 10.12.95 ah initial release * 31.01.97 ah added rectangle icon * 21.02.97 ah added edit points icon * 01.05.97 ah added add points icon ***************/ #include <stdio.h> #include <string.h> #include <dos/dos.h> #include <graphics/gfx.h> #include <graphics/gfxmacros.h> #include <graphics/gfxbase.h> #ifdef __STORM__ #include <pragma/graphics_lib.h> #include <pragma/dos_lib.h> #endif #ifndef TYPEDEFS_H #include "typedefs.h" #endif #ifndef MUIDEFS_H #include "MUIdefs.h" #endif #ifndef MUIUTILITY_H #include "MUIutility.h" #endif #ifndef PREFS_H #include "prefs.h" #endif #ifndef UTILITY_H #include "utility.h" #endif #pragma chip static UBYTE newdata[] = { 0x00,0x00,0x00,0x00,0x1f,0xe0,0x10,0x50,0x10,0x48,0x10,0x78,0x10,0x08, 0x10,0x08,0x10,0x08,0x10,0x08,0x10,0x08,0x10,0x08,0x10,0x08,0x1f,0xf8, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x0f,0xa0,0x0f,0xb0,0x0f,0x80,0x0f,0xf0, 0x0f,0xf0,0x0f,0xf0,0x0f,0xf0,0x0f,0xf0,0x0f,0xf0,0x0f,0xf0,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE loaddata[] = { 0x00,0x00,0x00,0x00,0x7f,0xf8,0x60,0x18,0x60,0x18,0x60,0x00,0x60,0x08, 0x60,0x7c,0x7e,0x7e,0x60,0x7f,0x60,0x7e,0x6c,0x1c,0x6c,0x08,0x7f,0xf8, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x5f,0xe8,0x00,0x00,0x1f,0x88,0x00,0x7c, 0x1e,0xfe,0x00,0xff,0x1e,0xfe,0x1e,0x8c,0x13,0x08,0x13,0xc0,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE savedata[] = { 0x00,0x00,0x00,0x00,0x7f,0xf8,0x60,0x18,0x60,0x08,0x60,0x08,0x60,0x10, 0x60,0x3f,0x7f,0x7f,0x60,0x7f,0x60,0x3e,0x6c,0x18,0x6c,0x08,0x7f,0xf8, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x5f,0xe8,0x00,0x00,0x1f,0xd0,0x00,0x3e, 0x1f,0x7e,0x00,0xfe,0x1f,0x3e,0x1f,0x90,0x13,0xc0,0x13,0xc0,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE frontdata[] = { 0x00,0x00,0x00,0x00,0x0f,0xf0,0x0f,0xf0,0x0c,0x00,0x0c,0x00,0x0c,0x00, 0x0f,0xc0,0x0f,0xc0,0x0c,0x00,0x0c,0x00,0x0c,0x00,0x0c,0x00,0x0c,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE rightdata[] = { 0x00,0x00,0x00,0x00,0x0f,0xe0,0x0f,0xf0,0x0c,0x30,0x0c,0x30,0x0c,0x30, 0x0f,0xf0,0x0f,0xe0,0x0f,0x80,0x0d,0xc0,0x0c,0xe0,0x0c,0x70,0x0c,0x30, 0x00,0x00,0x00,0x00, }; static UBYTE topdata[] = { 0x00,0x00,0x00,0x00,0x0f,0xf0,0x0f,0xf0,0x01,0x80,0x01,0x80,0x01,0x80, 0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80, 0x00,0x00,0x00,0x00, }; static UBYTE fourdata[] = { 0x00,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00, 0x7f,0xfe,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00, 0x01,0x00,0x00,0x00, 0x00,0x00,0x3c,0xb8,0x18,0xb4,0x18,0xb8,0x18,0xb0,0x18,0xb0,0x00,0x80, 0x00,0x00,0x7e,0xfe,0x00,0x80,0x3c,0xb8,0x30,0xb4,0x38,0xb8,0x30,0xb8, 0x30,0xb4,0x00,0x00, }; static UBYTE perspdata[] = { 0x00,0x00,0x00,0x00,0x0f,0xe0,0x0f,0xf0,0x0c,0x30,0x0c,0x30,0x0c,0x30, 0x0f,0xf0,0x0f,0xe0,0x0c,0x00,0x0c,0x00,0x0c,0x00,0x0c,0x00,0x0c,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE cameradata[] = { 0x00,0x00,0x00,0x00,0x18,0xc0,0x25,0x20,0x42,0x10,0x42,0x10,0x25,0x20, 0x18,0xc0,0x7f,0xe2,0x40,0x2e,0x40,0x32,0x40,0x22,0x40,0x32,0x40,0x2e, 0x7f,0xe2,0x00,0x00, }; static UBYTE boundingdata[] = { 0x00,0x00,0x7f,0xfe,0x60,0x06,0x50,0x0a,0x4f,0xf2,0x48,0x12,0x48,0x12, 0x48,0x12,0x48,0x12,0x48,0x12,0x48,0x12,0x4f,0xf2,0x50,0x0a,0x60,0x06, 0x7f,0xfe,0x00,0x00, }; static UBYTE wiredata[] = { 0x00,0x00,0x07,0xe0,0x0c,0x70,0x15,0xa8,0x26,0x24,0x7f,0xfe,0x4c,0x66, 0x54,0xaa,0x55,0x2a,0x66,0x32,0x7f,0xfe,0x26,0x24,0x15,0xa8,0x0c,0x70, 0x07,0xe0,0x00,0x00, }; static UBYTE soliddata[] = { 0x00,0x00,0x07,0xe0,0x1a,0xb8,0x20,0x14,0x20,0x2c,0x40,0x06,0x40,0x0a, 0x40,0x06,0x60,0x0a,0x40,0x06,0x68,0x0a,0x30,0x1c,0x2a,0xa4,0x1d,0xd8, 0x07,0xe0,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x40,0x07,0x80,0x17,0x40, 0x0f,0x80,0x15,0x40,0x02,0x00,0x05,0x40,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE rotatedata[] = { 0x00,0x00,0x00,0x00,0x03,0xe0,0x0f,0xf8,0x1f,0x7c,0x1c,0x1c,0x38,0x0e, 0xfe,0x0e,0x7c,0x06,0x38,0x0e,0x10,0x0e,0x04,0x1c,0x1f,0x7c,0x0f,0xf8, 0x03,0xe0,0x00,0x00, }; static UBYTE movedata[] = { 0x00,0x00,0x00,0xfe,0x00,0x7e,0x00,0x3e,0x00,0x7e,0x00,0xfe,0x01,0xf6, 0x03,0xe2,0x47,0xc0,0x6f,0x80,0x7f,0x00,0x7e,0x00,0x7c,0x00,0x7e,0x00, 0x7f,0x00,0x00,0x00, }; static UBYTE scaledata[] = { 0x00,0x00,0x01,0x80,0x07,0xe0,0x1f,0xf8,0x03,0xc0,0x03,0xc0,0x07,0xe0, 0x07,0xe0,0x07,0xe0,0x0f,0xf0,0x0f,0xf0,0x7f,0xfe,0x1f,0xf8,0x07,0xe0, 0x01,0x80,0x00,0x00, }; static UBYTE worldmovedata[] = { 0x00,0x00,0x00,0xfe,0x00,0x7e,0x00,0x3e,0x00,0x7e,0x00,0xfe,0x01,0xfe, 0x02,0x72,0x46,0x52,0x6e,0x72,0x7e,0x52,0x7e,0x02,0x7e,0x22,0x7e,0x52, 0x7f,0x8c,0x00,0x00, 0x00,0x00,0x00,0xfe,0x00,0x7e,0x00,0x3e,0x00,0x7e,0x00,0xfe,0x00,0x72, 0x01,0xac,0x45,0x8c,0x6d,0x8c,0x7d,0xac,0x7d,0xfc,0x7d,0xdc,0x7d,0x8c, 0x7e,0x00,0x00,0x00, }; static UBYTE worldrotatedata[] = { 0x00,0x00,0x00,0x00,0x03,0xe0,0x0f,0xf8,0x1f,0x7c,0x1c,0x1c,0x39,0x8e, 0xfe,0x52,0x7e,0x52,0x3a,0x72,0x12,0x52,0x06,0x02,0x1e,0x22,0x0e,0x72, 0x03,0xec,0x00,0x00, 0x00,0x00,0x00,0x00,0x03,0xe0,0x0f,0xf8,0x1f,0x7c,0x1c,0x1c,0x38,0x02, 0xfd,0x8c,0x7d,0x8c,0x39,0x8c,0x11,0xac,0x05,0xfc,0x1d,0xdc,0x0d,0xac, 0x02,0x60,0x00,0x00, }; static UBYTE worldscaledata[] = { 0x00,0x00,0x01,0x80,0x07,0xe0,0x1f,0xf8,0x03,0xc0,0x03,0xc0,0x07,0xec, 0x06,0x72,0x06,0x72,0x0e,0x72,0x0e,0x52,0x7e,0x02,0x1e,0x22,0x06,0x72, 0x01,0x8c,0x00,0x00, 0x00,0x00,0x01,0x80,0x07,0xe0,0x1f,0xf8,0x03,0xc0,0x03,0xc0,0x06,0x60, 0x05,0xac,0x05,0xac,0x0d,0x8c,0x0d,0xac,0x7d,0xfc,0x1d,0xdc,0x05,0xac, 0x00,0x00,0x00,0x00, }; static UBYTE xdata[] = { 0x00,0x00,0x00,0x00,0x0c,0x30,0x0c,0x30,0x06,0x60,0x06,0x60,0x03,0xc0, 0x01,0x80,0x01,0x80,0x03,0xc0,0x06,0x60,0x06,0x60,0x0c,0x30,0x0c,0x30, 0x00,0x00,0x00,0x00, }; static UBYTE ydata[] = { 0x00,0x00,0x00,0x00,0x0c,0x30,0x0c,0x60,0x06,0x60,0x06,0xc0,0x03,0xc0, 0x03,0x80,0x01,0x80,0x03,0x00,0x03,0x00,0x06,0x00,0x06,0x00,0x0c,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE zdata[] = { 0x00,0x00,0x00,0x00,0x0f,0xf0,0x0f,0xf0,0x00,0x60,0x00,0xc0,0x00,0xc0, 0x01,0x80,0x01,0x80,0x03,0x00,0x03,0x00,0x06,0x00,0x0f,0xf0,0x0f,0xf0, 0x00,0x00,0x00,0x00, }; static UBYTE viewdata[] = { 0x00,0x00,0x07,0xe0,0x09,0xd0,0x17,0xee,0x66,0x36,0x7c,0x1e,0x5c,0x1e, 0x6c,0x1a,0x56,0x36,0x6f,0xfa,0x7f,0xfe,0x00,0x00, 0x00,0x00,0x00,0x00,0x06,0x20,0x08,0x10,0x19,0xc8,0x03,0xe0,0x23,0xe0, 0x03,0xe0,0x01,0xc0,0x00,0x00,0x00,0x00,0x00,0x00, }; static UBYTE rectangledata[] = { 0x00,0x00,0x7f,0xfe,0x40,0x02,0x7f,0xfa,0x40,0x0a,0x7f,0xea,0x40,0x2a, 0x40,0x2a,0x40,0x2a,0x40,0x2a,0x40,0x2a,0x40,0x2a,0x40,0x2a,0x40,0x2a, 0x7f,0xfe,0x00,0x00, }; static UBYTE editpointsdata[] = { 0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE addpointsdata[] = { 0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x38,0x00,0x38,0x06,0x00,0x09,0x00, 0x09,0x00,0x39,0xc0,0x40,0x20,0x40,0x20,0x39,0xe0,0x09,0x00,0x09,0x00, 0x06,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x00,0x06,0x00, 0x06,0x00,0x06,0x00,0x3f,0xc0,0x3f,0xc0,0x06,0x00,0x06,0x00,0x06,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE editedgesdata[] = { 0x00,0x00,0x70,0x00,0x70,0x00,0x78,0x00,0x04,0x00,0x02,0x00,0x01,0x80, 0x00,0x40,0x00,0x20,0x00,0x1e,0x00,0x0e,0x00,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x0e,0x00,0x0e,0x00,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE addedgesdata[] = { 0x00,0x00,0x70,0x00,0x70,0x00,0x78,0x00,0x04,0x00,0x06,0x00,0x09,0x80, 0x09,0x40,0x39,0xe0,0x40,0x3e,0x40,0x2e,0x39,0xee,0x09,0x00,0x09,0x00, 0x06,0x00,0x00,0x00, 0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x06,0x00, 0x06,0x00,0x06,0x00,0x3f,0xce,0x3f,0xce,0x06,0x0e,0x06,0x00,0x06,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE editfacesdata[] = { 0x00,0x00,0x00,0x1c,0x00,0x1c,0x01,0xfc,0x7e,0x08,0x70,0x08,0x70,0x08, 0x0c,0x08,0x02,0x08,0x01,0x08,0x00,0x88,0x00,0x68,0x00,0x1c,0x00,0x1c, 0x00,0x1c,0x00,0x00, 0x00,0x00,0x00,0x1c,0x00,0x1c,0x00,0x1c,0x71,0xf0,0x7f,0xf0,0x7f,0xf0, 0x03,0xf0,0x01,0xf0,0x00,0xf0,0x00,0x70,0x00,0x10,0x00,0x1c,0x00,0x1c, 0x00,0x1c,0x00,0x00, }; static UBYTE addfacesdata[] = { 0x00,0x00,0x00,0x0e,0x00,0x0e,0x00,0xfe,0x3f,0x04,0x3e,0x04,0x39,0x04, 0x09,0x04,0x39,0xc4,0x40,0x24,0x40,0x24,0x39,0xf4,0x09,0x0e,0x09,0x0e, 0x06,0x0e,0x00,0x00, 0x00,0x00,0x00,0x0e,0x00,0x0e,0x00,0x0e,0x38,0xf8,0x39,0xf8,0x36,0xf8, 0x06,0xf8,0x06,0x38,0x3f,0xd8,0x3f,0xd8,0x06,0x08,0x06,0x0e,0x06,0x0e, 0x00,0x0e,0x00,0x00, }; static UBYTE localdata[] = { 0x00,0x00,0x18,0x00,0x3c,0x00,0x7e,0x00,0x18,0x00,0x1b,0xe0,0x19,0xe0, 0x19,0xe0,0x1b,0xe0,0x1f,0x28,0x1e,0x0c,0x1f,0xfe,0x1f,0xfe,0x00,0x0c, 0x00,0x08,0x00,0x00, }; static UBYTE tapefirstdata[] = { 0x00,0x00,0x78,0x42,0x48,0xc6,0x49,0x4a,0x4a,0x52,0x4c,0x62,0x48,0x42, 0x48,0x42,0x48,0x42,0x48,0x42,0x4c,0x62,0x4a,0x52,0x49,0x4a,0x48,0xc6, 0x78,0x42,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x00,0x30,0x84,0x31,0x8c,0x33,0x9c,0x37,0xbc, 0x37,0xbc,0x37,0xbc,0x37,0xbc,0x33,0x9c,0x31,0x8c,0x30,0x84,0x30,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE tapeprevdata[] = { 0x00,0x00,0x01,0x02,0x03,0x06,0x05,0x0a,0x09,0x12,0x11,0x22,0x21,0x42, 0x41,0x82,0x41,0x82,0x21,0x42,0x11,0x22,0x09,0x12,0x05,0x0a,0x03,0x06, 0x01,0x02,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x04,0x06,0x0c,0x0e,0x1c,0x1e,0x3c, 0x3e,0x7c,0x3e,0x7c,0x1e,0x3c,0x0e,0x1c,0x06,0x0c,0x02,0x04,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE tapestopdata[] = { 0x00,0x00,0x7f,0xfe,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02, 0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02, 0x7f,0xfe,0x00,0x00, 0x00,0x00,0x00,0x00,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc, 0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc,0x3f,0xfc, 0x00,0x00,0x00,0x00, }; static UBYTE tapeplaydata[] = { 0x00,0x00,0x10,0x00,0x1c,0x00,0x12,0x00,0x11,0x80,0x10,0x40,0x10,0x30, 0x10,0x08,0x10,0x08,0x10,0x30,0x10,0x40,0x11,0x80,0x12,0x00,0x1c,0x00, 0x10,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0x0e,0x00,0x0f,0x80,0x0f,0xc0, 0x0f,0xf0,0x0f,0xf0,0x0f,0xc0,0x0f,0x80,0x0e,0x00,0x0c,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE tapenextdata[] = { 0x00,0x00,0x40,0x80,0x60,0xc0,0x50,0xa0,0x48,0x90,0x44,0x88,0x42,0x84, 0x41,0x82,0x41,0x82,0x42,0x84,0x44,0x88,0x48,0x90,0x50,0xa0,0x60,0xc0, 0x40,0x80,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x40,0x30,0x60,0x38,0x70,0x3c,0x78, 0x3e,0x7c,0x3e,0x7c,0x3c,0x78,0x38,0x70,0x30,0x60,0x20,0x40,0x00,0x00, 0x00,0x00,0x00,0x00, }; static UBYTE tapelastdata[] = { 0x00,0x00,0x42,0x1e,0x63,0x12,0x52,0x92,0x4a,0x52,0x46,0x32,0x42,0x12, 0x42,0x12,0x42,0x12,0x42,0x12,0x46,0x32,0x4a,0x52,0x52,0x92,0x63,0x12, 0x42,0x1e,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x0c,0x21,0x0c,0x31,0x8c,0x39,0xcc,0x3d,0xec, 0x3d,0xec,0x3d,0xec,0x3d,0xec,0x39,0xcc,0x31,0x8c,0x21,0x0c,0x00,0x0c, 0x00,0x00,0x00,0x00, }; #pragma fast struct Image newimage = { 0,0,16,16,2,(UWORD*)&newdata,0x03,0,NULL }; struct Image loadimage = { 0,0,16,16,2,(UWORD*)&loaddata,0x03,0,NULL }; struct Image saveimage = { 0,0,16,16,2,(UWORD*)&savedata,0x03,0,NULL }; struct Image frontimage = { 0,0,16,16,2,(UWORD*)&frontdata,0x02,0,NULL }; struct Image rightimage = { 0,0,16,16,2,(UWORD*)&rightdata,0x02,0,NULL }; struct Image topimage = { 0,0,16,16,2,(UWORD*)&topdata,0x02,0,NULL }; struct Image perspimage = { 0,0,16,16,2,(UWORD*)&perspdata,0x02,0,NULL }; struct Image cameraimage = { 0,0,16,16,2,(UWORD*)&cameradata,0x02,0,NULL }; struct Image fourimage = { 0,0,16,16,2,(UWORD*)&fourdata,0x03,0,NULL }; struct Image boundingimage = { 0,0,16,16,2,(UWORD*)&boundingdata,0x02,0,NULL }; struct Image wireimage = { 0,0,16,16,2,(UWORD*)&wiredata,0x02,0,NULL }; struct Image solidimage = { 0,0,16,16,2,(UWORD*)&soliddata,0x03,0,NULL }; struct Image rotateimage = { 0,0,16,16,2,(UWORD*)&rotatedata,0x02,0,NULL }; struct Image moveimage = { 0,0,16,16,2,(UWORD*)&movedata,0x02,0,NULL }; struct Image scaleimage = { 0,0,16,16,2,(UWORD*)&scaledata,0x02,0,NULL }; struct Image worldmoveimage = { 0,0,16,16,2,(UWORD*)&worldmovedata,0x03,0,NULL }; struct Image worldrotateimage = { 0,0,16,16,2,(UWORD*)&worldrotatedata,0x03,0,NULL }; struct Image worldscaleimage = { 0,0,16,16,2,(UWORD*)&worldscaledata,0x03,0,NULL }; struct Image ximage = { 0,0,16,16,2,(UWORD*)&xdata,0x02,0,NULL }; struct Image yimage = { 0,0,16,16,2,(UWORD*)&ydata,0x02,0,NULL }; struct Image zimage = { 0,0,16,16,2,(UWORD*)&zdata,0x02,0,NULL }; struct Image viewimage = { 0,0,16,12,2,(UWORD*)&viewdata,0x03,0,NULL }; struct Image rectangleimage = { 0,0,16,16,2,(UWORD*)&rectangledata,0x02,0,NULL }; struct Image editpointsimage = { 0,0,16,16,2,(UWORD*)&editpointsdata,0x03,0,NULL }; struct Image addpointsimage = { 0,0,16,16,2,(UWORD*)&addpointsdata,0x03,0,NULL }; struct Image editedgesimage = { 0,0,16,16,2,(UWORD*)&editedgesdata,0x03,0,NULL }; struct Image addedgesimage = { 0,0,16,16,2,(UWORD*)&addedgesdata,0x03,0,NULL }; struct Image editfacesimage = { 0,0,16,16,2,(UWORD*)&editfacesdata,0x03,0,NULL }; struct Image addfacesimage = { 0,0,16,16,2,(UWORD*)&addfacesdata,0x03,0,NULL }; struct Image localimage = { 0,0,16,16,2,(UWORD*)&localdata,0x02,0,NULL }; struct Image tapefirstimage = { 0,0,16,16,2,(UWORD*)&tapefirstdata,0x03,0,NULL }; struct Image tapeprevimage = { 0,0,16,16,2,(UWORD*)&tapeprevdata,0x03,0,NULL }; struct Image tapestopimage = { 0,0,16,16,2,(UWORD*)&tapestopdata,0x03,0,NULL }; struct Image tapeplayimage = { 0,0,16,16,2,(UWORD*)&tapeplaydata,0x03,0,NULL }; struct Image tapenextimage = { 0,0,16,16,2,(UWORD*)&tapenextdata,0x03,0,NULL }; struct Image tapelastimage = { 0,0,16,16,2,(UWORD*)&tapelastdata,0x03,0,NULL }; /************* * DESCRIPTION: do a new for superclass * INPUT: cl class * obj object * tag1... tags * OUTPUT: *************/ #ifndef __PPC__ ULONG DoSuperNew(struct IClass *cl,Object *obj,ULONG tag1,...) { return(DoSuperMethod(cl,obj,OM_NEW,&tag1,NULL)); } #endif /************* * DESCRIPTION: get attribute of object * INPUT: obj object * attribute attribute * OUTPUT: value *************/ LONG xget(Object *obj,ULONG attribute) { ULONG x; GetAttr(attribute,obj,&x); return(x); } /************* * DESCRIPTION: Converts float value to a string and removes trailing zeros * INPUT: value value to convert * str result string * OUTPUT: - *************/ void Float2String(const float v,char *str) { int i; sprintf(str, "%.4f", v); i = strlen(str) - 1; while(str[i] == '0') // remove all trailing zeros { str[i] = 0; i--; } if(str[i] == '.') // also remove '.' if no numbers left str[i] = 0; } /************* * DESCRIPTION: Sets the color of a color field * INPUT: cf color field to set * color color to set to * OUTPUT: - *************/ void SetColorField(Object *cf, COLOR *color) { ULONG t; ULONG red,green,blue; #ifdef __STORM__ t = (ULONG)(color->r*255.f); #else t = (ULONG)(color->r*255.f+.5f); #endif red = t + (t<<8) + (t<<16) + (t<<24); #ifdef __STORM__ t = (ULONG)(color->g*255.f); #else t = (ULONG)(color->g*255.f+.5f); #endif green = t + (t<<8) + (t<<16) + (t<<24); #ifdef __STORM__ t = (ULONG)(color->b*255.f); #else t = (ULONG)(color->b*255.f+.5f); #endif blue = t + (t<<8) + (t<<16) + (t<<24); SetAttrs(cf, MUIA_Colorfield_Red, red, MUIA_Colorfield_Green, green, MUIA_Colorfield_Blue, blue, TAG_DONE); } /************* * DESCRIPTION: Gets the color of a color field * INPUT: cf color field to set * color color to set to * OUTPUT: - *************/ void GetColorField(Object *cf, COLOR *color) { ULONG col; GetAttr(MUIA_Colorfield_Red,cf,&col); color->r = float(col>>24)/255.f; GetAttr(MUIA_Colorfield_Green,cf,&col); color->g = float(col>>24)/255.f; GetAttr(MUIA_Colorfield_Blue,cf,&col); color->b = float(col>>24)/255.f; } /************* * DESCRIPTION: view a picture with preslected viewer * INPUT: obj MUI object * file file to view * OUTPUT: - *************/ void ViewPicture(Object *obj, char *file) { char buffer[256]; PREFS p; LONG err; if(!strlen(file)) { utility.Request("No picture specified."); return; } p.id = ID_VIEW; if(!p.GetPrefs()) { utility.Request("No viewer specified.\nUse 'Settings/Prefs' to set the viewer."); return; } sprintf(buffer, "run %s \"%s\"", p.data, file); p.data = NULL; err = SystemTags(buffer, TAG_DONE); if(err) { Fault(err, "Unable to start viewer", buffer, 255); utility.Request(buffer); return; } } /************* * DESCRIPTION: replacement of V39 FreeBitMap() * INPUT: bm bitmap * OUTPUT: - *************/ void NewFreeBitMap(struct BitMap *bm) { int i; if(bm) { for(i=0; i<bm->Depth; i++) { if(bm->Planes[i]) FreeRaster(bm->Planes[i], bm->BytesPerRow, bm->Rows); } delete bm; } } /************* * DESCRIPTION: replacement of V39 AllocBitMap() * INPUT: width,height,depth * OUTPUT: bitmap *************/ struct BitMap *NewAllocBitMap(int width, int height, int depth) { int i; struct BitMap *bm; bm = new struct BitMap; if(!bm) return 0; InitBitMap(bm, width, height, depth); for(i=0; i<depth; i++) { bm->Planes[i] = (PLANEPTR)AllocRaster(width, height); if(!bm->Planes[i]) { NewFreeBitMap(bm); return 0; } } return bm; }
26.12536
83
0.696376
privatosan
3a9cd0887fb90d3989d0fc032dd48bffbf1f663f
856
hpp
C++
lumino/Graphics/src/RHIs/RHIBitmap.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
113
2020-03-05T01:27:59.000Z
2022-03-28T13:20:51.000Z
lumino/Graphics/src/RHIs/RHIBitmap.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/Graphics/src/RHIs/RHIBitmap.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
12
2020-12-21T12:03:59.000Z
2021-12-15T02:07:49.000Z
#pragma once #include "GraphicsDeviceContext.hpp" namespace ln { namespace detail { class RHIBitmap : public RHIRefObject { public: RHIBitmap(); bool init(int32_t elementSize, int32_t width, int32_t height); void initWrap(const void* data, int32_t elementSize, int32_t width, int32_t height); void initWritableWrap(void* data, int32_t elementSize, int32_t width, int32_t height); uint8_t* writableData() { return m_writablePtr; } const uint8_t* data() const { return m_ptr; } int32_t width() const { return m_width; } int32_t height() const { return m_height; } void blit(const RHIBitmap* srcBitmap); void copyRaw(const void* data, size_t size); private: std::vector<uint8_t> m_data; const uint8_t* m_ptr; uint8_t* m_writablePtr; int32_t m_elementSize; int32_t m_width; int32_t m_height; }; } // namespace detail } // namespace ln
23.777778
87
0.75
GameDevery
3a9e127cc82b99089cb38f35fa460947a5c55b2e
834
hpp
C++
worker/include/DepOpenSSL.hpp
kicyao/mediasoup
ca8e2d5b57aa2b0d1e5812bb28782d858cd669c6
[ "0BSD" ]
null
null
null
worker/include/DepOpenSSL.hpp
kicyao/mediasoup
ca8e2d5b57aa2b0d1e5812bb28782d858cd669c6
[ "0BSD" ]
null
null
null
worker/include/DepOpenSSL.hpp
kicyao/mediasoup
ca8e2d5b57aa2b0d1e5812bb28782d858cd669c6
[ "0BSD" ]
null
null
null
#ifndef MS_DEP_OPENSSL_HPP #define MS_DEP_OPENSSL_HPP #include "common.hpp" #include <openssl/ssl.h> #include <openssl/crypto.h> #include <uv.h> /* OpenSSL doc: struct CRYPTO_dynlock_value has to be defined by the application. */ struct CRYPTO_dynlock_value { uv_mutex_t mutex; }; class DepOpenSSL { public: static void ClassInit(); static void ClassDestroy(); private: static void SetThreadId(CRYPTO_THREADID* id); static void LockingFunction(int mode, int n, const char *file, int line); static CRYPTO_dynlock_value* DynCreateFunction(const char* file, int line); static void DynLockFunction(int mode, CRYPTO_dynlock_value* v, const char* file, int line); static void DynDestroyFunction(CRYPTO_dynlock_value* v, const char* file, int line); private: static uv_mutex_t* mutexes; static uint32_t numMutexes; }; #endif
24.529412
92
0.775779
kicyao
3aa674fa2920d55cf37bc0e0513412c4e31bea42
8,701
cpp
C++
src/ui/graphics/sprite.cpp
Aalexdev/seasfarer-s-war
6d4ea641f7dd914c7ce74d70fcae8810af6ea00a
[ "MIT" ]
4
2020-10-30T09:03:35.000Z
2021-07-20T12:35:51.000Z
src/ui/graphics/sprite.cpp
Aalexdev/seasfarer-s-war
6d4ea641f7dd914c7ce74d70fcae8810af6ea00a
[ "MIT" ]
null
null
null
src/ui/graphics/sprite.cpp
Aalexdev/seasfarer-s-war
6d4ea641f7dd914c7ce74d70fcae8810af6ea00a
[ "MIT" ]
null
null
null
#include "ui/graphics/sprite.hpp" #include "main.hpp" Sprite_type::Sprite_type(){ if (IS_LOG_OPEN) LOG << "Sprite_type::Sprite_type()" << endl; this->sprite = nullptr; this->isLoaded = false; this->children.clear(); } Sprite_type::~Sprite_type(){ if (IS_LOG_OPEN) LOG << "Sprite_type::~Sprite_type" << endl; if (this->sprite) SDL_DestroyTexture(this->sprite); this->children.clear(); } bool Sprite_type::load_from_xml(XMLNode* node){ if (IS_LOG_OPEN) LOG << "Sprite_type::load_from_xml" << endl; if (!node){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite::load_from_xml, reason : cannot load a null node" << endl; return false; } for (int a=0; a<node->attributes.size; a++){ XMLAttribute attr = node->attributes.data[a]; if (!strcmp(attr.key, "name")){ this->name = attr.value; } else if (!strcmp(attr.key, "id")){ sscanf(attr.value, "%d", &this->id); } else if (!strcmp(attr.key, "image")){ this->sprite = loadTexture(attr.value, &this->dstRect); if (!this->sprite){ return false; } } else if (!strcmp(attr.key, "width")){ sscanf(attr.value, "%d", &this->width); } else if (!strcmp(attr.key, "height")){ sscanf(attr.value, "%d", &this->height); } else { if (IS_ERR_OPEN) ERR << "WARNING :: Sprite_type::load_from_xml, reason :: cannot reconize '" << attr.key << "' sprite attribute" << endl; } } return this->reload(); } bool Sprite_type::reload(void){ if (IS_LOG_OPEN) LOG << "Sprite_type::reload" << endl; if (!this->sprite){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_type::reload, reason : cannot reload a null sprite image" << endl; return false; } if (this->dstRect.w <= 0){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_type::reload, reason : cannot reaload a sprite without image width" << endl; return false; } if (this->dstRect.h <= 0){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_type::reload, reason : cannot reload a sprite without image height" << endl; return false; } int x=0, y=0; while (true){ Sprite_child* child = new Sprite_child(); child->setX(x); child->setY(y); child->setW(this->width); child->setH(this->height); this->children.push_back(child); x += this->width; if (x >= this->dstRect.w){ y += this->height; x = 0; } if (y >= this->dstRect.h){ break; } } return true; } SDL_Rect Sprite_type::getIndex(int index){ if (this->children.size() <= index){ if (IS_ERR_OPEN) ERR << "WARNING :: Sprite_type::getIndex, reason : the input index is greater than the sprite" << endl; index = this->children.size() - 1; } SDL_Rect output = this->children[index]->getRect(); return output; } bool Sprite_list::read_from_xml(XMLNode* node){ if (IS_LOG_OPEN) LOG << "Sprite_list::read_from_xml" << endl; if (!node){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_list::read_from_xml, reason : cannot load a null XMLNode" << endl; return false; } for (int c=0; c<node->children.size; c++){ XMLNode* sprite = XMLNode_child(node, c); if (!strcmp(sprite->tag, "sprite")){ Sprite_type *type = new Sprite_type(); if (type->load_from_xml(sprite)){ this->children.push_back(type); } else { delete type; } } else { if (IS_ERR_OPEN) ERR << "ERROR :: cannot reconize '" << sprite->tag << "' sprites children" << endl; } } return true; } Sprite_type* Sprite_list::search(string name){ if (IS_LOG_OPEN) LOG << "Sprite_list::search(" << name << ")" << endl; if (this->children.empty()){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_list::search, reason : cannot search a type in a empty list" << endl; return nullptr; } for (Sprite_type* type : this->children){ if (type->getName() == name){ return type; } } if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_list::search, reason : cannot found '" << name << "' type name" << endl; return nullptr; } Sprite_type* Sprite_list::search(int id){ if (IS_LOG_OPEN) LOG << "Sprite_list::search(" << id << ")" << endl; if (this->children.empty()){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_list::search, reason : cannot search a type in a empty list" << endl; return nullptr; } for (Sprite_type* type : this->children){ if (type->get_id() == id){ return type; } } if (IS_ERR_OPEN) ERR << "ERROR :: Sprite_list::search, reason : cannot found '" << id << "' type name" << endl; return nullptr; } Sprite::Sprite(Sprite_list* list) : list(list){ this->type = nullptr; this->duration = 0; this->angle = 0; this->index = 0; this->ticks = 0; this->update = true; } Sprite::Sprite(){ this->list = nullptr; this->type = nullptr; this->duration = 0; this->angle = 0; this->index = 0; this->ticks = 0; this->update = true; } Sprite::~Sprite(){ this->duration = 0; this->ticks = 0; this->type = 0; this->list = 0; this->index = 0; } void Sprite::setList(Sprite_list* list){ this->list = list; } bool Sprite::set(int id){ if (IS_LOG_OPEN) LOG << "Sprite::set(" << id << ")" << endl; if (!this->list){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite::set, reason : cannot set a sprite without list" << endl; return false; } this->type = this->list->search(id); if (!this->type) return false; return true; } bool Sprite::set(string name){ if (IS_LOG_OPEN) LOG << "Sprite::set(" << name << ")" << endl; if (!this->list){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite::set, reason : cannot set a sprite without list" << endl; return false; } this->type = this->list->search(name); if (!type) return false; return true; } void Sprite::set(Sprite_type* type){ if (IS_LOG_OPEN) LOG << "Sprite::set(Sprite_type* type)" << endl; this->type = type; } Sprite_type* Sprite::get_type(void){ if (IS_LOG_OPEN) LOG << "Sprite::get_type" << endl; return this->type; } int Sprite::get_id(void){ if (IS_LOG_OPEN) LOG << "Sprite::get_id" << endl; if (this->type){ return this->type->get_id(); } return 0; } string Sprite::get_name(void){ if (IS_LOG_OPEN) LOG << "sprite::get_name" << endl; if (this->type){ return this->type->getName(); } return ""; } bool Sprite::draw(void){ if (!this->type){ if (IS_ERR_OPEN) ERR << "ERROR :: sprite::draw, reason : cannot draw a sprite without image" << endl; return false; } if (this->update){ if (SDL_GetTicks() - this->duration >= this->ticks){ this->ticks = SDL_GetTicks(); this->index++; if (this->index >= this->type->getSize()){ this->index = 0; } } } SDL_Rect tempRect = this->type->getIndex(this->index); if (SDL_RenderCopyEx(RENDERER, this->type->getTexture(), &tempRect, &this->rect, this->angle, 0, SDL_FLIP_NONE)){ if (IS_ERR_OPEN) ERR << "ERROR :: SDL_RenderCopyEx, reason : " << SDL_GetError() << endl; } return true; } bool Sprite::is_Init(void){ return (this->type); } bool Sprite::read_from_xml(XMLNode* node){ if (!node){ if (IS_ERR_OPEN) ERR << "ERROR :: Sprite::read_from_xml, reason : cannot read a null node" << endl; return false; } for (int a=0; a<node->attributes.size; a++){ XMLAttribute attr = node->attributes.data[a]; if (!strcmp(attr.key, "x")){ sscanf(attr.value, "%d", &this->rect.x); } else if (!strcmp(attr.key, "y")){ sscanf(attr.value, "%d", &this->rect.y); } else if (!strcmp(attr.key, "w")){ sscanf(attr.value, "%d", &this->rect.w); } else if (!strcmp(attr.key, "h")){ sscanf(attr.value, "%d", &this->rect.h); } else if (!strcmp(attr.key, "duration")){ sscanf(attr.value, "%d", &this->duration); } else if (!strcmp(attr.value, "id")){ int id; sscanf(attr.value, "%d", &id); this->type = this->list->search(id); } else if (!strcmp(attr.key, "name")){ this->type = this->list->search(attr.value); } } return true; }
28.527869
149
0.55212
Aalexdev
3aa84bdbed3b5b3f3d141c758437a52c5de63394
5,984
hpp
C++
include/FakeInput/actions/actionsequence.hpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
40
2016-11-18T06:14:47.000Z
2022-03-16T14:36:21.000Z
include/FakeInput/actions/actionsequence.hpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
null
null
null
include/FakeInput/actions/actionsequence.hpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
9
2017-01-23T01:49:41.000Z
2020-11-05T13:09:56.000Z
/** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka <uiii.dev@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_ACTIONSEQUENCE_HPP #define FI_ACTIONSEQUENCE_HPP #include "action.hpp" #include "keyaction.hpp" #include "mouseaction.hpp" #include "commandaction.hpp" #include "waitaction.hpp" #include <list> namespace FakeInput { /** Represents a sequence of actions. */ class ActionSequence : public Action { typedef std::list<Action*> ActionList; public: /** ActionSequence constructor. */ ActionSequence(); /** ActionSequence copy-constructor. */ ActionSequence(const ActionSequence& anotherSequence); /** ActionSequence destructor. */ virtual ~ActionSequence(); /** Creates new copy of this action sequence. * * @returns * New copy of this action sequence allocated on heap. */ Action* clone() const; /** Adds another sequence to the end of this sequence. * * So all actions from another sequence will be performed * after all action before it in this sequence * * @param anotherSequence * Another sequence to join * * @returns * The referece to this action */ ActionSequence& join(ActionSequence& anotherSequence); /** Adds key press action to the end of this sequence. * * @param key * The key to press * * @returns * The referece to this action */ ActionSequence& press(Key key); /** Adds key press action to the end of this sequence. * * @param keyType * The keyType of key to press * * @returns * The referece to this action */ ActionSequence& press(KeyType keyType); /** Adds mouse press action to the end of this sequence. * * @param button * The mouse button to press * * @returns * The referece to this action */ ActionSequence& press(MouseButton button); /** Adds key release action to the end of this sequence. * * @param key * The key to release * * @returns * The referece to this action */ ActionSequence& release(Key key); /** Adds key release action to the end of this sequence. * * @param keyType * The keyType of key to release * * @returns * The referece to this action */ ActionSequence& release(KeyType keyType); /** Adds mouse release action to the end of this sequence. * * @param button * The mouse button to release * * @returns * The referece to this action */ ActionSequence& release(MouseButton button); /** Adds mouse relative motion action to the end of this sequence. * * @param dx * Amount of pixels to move on X axis * @param dy * Amount of pixels to move on Y axis * * @returns * The referece to this action */ ActionSequence& moveMouse(int dx, int dy); /** Adds mouse absolute motion action to the end of this sequence. * * @param x * Where to move on X axis * @param y * Where to move on Y axis * * @returns * The referece to this action */ ActionSequence& moveMouseTo(int x, int y); /** Adds mouse wheel up action to the end of this sequence. * * @returns * The referece to this action */ ActionSequence& wheelUp(); /** Adds mouse wheel down action to the end of this sequence. * * @returns * The referece to this action */ ActionSequence& wheelDown(); /** Adds command run action to the end of this sequence. * * @param cmd * Command to run * * @returns * The referece to this action */ ActionSequence& runCommand(const std::string& cmd); /** Adds wait action to the end of this sequence. * * @param milisec * Time to wait in milisecods * * @returns * The referece to this action */ ActionSequence& wait(unsigned int milisec); /** Performs all actions in sequence. */ void send() const; private: /** List of actions in this sequence. */ ActionList actions_; }; } #endif
29.623762
81
0.571691
perara-libs
3aa9735699e5c7de887bf547b80ffe52c842bf21
2,651
hpp
C++
libraries/include/Engine/ShaderProgram.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
3
2015-04-25T22:57:58.000Z
2019-11-05T18:36:31.000Z
libraries/include/Engine/ShaderProgram.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
1
2016-06-23T15:22:41.000Z
2016-06-23T15:22:41.000Z
libraries/include/Engine/ShaderProgram.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
null
null
null
#ifndef SHADERPROGRAM_H #define SHADERPROGRAM_H #include <unordered_map> #include <glm/glm.hpp> #include <Engine/NonCopyable.hpp> #include <Engine/Shader.hpp> namespace Engine { class ShaderProgram : private NonCopyable { public: /** * Constructor. */ ShaderProgram(); /** * Destructor. */ virtual ~ShaderProgram(); /** * Attaches the specified shader to the program. * * @param shader Reference to the shader to attach. */ void AttachShader(const Shader& shader); /** * Links the shader program. * * @return True if the program was linked successfully. */ bool Link(); /** * Use the shader program. */ void Use() const; /** * Sets the uniform specified by the provided name with the 4x4 matrix * of floating point values. * * @param name Name for the uniform to set. * @param matrix Matrix value to assign to the uniform. */ void SetUniformMatrix4fv(std::string name, const glm::mat4& matrix); /** * Sets the uniform specified by the provided name with the 3x3 matrix * of floating point values. * * @param name Name for the uniform to set. * @param matrix Matrix value to assign to the uniform. */ void SetUniformMatrix3fv(std::string name, const glm::mat3& matrix); /** * Sets the uniform specified by the provided name with the 3-dimensional * vector of floating point values. * * @param name Name for the uniform to set. * @param matrix Vector value to assign to the uniform. */ void SetUniform3fv(std::string name, const glm::vec3& vector); /** * Sets the uniform specified by the provided name with the floating * point value. * * @param name Name for the uniform to set. * @param matrix Floating point value to assign to the uniform. */ void SetUniform1f(std::string name, float value); /** * Sets the uniform specified by the provided name with the integer * value. * * @param name Name for the uniform to set. * @param matrix Integer value to assign to the uniform. */ void SetUniform1i(std::string name, int value); /** * Returns the location of the uniform specified by the provided name. * * @param name Name for the uniform. * @return Uniform location. */ GLint GetUniformLocation(std::string name); /** * Returns the OpenGL identifier for the shader program. * * @return OpenGL object identifier. */ GLuint GetId() const; private: /** * Program identifier. */ GLuint m_id; /** * Cache for uniform locations. */ std::unordered_map<std::string, GLint> m_uniformLocationCache; }; } #endif
22.277311
75
0.665032
kermado
3aac6bd160c43e86a209ffa0e5ababdda92f8f95
3,072
cpp
C++
src/2dpoly_to_3d/point.cpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
src/2dpoly_to_3d/point.cpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
src/2dpoly_to_3d/point.cpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
/* * File: point.cpp * -------------------- * Author: Matyalatte * Last updated: 2021/09/25 */ #include "point.hpp" #include <cmath> namespace graph { point::point(double px, double py, double pz, size_t id) { x = px; y = py; z = pz; index = id; } void point::setXYZ(double px, double py, double pz) { x = px; y = py; z = pz; } double point::getX() { return x; } double point::getY() { return y; } double point::getZ() { return z; } void point::setZ(double pz) { z = pz; } void point::setID(size_t id) { index = id; } size_t point::getID() { return index; } //c->a X c->b double crossprod2D(point* a, point* b, point* c) { return (a->getX() - c->getX()) * (b->getY() - c->getY()) - (b->getX() - c->getX()) * (a->getY() - c->getY()); }; void calNormal(point* a, point* b, point* c, double* normal) { double ax = a->getX() - c->getX(); double ay = a->getY() - c->getY(); double az = a->getZ() - c->getZ(); double bx = b->getX() - c->getX(); double by = b->getY() - c->getY(); double bz = b->getZ() - c->getZ(); normal[0] = ay * bz - az * by; normal[1] = az * bx - ax * bz; normal[2] = ax * by - ay * bx; double d = sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]); normal[0] = normal[0] / d; normal[1] = normal[1] / d; normal[2] = normal[2] / d; } //c->a * c->b double innerprod2D(point* a, point* b, point* c) { return (a->getX() - c->getX()) * (b->getX() - c->getX()) + (b->getY() - c->getY()) * (a->getY() - c->getY()); }; //|a->b|^2 double squaredDistance(point* a, point* b) { double x = a->getX() - b->getX(); double y = a->getY() - b->getY(); return x * x + y * y; } //|a->b| double distance(point* a, point* b) { return sqrt(squaredDistance(a, b)); } //square p1->p2->p3->p4->p1 is convex or not bool isConvexSquare(point* p1, point* p2, point* p3, point* p4) { return (crossprod2D(p1, p2, p3) > 0) == (crossprod2D(p2, p3, p4) > 0) == (crossprod2D(p3, p4, p1) > 0) == (crossprod2D(p4, p1, p2) > 0); } //edge p1->p2 crosses edge p3->p4 or not bool isCross(point* p1, point* p2, point* p3, point* p4) { return (crossprod2D(p2, p3, p1) * crossprod2D(p2, p4, p1) < 0) && (crossprod2D(p4, p1, p3) * crossprod2D(p4, p2, p3) < 0); } //mid point between p1 and p2 point* mid(point* p1, point* p2) { return new point((p1->getX() + p2->getX()) / 2, (p1->getY() + p2->getY()) / 2); } //center point of the set (p1, p2, p3) point* center(point* p1, point* p2, point* p3) { point* p = new point((p1->getX() + p2->getX() + p3->getX()) / 3, (p1->getY() + p2->getY() + p3->getY()) / 3); return p; } //target is in a circle or not. p1 and p2 are on the circle. p1->p2 is the diameter of the circle bool isInCircle(point* target, point* p1, point* p2) { point* p = mid(p1, p2); double centerX = (p1->getX() + p2->getX()) / 2; double centerY = (p1->getY() + p2->getY()) / 2; double radius = distance(p1, p2) / 2; bool ret = (distance(p, target) <= radius); delete p; return ret; } }
24.774194
111
0.546875
matyalatte
3aaf0d003642251317385621d891ec4da60cea55
7,647
hpp
C++
opt/nomad/src/Type/StepType.hpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
31
2019-02-05T16:39:18.000Z
2022-03-11T23:14:11.000Z
opt/nomad/src/Type/StepType.hpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
20
2020-04-13T09:22:53.000Z
2021-08-16T16:14:13.000Z
opt/nomad/src/Type/StepType.hpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
6
2020-04-21T17:43:47.000Z
2021-03-10T04:12:34.000Z
/*---------------------------------------------------------------------------------*/ /* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */ /* */ /* NOMAD - Version 4 has been created by */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* The copyright of NOMAD - version 4 is owned by */ /* Charles Audet - Polytechnique Montreal */ /* Sebastien Le Digabel - Polytechnique Montreal */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */ /* NSERC (Natural Sciences and Engineering Research Council of Canada), */ /* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */ /* for Data Valorization) */ /* */ /* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */ /* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */ /* and Exxon Mobil. */ /* */ /* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */ /* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */ /* Exxon Mobil. */ /* */ /* Contact information: */ /* Polytechnique Montreal - GERAD */ /* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ /* e-mail: nomad@gerad.ca */ /* */ /* This program 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 3 of the License, or (at your */ /* option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, but WITHOUT */ /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */ /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License */ /* for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* You can find information on the NOMAD software at www.gerad.ca/nomad */ /*---------------------------------------------------------------------------------*/ /** \file StepType.hpp \brief Types for Steps that generate points: Search and Poll methods, and Algorithms \author Viviane Rochon Montplaisir \date June 2021 \see StepType.cpp */ #ifndef __NOMAD_4_0_STEP_TYPE__ #define __NOMAD_4_0_STEP_TYPE__ #include <map> #include <sstream> #include <vector> #include "../nomad_nsbegin.hpp" enum class StepType { ALGORITHM_LH, ///< Algorithm Latin Hypercube ALGORITHM_MADS, ///< Algorithm Mads ALGORITHM_NM, ///< Algorithm Nelder-Mead ALGORITHM_PHASE_ONE, ///< Phase One ALGORITHM_PSD_MADS_SUBPROBLEM, ///< Subproblem in PSD-Mads ALGORITHM_PSD_MADS, ///< Algorithm PSD-Mads ALGORITHM_QUAD_MODEL, ///< Algorithm Quad Model ALGORITHM_SGTELIB_MODEL, ///< Algorithm Quad Model ALGORITHM_SSD_MADS, ///< Algorithm SSD-Mads ALGORITHM_VNS_MADS, ///< Algorithm VNS-Mads INITIALIZATION, ///< Initialization step ITERATION, ///< Iteration step MAIN, ///< Main step MAIN_OBSERVE, ///< Main step for Observe MAIN_SUGGEST, ///< Main step for Suggest MEGA_ITERATION, ///< MegaIteration step MEGA_SEARCH_POLL, ///< MegaSearchPoll NM_CONTINUE, ///< NM continue NM_EXPAND, ///< NM Expansion NM_INITIAL, ///< NM initial step type NM_INITIALIZE_SIMPLEX, ///< NM initialize simplex NM_INSERT_IN_Y, ///< NM insert in Y NM_INSIDE_CONTRACTION, ///< NM Inside Contraction NM_OUTSIDE_CONTRACTION, ///< NM Outside Contraction NM_REFLECT, ///< NM Reflect NM_SHRINK, ///< NM Shrink NM_UNSET, ///< NM step type not set OPTIMIZE, ///< Sub-optimization POLL, ///< Poll POLL_METHOD_DOUBLE, ///< Double poll method POLL_METHOD_ORTHO_NPLUS1_NEG, ///< Ortho N+1 neg poll method POLL_METHOD_ORTHO_2N, ///< Ortho 2N poll method POLL_METHOD_SINGLE, ///< Single poll method POLL_METHOD_UNI_NPLUS1, ///< Uniform N+1 poll method SEARCH, ///< Search SEARCH_METHOD_LH, ///< Latin hypercube search method SEARCH_METHOD_NM, ///< Nelder-Mead search method SEARCH_METHOD_QUAD_MODEL, ///< Quadratic model search method SEARCH_METHOD_SGTELIB_MODEL,///< Sgtelib model search method SEARCH_METHOD_SPECULATIVE, ///< Speculative search method SEARCH_METHOD_USER, ///< User-defined search method SEARCH_METHOD_VNS_MADS, ///< VNS Mads search method SURROGATE_EVALUATION, ///< Evaluating trial points using static surrogate TERMINATION, ///< Termination UNDEFINED, ///< Unknown value (default) UPDATE ///< Update step }; /// Definition for a vector of StepTypes typedef std::vector<StepType> StepTypeList; /// Helper to test if a StepType represents an Algorithm (ALGORITHM_MADS, etc). bool isAlgorithm(const StepType& stepType); std::map<StepType, std::string>& dictStepType(); // Convert an StepType to a string std::string stepTypeToString(const StepType& stepType); // Convert a StepTypeList to a string; show only pertinent information. std::string StepTypeListToString(const StepTypeList& stepTypeList); inline std::ostream& operator<<(std::ostream& out, const StepType &stepType) { out << stepTypeToString(stepType); return out; } #include "../nomad_nsend.hpp" #endif // __NOMAD_4_0_STEP_TYPE__
54.234043
86
0.490911
scikit-quant
3aaf166a74a825a8ecf6151016548aceb26344b0
1,272
cpp
C++
ConsoleApplication1/Warrior.cpp
ghostinthecamera/FightClub
034a8e5ff260f84396b55a9533f214d5ed6d9d67
[ "BSD-2-Clause" ]
null
null
null
ConsoleApplication1/Warrior.cpp
ghostinthecamera/FightClub
034a8e5ff260f84396b55a9533f214d5ed6d9d67
[ "BSD-2-Clause" ]
null
null
null
ConsoleApplication1/Warrior.cpp
ghostinthecamera/FightClub
034a8e5ff260f84396b55a9533f214d5ed6d9d67
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <sstream> #include "Warrior.h" using namespace std; int Warrior::numberofWarriors = 0; //initialise this one Warrior::Warrior() { this->name = "Default"; this->attack = 0; this->defense = 0; this->health = 0; } void Warrior::setWarriorAttributes(string name, double attack, double defense, double health) { this->name = name; this->attack = attack; this->defense = defense; this->health = health; numberofWarriors++; } Warrior::Warrior(string uname, double att, double def, double hp) : name(uname), attack(att), defense(def), health(hp) { numberofWarriors++; } void Warrior::DebugString() { cout << "User created warrior " << this->name << " has an attack of " << this->attack << " a defence of " << this->defense << " and " << this->health << "hp." << "\n"; } double Warrior::AttackVal() { random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0.1, 1.0); double attackMod = dis(gen); return this->attack * attackMod; } double Warrior::DefendVal() { random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0.1, 1.0); double defendMod = dis(gen); return this->defense * defendMod; } Warrior::~Warrior() { #ifdef DEBUG cout << this->name << " has been destroyed" << "\n"; #endif }
23.127273
142
0.669811
ghostinthecamera
3aaf272de0543c9b87cec1e34c5364d2d37163b2
3,594
cpp
C++
lz5.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
7
2018-04-08T15:01:59.000Z
2022-02-27T12:13:19.000Z
lz5.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2017-04-23T15:27:37.000Z
2017-04-24T05:38:18.000Z
lz5.cpp
CaptainDreamcast/libtari
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2020-04-24T04:21:00.000Z
2020-04-24T04:21:00.000Z
// blatantly "borrowed" from https://github.com/bmarquismarkail/SFFv2 #include "prism/lz5.h" static void naivememcpy(uint8_t* dst, uint32_t *dstpos, uint32_t ofs, uint32_t len) { int run; for (run = len; run > 0; run--) { dst[*dstpos] = dst[((*dstpos) - ofs)]; (*dstpos)++; } } static void copyLZ(uint8_t* dst, uint32_t* dstpos, uint32_t ofs, uint32_t len) { naivememcpy(dst, dstpos, ofs, len); } static uint32_t processSLZ(uint8_t* dst, const uint8_t* src, uint32_t* dstpos, uint32_t* srcpos, uint8_t *recyclebyte, uint8_t* recyclecount) { //Process a short LZ packet. (*recyclebyte) |= ((src[*srcpos] & 0xC0) >> ((*recyclecount) * 2)); (*recyclecount)++; //the answer used to determine the short packet is the copy length. //check and see if this is the forth short LZ packet being processed. if (*recyclecount == 4) { //if so, the recycle buffer has the offset of decompressed data for copying. copyLZ(dst, dstpos, ((*recyclebyte) + 1), (src[*srcpos] & 0x3F) + 1); (*srcpos)++; (*recyclecount) = 0; (*recyclebyte) = 0; } //else read another byte. that is the offset of decompressed data for copying. else { copyLZ(dst, dstpos, (src[*srcpos + 1] + 1), (src[*srcpos] & 0x3F) + 1); (*srcpos) += 2; } return 0; } static uint32_t processLLZ(uint8_t* dst, const uint8_t* src, uint32_t* dstpos, uint32_t *srcpos) { //Process a long LZ packet. //the byte read before ANDed by 0xC0 is the top 2 bits of the offset //read another byte. That is the bottom 8 bits of the offset. uint16_t offset = ((src[*srcpos] & 0xC0) << 2) | (src[*srcpos + 1]); //read one more byte. That is the copy length. //Now copy using the offset - 3 copyLZ(dst, dstpos, offset + 1, (src[*srcpos + 2]) + 3); (*srcpos) += 3; return 0; } static uint32_t processLZ(uint8_t* dst, uint8_t* src, uint32_t* dstpos, uint32_t *srcpos, uint8_t* recyclebyte, uint8_t* recyclecount) { //Process an LZ Packet by ANDing the first byte by 0x3F. if (src[*srcpos] & 0x3F) //if that equation is nonzero, it is a short LZ packet processSLZ(dst, src, dstpos, srcpos, recyclebyte, recyclecount); //else it is a long LZ packet. else processLLZ(dst, src, dstpos, srcpos); return 0; } static uint32_t processSRLE(uint8_t* dst, uint8_t* src, uint32_t* dstpos, uint32_t* srcpos) { int run; for (run = 0; run < (src[*srcpos] >> 5); run++) { dst[*dstpos] = (src[*srcpos] & 0x1F); (*dstpos)++; } (*srcpos)++; return 0; } static uint32_t processLRLE(uint8_t* dst, uint8_t* src, uint32_t* dstpos, uint32_t* srcpos) { int run; for (run = 0; run < (src[(*srcpos) + 1] + 8); run++) { dst[*dstpos] = (src[*srcpos] & 0x1F); (*dstpos)++; } (*srcpos) += 2; return 0; } static uint32_t processRLE(uint8_t* dst, uint8_t* src, uint32_t *dstpos, uint32_t *srcpos) { //Process an RLE Packet by ANDing the first byte by 0xC0 and checking if it's 0 if (src[*srcpos] & 0xE0) processSRLE(dst, src, dstpos, srcpos); else processLRLE(dst, src, dstpos, srcpos); return 0; } void decompressLZ5(uint8_t* tDst, uint8_t* tSrc, uint32_t tSourceLength) { uint32_t dstpos = 0; uint32_t srcpos = 0; uint8_t recbyt = 0; uint8_t reccount = 0; while (srcpos < tSourceLength) { //read a control packet and process it bit by bit //if the bit is 0, it is an RLE Packet, otherwise it is an LZ packet. uint8_t ctrlbyt = tSrc[srcpos]; srcpos++; int b; for (b = 0; (b < 8); b++) { if (!(ctrlbyt & (1 << b))) processRLE(tDst, tSrc, &dstpos, &srcpos); else processLZ(tDst, tSrc, &dstpos, &srcpos, &recbyt, &reccount); if (srcpos >= tSourceLength) break; } } }
27.227273
141
0.661937
CaptainDreamcast
3ab305223fa3e3136616b244c1f80292cb2039ec
12,851
cpp
C++
code/src/Graphics/Vulkan/Shaders/Renderpass.cpp
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
4
2019-03-21T16:02:03.000Z
2020-04-09T08:53:29.000Z
code/src/Graphics/Vulkan/Shaders/Renderpass.cpp
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
24
2018-04-06T08:25:17.000Z
2020-10-19T11:01:09.000Z
code/src/Graphics/Vulkan/Shaders/Renderpass.cpp
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
null
null
null
#include "Graphics/Vulkan/Shaders/Renderpass.h" #include "Core/Threading/Tasks/Scheduler.h" #ifdef _DEBUG #include <set> #endif Pu::Renderpass::Renderpass(LogicalDevice & device) : Asset(true), device(&device), hndl(nullptr), ownsShaders(false), usesDependency(false), PreCreate("RenderpassPreCreate"), PostCreate("RenderpassPostCreate") {} Pu::Renderpass::Renderpass(LogicalDevice & device, std::initializer_list<std::initializer_list<wstring>> shaderModules) : Renderpass(device) { ownsShaders = true; subpasses.reserve(shaderModules.size()); /* Inline load all the shader modules and then start the creation process. */ for (const std::initializer_list<wstring> &modules : shaderModules) { vector<Shader*> shaders(modules.size()); for (const wstring &shader : modules) { shaders.emplace_back(new Shader(device, shader)); } subpasses.emplace_back(device, shaders); } } Pu::Renderpass::Renderpass(LogicalDevice & device, Subpass && subpass) : Renderpass(device) { subpasses.emplace_back(std::move(subpass)); } Pu::Renderpass::Renderpass(LogicalDevice & device, vector<Subpass>&& subpasses) : Renderpass(device) { this->subpasses = std::move(subpasses); } Pu::Renderpass::Renderpass(Renderpass && value) : Asset(std::move(value)), device(value.device), hndl(value.hndl), ownsShaders(value.ownsShaders), outputDependency(value.outputDependency), subpasses(std::move(value.subpasses)), clearValues(std::move(value.clearValues)), usesDependency(value.usesDependency), PreCreate(std::move(value.PreCreate)), PostCreate(std::move(value.PostCreate)) { value.hndl = nullptr; } Pu::Renderpass & Pu::Renderpass::operator=(Renderpass && other) { if (this != &other) { Destroy(); Asset::operator=(std::move(other)); device = other.device; hndl = other.hndl; ownsShaders = other.ownsShaders; usesDependency = other.usesDependency; outputDependency = other.outputDependency; subpasses = std::move(other.subpasses); clearValues = std::move(other.clearValues); PreCreate = std::move(other.PreCreate); PostCreate = std::move(other.PostCreate); other.hndl = nullptr; } return *this; } void Pu::Renderpass::Initialize(void) { /* Just call create, but only if we've not loaded the renderpass! */ if (!(IsLoaded() || ownsShaders)) Create(false); } void Pu::Renderpass::AddDependency(PipelineStageFlags srcStage, PipelineStageFlags dstStage, AccessFlags srcAccess, AccessFlags dstAccess, DependencyFlags flag) { usesDependency = true; outputDependency.SrcSubpass = static_cast<uint32>(subpasses.size() - 1); outputDependency.DstSubpass = SubpassExternal; outputDependency.SrcStageMask = srcStage; outputDependency.DstStageMask = dstStage; outputDependency.SrcAccessMask = srcAccess; outputDependency.DstAccessMask = dstAccess; outputDependency.DependencyFlags = flag; } Pu::Asset & Pu::Renderpass::Duplicate(AssetCache &) { Reference(); /* The underlying shaders need to be references as well in case they were loaded with the loader. */ for (const Subpass &subpass : subpasses) { for (Shader *shader : subpass.GetShaders()) shader->Reference(); } return *this; } void Pu::Renderpass::Recreate(void) { if (IsLoaded()) { /* Destroy the old renderpass. */ MarkAsLoading(); device->vkDestroyRenderPass(device->hndl, hndl, nullptr); /* Only re-create the renderpass handle. */ PreCreate.Post(*this); CreateRenderpass(); PostCreate.Post(*this); MarkAsLoaded(); } } void Pu::Renderpass::Create(bool viaLoader) { /* We need to set a subpass indicator for all outputs, this is used for checking later on. We also need to set the attachment reference attachment index, otherwise we'll have overlapping indices with multiple subpasses. */ for (uint32 i = 0, start = 0; i < subpasses.size(); i++) { for (Output &output : subpasses[i].outputs) { output.subpass = i; output.reference.Attachment += start; } start += static_cast<uint32>(subpasses[i].outputs.size()); } /* We call pre-create to give the owner the chance to initialize the subpasses. In create we actually create the renderpass. After this we call post-create for optional ownder code and then mark it as loaded. Marking as loaded should always be the last thing to do for thread safety. */ PreCreate.Post(*this); CreateRenderpass(); PostCreate.Post(*this); MarkAsLoaded(viaLoader, L"Renderpass"); } void Pu::Renderpass::CreateRenderpass(void) { /* We aren't going to use the old clear values anymore. */ clearValues.clear(); /* Pre-set the size of the attachment descriptions. The order of the descriptions is based on the references set by the user (or kept as default). */ size_t reserveSize = 0; vector<AttachmentDescription> attachmentDescriptions; for (const Subpass &subpass : subpasses) reserveSize += subpass.outputs.size(); attachmentDescriptions.resize(reserveSize); clearValues.resize(reserveSize); /* Generate the subpass descriptions, make sure that the vectors don't resize. */ vector<SubpassDescription> subpassDescriptions; subpassDescriptions.reserve(subpasses.size()); vector<vector<AttachmentReference>> inputAttachments{ subpasses.size() }; vector<vector<AttachmentReference>> colorAttachments{ subpasses.size() }; vector<vector<AttachmentReference>> resolveAttachments{ subpasses.size() }; uint32 maxReference = 0; for (const Subpass &subpass : subpasses) { const size_t i = subpassDescriptions.size(); const AttachmentReference *depthStencil = nullptr; /* Add all the color, resolve attachments to a temporary vector and set the depth/stencil attachment (if needed). */ for (const Output &output : subpass.outputs) { #ifdef _DEBUG /* Log a warning if the user is overriding the previous depth/stencil attachment. */ if (output.type == OutputUsage::DepthStencil && depthStencil) { Log::Warning("A depth/stencil attachment is already set for subpass %zu, overriding attachment!", i); } #endif /* Clones are just previously defined references that need to be added again. */ if (output.clone) { if (output.type == OutputUsage::Color) CopyReference(colorAttachments, i, output.reference.Attachment); else if (output.type == OutputUsage::Resolve) CopyReference(resolveAttachments, i, output.reference.Attachment); else if (output.type == OutputUsage::DepthStencil) { for (const SubpassDescription &cur : subpassDescriptions) { if (cur.DepthStencilAttachment && cur.DepthStencilAttachment->Attachment == output.reference.Attachment) { depthStencil = cur.DepthStencilAttachment; break; } } } } else { /* Just add the attachment reference to the correct list. */ if (output.type == OutputUsage::Color) colorAttachments[i].emplace_back(output.reference); else if (output.type == OutputUsage::Resolve) resolveAttachments[i].emplace_back(output.reference); else if (output.type == OutputUsage::DepthStencil) depthStencil = &output.reference; /* Set the correct attachment description and clear value. */ attachmentDescriptions[output.reference.Attachment] = output.description; clearValues[output.reference.Attachment] = output.clear; } /* This is used to scale down the attachments that are used in multiple subpasses. */ maxReference = max(maxReference, output.reference.Attachment); } /* Add the input attachments from the descriptors. */ for (const Descriptor &descriptor : subpass.descriptors) { if (descriptor.GetType() == DescriptorType::InputAttachment) { const uint32 idx = descriptor.GetInfo().Decorations.Numbers.at(spv::Decoration::InputAttachmentIndex); bool handled = false; for (const vector<AttachmentReference> &attachments : colorAttachments) { for (AttachmentReference ref : attachments) { /* The input attachment will have the same index as a previous subpass color attachment. */ if (ref.Attachment == idx) { /* Color attachments will always have shader read only optimal layout. */ inputAttachments[i].emplace_back(idx, ImageLayout::ShaderReadOnlyOptimal); handled = true; break; } } if (handled) break; } /* It wasn't a color attachment, maybe it was a depth/stencil attachment? */ if (!handled) { /* Search all the previous subpasses for a mathcing depth/stencil attachment. */ for (size_t j = 0; j < i; j++) { const SubpassDescription &desc = subpassDescriptions[j]; if (desc.DepthStencilAttachment && desc.DepthStencilAttachment->Attachment == idx) { /* Depth/stencil attachments will also always have shader read only optimal layout. */ inputAttachments[i].emplace_back(idx, ImageLayout::ShaderReadOnlyOptimal); handled = true; break; } } } /* Crash if we could not handle the input attachment. */ if (!handled) { Log::Fatal("Unable to find origional attachment for input attachment '%s' cannot create reference!", descriptor.GetInfo().Name.c_str()); } } } /* Create the subpass description, TODO: handle preserve attachments. */ SubpassDescription description{ colorAttachments[i], inputAttachments[i], resolveAttachments[i] }; description.DepthStencilAttachment = depthStencil; subpassDescriptions.emplace_back(description); } /* Copy the dependencies from the subpasses. */ vector<SubpassDependency> dependencies; for (uint32 i = 0; i < subpasses.size(); i++) { /* A subpass might have multiple dependencies. */ for (SubpassDependency depenceny : subpasses[i].dependencies) { /* Set the destination subpass to the current subpass index. */ depenceny.DstSubpass = i; /* Override the source to the previous subpass if it's not the first one, but it still has the default value of SubpassNotSet. */ if (depenceny.SrcSubpass == Subpass::SubpassNotSet) { depenceny.SrcSubpass = i == 0 ? SubpassExternal : i - 1; } dependencies.emplace_back(depenceny); } } /* Only add the external output dependency if the user created one. */ if (usesDependency) dependencies.emplace_back(outputDependency); /* Scale the attachments down to avoid duplicates. */ attachmentDescriptions.resize(maxReference + 1); /* Create the renderpass. */ const RenderPassCreateInfo createInfo(attachmentDescriptions, subpassDescriptions, dependencies); VK_VALIDATE(device->vkCreateRenderPass(device->hndl, &createInfo, nullptr, &hndl), PFN_vkCreateRenderPass); } void Pu::Renderpass::CopyReference(vector<vector<AttachmentReference>>& references, size_t i, uint32 refIdx) { for (size_t j = 0; j < i; j++) { for (const AttachmentReference &ref : references[j]) { if (ref.Attachment == refIdx) { references[i].emplace_back(ref); return; } } } Log::Error("Cannot clone attachment referece %u for subpass %zu (parent attachment could not be found in previous subpasses)!", refIdx, i); } void Pu::Renderpass::Destroy(void) { if (hndl) device->vkDestroyRenderPass(device->hndl, hndl, nullptr); /* This means we loaded the shaders inline, which means we need to free them. */ if (ownsShaders) { for (const Subpass &subpass : subpasses) { for (const Shader *shader : subpass.GetShaders()) delete shader; } } subpasses.clear(); } Pu::Renderpass::LoadTask::LoadTask(Renderpass & result, const vector<std::tuple<size_t, size_t, wstring>>& toLoad) : Task("Link Shader Program"), renderpass(result) { children.reserve(toLoad.size()); for (const auto &[subpass, idx, path] : toLoad) { children.emplace_back(new Shader::LoadTask(*renderpass.subpasses[subpass].shaders[idx], path)); } } Pu::Task::Result Pu::Renderpass::LoadTask::Execute(void) { /* Shader load tasks are important as other tasks depend on them, so force their loading. */ for (Shader::LoadTask *task : children) { task->SetParent(*this); TaskScheduler::Force(*task); } return Result::CustomWait(); } bool Pu::Renderpass::LoadTask::ShouldContinue(void) const { /* We want to check if all shaders are loaded before we continue. We can have a race if two renderpasses use the same shader and are loaded at the same time. */ for (const Subpass &subpass : renderpass.subpasses) { for (const Shader *shader : subpass.shaders) { if (!shader->IsLoaded()) return false; } } return Task::ShouldContinue(); } Pu::Task::Result Pu::Renderpass::LoadTask::Continue(void) { /* Make sure that the subpasses are compatible and initialized. */ for (Subpass &subpass : renderpass.subpasses) subpass.Link(*renderpass.device, true); /* Delete the underlying shader load tasks, create the renderpass and finally allow the scheduler to delete this task. */ for (const Shader::LoadTask *task : children) delete task; renderpass.Create(true); return Result::AutoDelete(); }
32.20802
160
0.721422
Arzana
3ab7fae4cbce84c5541e79e4d1174bd49b62ccc5
8,108
cpp
C++
examples/ReinforcedLearning/ReinforcedLearning.cpp
OuluLinux/ConvNetCpp
48854357b49b35d6599fb8ae42be01f4ba1903a6
[ "MIT" ]
7
2017-05-04T17:20:10.000Z
2019-10-02T13:08:33.000Z
examples/ReinforcedLearning/ReinforcedLearning.cpp
sppp/ConvNetC-
48854357b49b35d6599fb8ae42be01f4ba1903a6
[ "MIT" ]
null
null
null
examples/ReinforcedLearning/ReinforcedLearning.cpp
sppp/ConvNetC-
48854357b49b35d6599fb8ae42be01f4ba1903a6
[ "MIT" ]
3
2017-04-13T06:29:23.000Z
2018-01-09T07:44:09.000Z
#include "ReinforcedLearning.h" #include "pretrained.brc" #include <plugin/bz2/bz2.h> #define IMAGECLASS ReinforcedLearningImg #define IMAGEFILE <ReinforcedLearning/ReinforcedLearning.iml> #include <Draw/iml_source.h> GUI_APP_MAIN { ReinforcedLearning().Run(); } ReinforcedLearning::ReinforcedLearning() { Title("Deep Q Learning Reinforcement"); Icon(ReinforcedLearningImg::icon()); Sizeable().MaximizeBox().MinimizeBox().Zoomable(); ticking_running = false; ticking_stopped = true; skipdraw = false; t = "[\n" "\t{\"type\":\"input\", \"input_width\":1, \"input_height\":1, \"input_depth\":59},\n" "\t{\"type\":\"fc\", \"neuron_count\": 50, \"activation\":\"relu\"},\n" "\t{\"type\":\"fc\", \"neuron_count\": 50, \"activation\":\"relu\"},\n" "\t{\"type\":\"regression\", \"neuron_count\":5},\n" "\t{\"type\":\"sgd\", \"learning_rate\":0.001, \"momentum\":0.0, \"batch_size\":64, \"l2_decay\":0.01}\n" "]\n"; net_edit.SetData(t); Add(world.SizePos()); net_ctrl.Add(net_edit.HSizePos().VSizePos(0,30)); net_ctrl.Add(reload_btn.HSizePos().BottomPos(0,30)); reload_btn.SetLabel("Reload Network"); reload_btn <<= THISBACK(Reload); average_size = 10; network_view.SetSession(world.agents[0].brain); input_view.SetSession(world.agents[0].brain); is_training.SetLabel("Is training"); load_trained.SetLabel("Load pre-trained"); load_file.SetLabel("Load file"); store_file.SetLabel("Save file"); load_trained <<= THISBACK(LoadPreTrained); load_file <<= THISBACK(OpenFile); store_file <<= THISBACK(SaveFile); is_training.Set(true); is_training <<= THISBACK(RefreshTrainingStatus); // "Very fast" is meaningful only if the program doesn't have threads, and calculating // must be done in the GUI loop, like in the JS version. #ifdef flagMT speed.MinMax(0,2); speed.SetData(0); #else speed.MinMax(0,3); speed.SetData(1); #endif speed.Step(1); speed <<= THISBACK(RefreshSpeed); controller.Add(is_training.TopPos(0,30).LeftPos(0,150)); controller.Add(load_trained.TopPos(30,30).LeftPos(0,150)); controller.Add(load_file.TopPos(60,30).LeftPos(0,150)); controller.Add(store_file.TopPos(90,30).LeftPos(0,150)); controller.Add(speed.VSizePos().LeftPos(150,30)); reward_graph.SetSession(world.agents[0].brain); PostCallback(THISBACK(Reload)); PostCallback(THISBACK(Start)); PostCallback(THISBACK(Refresher)); } ReinforcedLearning::~ReinforcedLearning() { ticking_running = false; while (!ticking_stopped) Sleep(100); } void ReinforcedLearning::DockInit() { DockLeft(Dockable(input_view, "Input").SizeHint(Size(320, 240))); DockLeft(Dockable(reward_graph, "Reward").SizeHint(Size(320, 240))); DockLeft(Dockable(status, "Status").SizeHint(Size(120, 120))); DockBottom(Dockable(network_view, "Network View").SizeHint(Size(640, 120))); DockBottom(Dockable(controller, "Controls").SizeHint(Size(180, 30*4))); AutoHide(DOCK_LEFT, Dockable(net_ctrl, "Edit Network").SizeHint(Size(640, 320))); } void ReinforcedLearning::RefreshStatus() { Brain& b = world.agents[0].brain; String s; s << " experience replay size: " << b.GetExperienceCount() << "\n"; s << " exploration epsilon: " << b.GetEpsilon() << "\n"; s << " age: " << b.GetAge() << "\n"; s << " average Q-learning loss: " << b.GetAverageLoss() << "\n"; s << " smooth-ish reward: " << b.GetAverageReward(); status.SetLabel(s); } void ReinforcedLearning::RefreshTrainingStatus() { bool is_training = this->is_training; for(int i = 0; i < world.agents.GetCount(); i++) { world.agents[i].brain.SetLearning(is_training); } } void ReinforcedLearning::RefreshSpeed() { int speed = this->speed.GetMax() - (int)this->speed.GetData(); // Inverse direction switch (speed) { case 0: GoSlow(); break; case 1: GoNormal(); break; case 2: GoFast(); break; case 3: GoVeryFast(); break; } } void ReinforcedLearning::Tick() { // "Normal" is a little bit slower than fastest if (simspeed == 1) Sleep(10); else if (simspeed == 0) Sleep(100); world.Tick(); Brain& brain = world.agents[0].brain; int age = brain.GetAge(); int average_window_size = brain.GetAverageLossWindowSize(); if (age >= average_window_size && (age % 100) == 0) reward_graph.AddValue(); } void ReinforcedLearning::Ticking() { while (ticking_running) { ticking_lock.Enter(); Tick(); ticking_lock.Leave(); } ticking_stopped = true; } void ReinforcedLearning::GoVeryFast() { skipdraw = true; simspeed = 3; } void ReinforcedLearning::GoFast() { skipdraw = false; simspeed = 2; } void ReinforcedLearning::GoNormal() { skipdraw = false; simspeed = 1; } void ReinforcedLearning::GoSlow() { skipdraw = false; simspeed = 0; } void ReinforcedLearning::Reload() { String net_str = net_edit.GetData(); Brain& brain = world.agents[0].brain; ticking_lock.Enter(); brain.Reset(); bool success = brain.MakeLayers(net_str); ticking_lock.Leave(); } void ReinforcedLearning::Start() { GoFast(); ticking_running = true; ticking_stopped = false; Thread::Start(THISBACK(Ticking)); } void ReinforcedLearning::Refresher() { if (!skipdraw) { input_view.Refresh(); network_view.Refresh(); world.Refresh(); reward_graph.RefreshData(); RefreshStatus(); } PostCallback(THISBACK(Refresher)); } void ReinforcedLearning::LoadPreTrained() { // This is the pre-trained network from original ConvNetJS MemReadStream pretrained_mem(pretrained, pretrained_length); BZ2DecompressStream stream(pretrained_mem); // Stop training ticking_lock.Enter(); this->is_training = false; RefreshTrainingStatus(); // Load json world.agents[0].brain.SerializeWithoutExperience(stream); ticking_lock.Leave(); // Go slower GoNormal(); } void ReinforcedLearning::OpenFile() { String file = SelectFileOpen("BIN files\t*.bin\nAll files\t*.*"); if (file.IsEmpty()) return; if (!FileExists(file)) { PromptOK("File does not exists"); return; } // Stop training this->is_training = false; RefreshTrainingStatus(); ticking_lock.Enter(); FileIn fin(file); world.agents[0].brain.SerializeWithoutExperience(fin); ticking_lock.Leave(); // Go slower GoNormal(); if (!ticking_running) Start(); } void ReinforcedLearning::SaveFile() { String file = SelectFileSaveAs("BIN files\t*.bin\nAll files\t*.*"); if (file.IsEmpty()) return; FileOut fout(file); if (!fout.IsOpen()) { PromptOK("Error: could not open file " + file); return; } world.agents[0].brain.SerializeWithoutExperience(fout); } // line intersection helper function: does line segment (l1a,l1b) intersect segment (l2a,l2b) ? InterceptResult IsLineIntersect(Pointf l1a, Pointf l1b, Pointf l2a, Pointf l2b) { double denom = (l2b.y - l2a.y) * (l1b.x - l1a.x) - (l2b.x - l2a.x) * (l1b.y - l1a.y); if (denom == 0.0) return InterceptResult(false); // parallel lines double ua = ((l2b.x-l2a.x)*(l1a.y-l2a.y)-(l2b.y-l2a.y)*(l1a.x-l2a.x))/denom; double ub = ((l1b.x-l1a.x)*(l1a.y-l2a.y)-(l1b.y-l1a.y)*(l1a.x-l2a.x))/denom; if (ua > 0.0 && ua<1.0 && ub > 0.0 && ub < 1.0) { Pointf up(l1a.x+ua*(l1b.x-l1a.x), l1a.y+ua*(l1b.y-l1a.y)); InterceptResult res; res.ua = ua; res.ub = ub; res.up = up; res.is_intercepting = true; return res; } return InterceptResult(false); } InterceptResult IsLinePointIntersect(Pointf a, Pointf b, Pointf p, int rad) { Pointf v(b.y-a.y,-(b.x-a.x)); // perpendicular vector double d = fabs((b.x-a.x)*(a.y-p.y)-(a.x-p.x)*(b.y-a.y)); d = d / Length(v); if (d > rad) return false; Normalize(v); Scale(v, d); Pointf up = p + v; double ua; if (fabs(b.x-a.x) > fabs(b.y-a.y)) { ua = (up.x - a.x) / (b.x - a.x); } else { ua = (up.y - a.y) / (b.y - a.y); } if (ua > 0.0 && ua < 1.0) { InterceptResult ir; ir.up = up; ir.ua = ua; ir.up = up; ir.is_intercepting = true; return ir; } return false; } void AddBox(Vector<Wall>& lst, int x, int y, int w, int h) { lst.Add(Wall(Point(x,y), Point(x+w,y))); lst.Add(Wall(Point(x+w,y), Point(x+w,y+h+1))); lst.Add(Wall(Point(x+w,y+h), Point(x,y+h))); lst.Add(Wall(Point(x,y+h), Point(x,y))); }
24.644377
107
0.670079
OuluLinux
3ab98b530f501893e51486e969313a8e4b6b179e
2,701
cpp
C++
src/Jogo/Entidades/Inimigo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Entidades/Inimigo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Entidades/Inimigo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
// // Inimigo.cpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 10/5/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #include "Inimigo.hpp" namespace Game { namespace Entidades { namespace Personagens { Inimigo::Inimigo(ID id,const Vector2f& position, Texture* texture, Jogador* jogador_a, Jogador* jogador_b, const int& damage): Personagem(id, position, texture), jogador_a(jogador_a), jogador_b(jogador_b), damage(damage), amplitude_mov(.25), vel_mov(2.4), time_mov(0.f), idle_time(0.f), attack_delay(2.f) { this->move_comp.setAceleration(Vector2f(this->move_comp.getAceleration().x*this->amplitude_mov, this->move_comp.getAceleration().y)); } Inimigo::~Inimigo(){ } // Methods void Inimigo::update(const float& dt){ // Atualiza tempo ataque this->idle_time += dt; // Atualiza paso de movimento this->autoMove(dt); // Atualiza componente de movimento this->move_comp.update(dt); // Verifica se pode atacar ao jogador this->updatePlayerAttack(); } void Inimigo::updatePlayerAttack(){ // Espera para voltar a atacar if (this->idle_time < this->attack_delay) return; Vector2f distance, max_distance; // Verifica distancia de ataque com jogador if (jogador_a){ distance = Entidade::distanceV(this->jogador_a, this); max_distance = Entidade::maxDistanceV(this->jogador_a, this); if ((distance.x <= max_distance.x && distance.y < max_distance.y) && (distance.y <= max_distance.y && distance.x < max_distance.x)) this->attack(jogador_a); } // Verifica distancia de ataque com jogador if (this->jogador_b){ distance = Entidade::distanceV(this->jogador_b, this); max_distance = Entidade::maxDistanceV(this->jogador_a, this); if ((distance.x <= max_distance.x && distance.y < max_distance.y) && (distance.y <= max_distance.y && distance.x < max_distance.x)) this->attack(jogador_b); } } // Getters & Setters void Inimigo::setDamage(const float &damage) { this->damage = damage; } const float& Inimigo::getDamage() const { return this->damage; } void Inimigo::setAmplitudeMov(const float& amplitude_mov) { this->amplitude_mov = amplitude_mov; } const float& Inimigo::getAmplitudeMov() const { return this->amplitude_mov; } void Inimigo::setVelMov(const float &vel_mov) { this->vel_mov = vel_mov; } const float& Inimigo::getVelMov() const { return this->vel_mov; } void Inimigo::setAttackDelay(const float &attack_delay) { this->attack_delay = attack_delay; } const float& Inimigo::getAttackDelay() const { return this->attack_delay; } }}}
26.223301
139
0.679748
MatheusKunnen
3ab9a061f1d7d55c9560463fcfc204466ab4f4aa
11,843
cpp
C++
tools/ifaceed/ifaceed/scripting/layouts/scriptablegrid.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/scripting/layouts/scriptablegrid.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/scripting/layouts/scriptablegrid.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "scriptablegrid.h" #include "scriptablegridcell.h" #include <renderer.h> #include <layouts/grid.h> #include <db/dbdatabase.h> #include "../queryobject.h" #include "../scripting.h" #include "../core/editor.h" #include "../gui/actions/actions.h" #include "../gui/actions/gridactions.h" #include "../../qstdstring.h" Q_DECLARE_METATYPE(scripting::layouts::ScriptableGrid*) Q_DECLARE_METATYPE(scripting::layouts::ScriptableGridCell*) // ==================================== PUBLIC METHODS ==================================== scripting::layouts::ScriptableGrid::ScriptableGrid( unsigned long long major_id, scripting::Scripting* s ) : m_majorid(major_id), m_scripting(s) { } scripting::layouts::ScriptableGrid::~ScriptableGrid() { } sad::layouts::Grid* scripting::layouts::ScriptableGrid::grid(bool throw_exception, const QString& name) const { sad::db::Database* db = sad::Renderer::ref()->database(""); if (db) { sad::layouts::Grid* grid = db->objectByMajorId<sad::layouts::Grid>(m_majorid); if (grid) { if (grid->Active) { return grid; } } } if (throw_exception) { m_scripting->context()->throwError(std::string("ScriptableGrid.") + name.toStdString() + ": Reference to a grid is not a valid instance"); throw dukpp03::ArgumentException(); } return nullptr; } void scripting::layouts::ScriptableGrid::setArea(sad::Rect2D new_area) const { if (!sad::isAABB(new_area)) { m_scripting->context()->throwError("setArea: rectangle is not axis-aligned"); throw new dukpp03::ArgumentException(); } sad::layouts::Grid* g = grid(true, "setArea"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeAreaForGrid(g, new_area, false); } } dukpp03::Maybe<QVector<QVariant> > scripting::layouts::ScriptableGrid::findChild(sad::SceneNode* o) { dukpp03::Maybe<QVector<QVariant> > result; sad::layouts::Grid* g = grid(true, "findChild"); if (g) { sad::Maybe<sad::layouts::Grid::SearchResult> res = g->find(o); if (res.exists()) { sad::layouts::Cell* c = g->cell(res.value().p1()); QVector<QVariant> result_vector; QVariant first_variant; first_variant.setValue(new scripting::layouts::ScriptableGridCell(g->MajorId, c->Row, c->Col, m_scripting)); QVariant second_variant; second_variant.setValue(static_cast<unsigned int>(res.value().p2())); result_vector << first_variant << second_variant; result.setValue(result_vector); } } return result; } scripting::layouts::ScriptableGridCell* scripting::layouts::ScriptableGrid::cell(int row, int column) { sad::layouts::Grid* g = grid(true, "cell"); if (g) { if (row < 0 || column < 0 || row >= g->rows() || column >= g->columns()) { QString errorMessage = "ScriptableGrid.cell: There are no such cell %1, %2 in grid"; errorMessage = errorMessage.arg(row).arg(column); m_scripting->context()->throwError(errorMessage.toStdString()); throw new dukpp03::ArgumentException(); } else { return new scripting::layouts::ScriptableGridCell(g->MajorId, row, column, m_scripting); } } else { m_scripting->context()->throwError("ScriptableGrid.cell: Attempt to get cell for non-existing grid"); throw new dukpp03::ArgumentException(); } return nullptr; } QVector<unsigned long long> scripting::layouts::ScriptableGrid::children() const { QVector<unsigned long long> result; sad::layouts::Grid* g = grid(true, "children"); if (g) { sad::Vector<unsigned long long> major_ids = g->childrenMajorIds(); for (size_t i = 0; i < major_ids.size(); i++) { result << major_ids[i]; } } return result; } // ==================================== PUBLIC SLOT METHODS ==================================== QString scripting::layouts::ScriptableGrid::toString() const { if (!valid()) { return "ScriptableGrid(<invalid>)"; } QString result = QString("ScriptableGrid(majorid : %1)") .arg(m_majorid); return result; } bool scripting::layouts::ScriptableGrid::valid() const { return grid(false) != nullptr; } sad::Rect2D scripting::layouts::ScriptableGrid::area() const { sad::Rect2D v; sad::layouts::Grid* g = grid(true, "area"); if (g) { v = g->area(); } return v; } unsigned long long scripting::layouts::ScriptableGrid::majorId() const { unsigned long long result = 0; sad::layouts::Grid* g = grid(true, "majorId"); if (g) { result = g->MajorId; } return result; } unsigned long long scripting::layouts::ScriptableGrid::minorId() const { unsigned long long result = 0; sad::layouts::Grid* g = grid(true, "minorId"); if (g) { result = g->MinorId; } return result; } QString scripting::layouts::ScriptableGrid::name() const { QString result; sad::layouts::Grid* g = grid(true, "name"); if (g) { result = STD2QSTRING(g->objectName()); } return result; } void scripting::layouts::ScriptableGrid::setName(const QString& name) const { sad::layouts::Grid* g = grid(true, "setName"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeNameForGrid(g, Q2STDSTRING(name), false); } } bool scripting::layouts::ScriptableGrid::fixedWidth() const { bool result = false; sad::layouts::Grid* g = grid(true, "fixedWidth"); if (g) { result = g->fixedWidth(); } return result; } void scripting::layouts::ScriptableGrid::setFixedWidth(bool fixed_width) const { sad::layouts::Grid* g = grid(true, "setFixedWidth"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeFixedWidthForGrid(g, fixed_width, false); } } bool scripting::layouts::ScriptableGrid::fixedHeight() const { bool result = false; sad::layouts::Grid* g = grid(true, "fixedHeight"); if (g) { result = g->fixedHeight(); } return result; } void scripting::layouts::ScriptableGrid::setFixedHeight(bool fixed_height) const { sad::layouts::Grid* g = grid(true, "setFixedHeight"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeFixedHeightForGrid(g, fixed_height, false); } } unsigned long scripting::layouts::ScriptableGrid::rows() const { unsigned long result = 0; sad::layouts::Grid* g = grid(true, "rows"); if (g) { result = g->rows(); } return result; } void scripting::layouts::ScriptableGrid::setRows(int rows) const { if (rows <= 0) { m_scripting->context()->throwError("ScriptableGrid.setRows: amount of rows cannot be lesser or equal to 0"); throw new dukpp03::ArgumentException(); } sad::layouts::Grid* g = grid(true, "setRows"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeRowCountForGrid(g, rows, false); } } unsigned long scripting::layouts::ScriptableGrid::columns() const { unsigned long result = 0; sad::layouts::Grid* g = grid(true, "columns"); if (g) { result = g->columns(); } return result; } void scripting::layouts::ScriptableGrid::setColumns(int columns) const { if (columns <= 0) { m_scripting->context()->throwError("ScriptableGrid.setColumns: amount of columns cannot be lesser or equal to 0"); throw new dukpp03::ArgumentException(); } sad::layouts::Grid* g = grid(true, "setColumns"); if (g) { m_scripting->editor()->actions()->gridActions()->tryChangeColumnCountForGrid(g, columns, false); } } double scripting::layouts::ScriptableGrid::paddingTop() const { double result = 0; sad::layouts::Grid* g = grid(true, "paddingTop"); if (g) { result = g->paddingTop(); } return result; } double scripting::layouts::ScriptableGrid::paddingBottom() const { double result = 0; sad::layouts::Grid* g = grid(true, "paddingBottom"); if (g) { result = g->paddingBottom(); } return result; } double scripting::layouts::ScriptableGrid::paddingLeft() const { double result = 0; sad::layouts::Grid* g = grid(true, "paddingLeft"); if (g) { result = g->paddingLeft(); } return result; } double scripting::layouts::ScriptableGrid::paddingRight() const { double result = 0; sad::layouts::Grid* g = grid(true, "paddingRight"); if (g) { result = g->paddingRight(); } return result; } void scripting::layouts::ScriptableGrid::setPaddingTop(double v, bool p) const { sad::layouts::Grid* g = grid(true, "setPaddingTop"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); ga->tryChangePaddingForGrid( gui::actions::GridActions::GridUpdateOptions::GGAUO_TopPadding, g, v, p, false ); } } void scripting::layouts::ScriptableGrid::setPaddingBottom(double v, bool p) const { sad::layouts::Grid* g = grid(true, "setPaddingBottom"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); ga->tryChangePaddingForGrid( gui::actions::GridActions::GridUpdateOptions::GGAUO_BottomPadding, g, v, p, false ); } } void scripting::layouts::ScriptableGrid::setPaddingLeft(double v, bool p) const { sad::layouts::Grid* g = grid(true, "setPaddingLeft"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); ga->tryChangePaddingForGrid( gui::actions::GridActions::GridUpdateOptions::GGAUO_LeftPadding, g, v, p, false ); } } void scripting::layouts::ScriptableGrid::setPaddingRight(double v, bool p) const { sad::layouts::Grid* g = grid(true, "setPaddingRight"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); ga->tryChangePaddingForGrid( gui::actions::GridActions::GridUpdateOptions::GGAUO_RightPadding, g, v, p, false ); } } void scripting::layouts::ScriptableGrid::setPaddingTop(double v) const { this->setPaddingTop(v, true); } void scripting::layouts::ScriptableGrid::setPaddingBottom(double v) const { this->setPaddingBottom(v, true); } void scripting::layouts::ScriptableGrid::setPaddingLeft(double v) const { this->setPaddingLeft(v, true); } void scripting::layouts::ScriptableGrid::setPaddingRight(double v) const { this->setPaddingRight(v, true); } bool scripting::layouts::ScriptableGrid::merge(int row, int column, int row_span, int col_span) { sad::layouts::Grid* g = grid(true, "merge"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); return ga->tryPerformMergeOrSplit(true, g, row, column, row_span, col_span, false); } return false; } bool scripting::layouts::ScriptableGrid::split(int row, int column, int row_span, int col_span) { sad::layouts::Grid* g = grid(true, "split"); if (g) { gui::actions::GridActions* ga = m_scripting->editor()->actions()->gridActions(); return ga->tryPerformMergeOrSplit(false, g, row, column, row_span, col_span, false); } return false; }
25.801743
147
0.607279
mamontov-cpp
3ab9dd37fcf98644e9252fe4afc566db17d8f2c2
4,793
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/profile__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/profile__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/profile__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from rmf_traffic_msgs:msg/Profile.idl // generated code does not contain a copyright notice #ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__PROFILE__STRUCT_HPP_ #define RMF_TRAFFIC_MSGS__MSG__DETAIL__PROFILE__STRUCT_HPP_ #include <rosidl_runtime_cpp/bounded_vector.hpp> #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> // Include directives for member types // Member 'footprint' // Member 'vicinity' #include "rmf_traffic_msgs/msg/detail/convex_shape__struct.hpp" // Member 'shape_context' #include "rmf_traffic_msgs/msg/detail/convex_shape_context__struct.hpp" #ifndef _WIN32 # define DEPRECATED__rmf_traffic_msgs__msg__Profile __attribute__((deprecated)) #else # define DEPRECATED__rmf_traffic_msgs__msg__Profile __declspec(deprecated) #endif namespace rmf_traffic_msgs { namespace msg { // message struct template<class ContainerAllocator> struct Profile_ { using Type = Profile_<ContainerAllocator>; explicit Profile_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : footprint(_init), vicinity(_init), shape_context(_init) { (void)_init; } explicit Profile_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : footprint(_alloc, _init), vicinity(_alloc, _init), shape_context(_alloc, _init) { (void)_init; } // field types and members using _footprint_type = rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>; _footprint_type footprint; using _vicinity_type = rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>; _vicinity_type vicinity; using _shape_context_type = rmf_traffic_msgs::msg::ConvexShapeContext_<ContainerAllocator>; _shape_context_type shape_context; // setters for named parameter idiom Type & set__footprint( const rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> & _arg) { this->footprint = _arg; return *this; } Type & set__vicinity( const rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> & _arg) { this->vicinity = _arg; return *this; } Type & set__shape_context( const rmf_traffic_msgs::msg::ConvexShapeContext_<ContainerAllocator> & _arg) { this->shape_context = _arg; return *this; } // constant declarations // pointer types using RawPtr = rmf_traffic_msgs::msg::Profile_<ContainerAllocator> *; using ConstRawPtr = const rmf_traffic_msgs::msg::Profile_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_traffic_msgs::msg::Profile_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_traffic_msgs::msg::Profile_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_traffic_msgs__msg__Profile std::shared_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_traffic_msgs__msg__Profile std::shared_ptr<rmf_traffic_msgs::msg::Profile_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const Profile_ & other) const { if (this->footprint != other.footprint) { return false; } if (this->vicinity != other.vicinity) { return false; } if (this->shape_context != other.shape_context) { return false; } return true; } bool operator!=(const Profile_ & other) const { return !this->operator==(other); } }; // struct Profile_ // alias to use template instance with default allocator using Profile = rmf_traffic_msgs::msg::Profile_<std::allocator<void>>; // constant definitions } // namespace msg } // namespace rmf_traffic_msgs #endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__PROFILE__STRUCT_HPP_
30.144654
152
0.759441
flitzmo-hso
3abaafa609bb981897b7a5b2a81dc3985f1b5850
825
cpp
C++
AtUnitTest/AutCharInfo.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
4
2019-11-10T21:56:40.000Z
2021-12-11T20:10:55.000Z
AtUnitTest/AutCharInfo.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
null
null
null
AtUnitTest/AutCharInfo.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
1
2019-11-11T08:38:59.000Z
2019-11-11T08:38:59.000Z
#include "AutIncludes.h" #include "AutMain.h" void ShowCharInfo(uint c) { Unicode::CharInfo ci = Unicode::CharInfo::Get(c); Str line; line.UInt(c).Add(" U+").UInt(c, 16, 4).Ch(' ') .Add(Unicode::Category::ValueToName(ci.m_cat)).Add(" (") .Add(Unicode::Category::ValueToCode(ci.m_cat)).Add(") width ") .UInt(ci.m_width).Add("\r\n"); Console::Out(line); } void CharInfoTest(Args& args) { if (!args.Any()) ShowCharInfo(0x27F3); else do { Seq arg = args.Next(); uint c; if (arg.StripPrefixInsensitive("0x")) c = arg.ReadNrUInt32(16); else c = arg.ReadNrUInt32Dec(); if (c == UINT32_MAX || arg.n) Console::Out(Str::Join("Expecting decimal or hexadecimal code point: ", arg, "\r\n")); else ShowCharInfo(c); } while (args.Any()); }
21.153846
91
0.591515
denisbider
3abdcf8b153be82f05584765f2ff0fa17718c2a0
4,980
tpp
C++
code/source/ui/game/editor/editorcomponent_ui.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/ui/game/editor/editorcomponent_ui.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/ui/game/editor/editorcomponent_ui.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
template<typename T> EditorComponentUi<T>::EditorComponentUi(T& comp): radius(EditorComponentUiTraits<ComponentType>::defaultRadius()), component(&comp), bgPanel(util::Coord::VF(0), radius), panelLayout(gui::LinearLayoutElement::Vertical, util::Coord::VF(0), util::Coord::VF(0)), titleLabel(EditorComponentTraits<ComponentType>::name(), util::Coord::VF(0)), resizeButtonLayout(gui::LinearLayoutElement::Horizontal, util::Coord::VF(0), util::Coord::VF(0)), resizeButton(util::Coord::VF(0), util::Coord::VF({resizeButtonVerticalRad*5, resizeButtonVerticalRad})), resizing(false), contentPanel(util::Coord::VF(0), util::Coord::VF(0)){ bgPanel.addSubElement(panelLayout); panelLayout.setMargin(false); panelLayout.setMaxSpacing(util::Coord::VF(0.1)); panelLayout.setMinSpacing(util::Coord::VF(0)); panelLayout.addSubElement(titleLabel); panelLayout.addSubElement(contentPanel); contentPanel.setStretchable(); panelLayout.addSubElement(resizeButtonLayout); resizeButtonLayout.setMargin(false); resizeButtonLayout.mirrorFirstNodeSide(); resizeButtonLayout.addSubElement(resizeButton); setMaxRadius(util::Coord::VSt(1.0)); setRadius(radius); resizeButton.setOnDraggingStartCallback([&] (gui::Element& caller){ resizing= true; resizeRadius= radius; //gUserInput->pushCursorLock(); }); resizeButton.setOnDraggingCallback([&] (gui::Element& caller){ // Had to add "this->" so gcc 4.7.2 wouldn't segfault :p (internal compiler error: Segmentation fault) resizeRadius += gUserInput->getCursorDifference().converted(util::Coord::View_Stretch)*util::Vec2d{0.5,-0.5}; if (resizeRadius.x < 0) resizeRadius.x= 0; if (resizeRadius.y < 0) resizeRadius.y= 0; this->setRadius(this->resizeRadius); global::Event e(global::Event::OnEditorComponentUiUserResize); e(global::Event::Object)= this; e.send(); }); resizeButton.setOnDraggingStopCallback([&] (gui::Element& caller){ resizing= false; //gUserInput->popCursorLock(); }); titleLabel.setTouchable(); titleLabel.setOnTriggerCallback([&](gui::Element& caller){ global::Event e(global::Event::EditorComponentUiDestroyRequest); e(global::Event::Object)= this; e.send(); }); onResize(); } template<typename T> EditorComponentUi<T>::~EditorComponentUi(){ } template<typename T> util::Str8 EditorComponentUi<T>::getComponentName(){ return EditorComponentTraits<ComponentType>::name(); } template<typename T> gui::Element& EditorComponentUi<T>::getSuperGuiElement(){ return bgPanel; } template<typename T> void EditorComponentUi<T>::setAdditionalTitle(const util::Str8& t){ titleLabel.setText(EditorComponentTraits<ComponentType>::name() + " - " + t); } template<typename T> T& EditorComponentUi<T>::getComponent(){ return *component; } template<typename T> void EditorComponentUi<T>::setMaxRadius(const util::Coord& max_radius_){ util::Coord max_radius= max_radius_.converted(radius.getType()); if (max_radius.y < 0.1) max_radius.y= 0.1; if (max_radius.x < 0.1) max_radius.x= 0.1; bool changed= false; if (util::abs(maxRadius.x - max_radius.x) > util::epsilon || util::abs(maxRadius.y - max_radius.y) > util::epsilon) changed= true; maxRadius= max_radius.converted(util::Coord::View_Stretch); setRadius(getRadius()); // Limit if (changed) onResize(); } template<typename T> void EditorComponentUi<T>::setRadius(const util::Coord& rad){ util::Coord rad_v= rad.converted(util::Coord::View_Stretch); util::Coord max_v= maxRadius.converted(util::Coord::View_Stretch); // Limit radius if (rad_v.y < 0.1) rad_v.y= 0.1; else if (rad_v.y > max_v.y) rad_v.y= max_v.y; if (rad_v.x < 0.1) rad_v.x= 0.1; else if (rad_v.x > max_v.x) rad_v.x= max_v.x; bool changed= false; if (util::abs(radius.x - rad.converted(radius.getType()).x) > util::epsilon || util::abs(radius.y - rad.converted(radius.getType()).y) > util::epsilon) changed= true; radius= rad_v.converted(radius.getType()); if (changed) onResize(); } template<typename T> const util::Coord& EditorComponentUi<T>::getRadius() const { return radius; } template<typename T> void EditorComponentUi<T>::onResize(){ bgPanel.setRadius(radius); bgPanel.setMaxRadius(radius); bgPanel.setMinRadius(radius); panelLayout.setMaxRadius(radius); panelLayout.setMinRadius(radius); panelLayout.setRadius(radius); util::Coord resize_layout_rad= util::Coord::VF({0,resizeButton.getRadius().y}) + util::Coord({radius.x, 0}, radius.getType()); resizeButtonLayout.setMaxRadius(resize_layout_rad); resizeButtonLayout.setMinRadius(resize_layout_rad); resizeButtonLayout.setRadius(resize_layout_rad); util::Coord content_rad= radius - util::Coord::VF({0,resizeButtonVerticalRad + titleLabel.getRadius().converted(util::Coord::View_Fit).y}); if (content_rad.x < 0) content_rad.x= 0; if (content_rad.y < 0) content_rad.y= 0; contentPanel.setMaxRadius(content_rad); contentPanel.setMinRadius(content_rad); contentPanel.setRadius(content_rad); }
29.820359
140
0.733735
crafn
3ac3b232ff4e245f2efdc52d14f788ee4da7a34c
16,160
cpp
C++
src/scsi2sd-util6/TerminalWx/src/GTerm/actions.cpp
gcasa/SCSI2SD-V6
9f169472d2e1c2aee3e2a0f970dd96778953ffb8
[ "BSD-3-Clause" ]
2
2020-11-29T01:28:03.000Z
2021-11-07T18:23:11.000Z
src/scsi2sd-util6/TerminalWx/src/GTerm/actions.cpp
tweakoz/SCSI2SD-V6
77db5f86712213e25c9b12fa5c9fa9c54b80cb80
[ "BSD-3-Clause" ]
null
null
null
src/scsi2sd-util6/TerminalWx/src/GTerm/actions.cpp
tweakoz/SCSI2SD-V6
77db5f86712213e25c9b12fa5c9fa9c54b80cb80
[ "BSD-3-Clause" ]
null
null
null
/* TerminalWx - A wxWidgets terminal widget Copyright (C) 1999 Timothy Miller 2004 Mark Erikson 2012-2013 Jeremy Salwen License: wxWindows License Version 3.1 (See the file license3.txt) */ #include "gterm.hpp" // For efficiency, this grabs all printing characters from buffer, up to // the end of the line or end of buffer void GTerm::normal_input() { int n, n_taken, i, c, y; #if 0 char str[100]; #endif #define IS_CTRL_CHAR(c) ((c)<32 || (c) ==127) if (IS_CTRL_CHAR(*input_data)) return; if (cursor_x >= width) { if (mode_flags & NOEOLWRAP) { cursor_x = width-1; } else { next_line(); } } n = 0; if (mode_flags & NOEOLWRAP) { while (!IS_CTRL_CHAR(input_data[n]) && n<data_len) n++; n_taken = n; if (cursor_x+n>=width) n = width-cursor_x; } else { while (!IS_CTRL_CHAR(input_data[n]) && n<data_len && cursor_x+n<width) n++; n_taken = n; } #if 0 memcpy(str, input_data, n); str[n] = 0; //printf("Processing %d characters (%d): %s\n", n, str[0], str); #endif if (mode_flags & INSERT) { changed_line(cursor_y, cursor_x, width-1); } else { changed_line(cursor_y, cursor_x, cursor_x+n-1); } y = linenumbers[cursor_y]*MAXWIDTH; if (mode_flags & INSERT) for (i=width-1; i>=cursor_x+n; i--) { text[y+i] = text[y+i-n]; color[y+i] = color[y+i-n]; } c = calc_color(fg_color, bg_color, mode_flags); for (i=0; i<n; i++) { text[y+cursor_x] = input_data[i]; color[y+cursor_x] = c; cursor_x++; } input_data += n_taken-1; data_len -= n_taken-1; } void GTerm::cr() { move_cursor(0, cursor_y); } void GTerm::lf() { if (cursor_y < scroll_bot) { move_cursor(cursor_x, cursor_y+1); } else { scroll_region(scroll_top, scroll_bot, 1); } } void GTerm::ff() { clear_area(0, scroll_top, width-1, scroll_bot); move_cursor(0, scroll_top); } void GTerm::tab() { int i, x = 0; for (i=cursor_x+1; i<width && !x; i++) if (tab_stops[i]) x = i; if (!x) x = (cursor_x+8) & -8; if (x < width) { move_cursor(x, cursor_y); } else { if (mode_flags & NOEOLWRAP) { move_cursor(width-1, cursor_y); } else { next_line(); } } } void GTerm::bs() { if (cursor_x>0) move_cursor(cursor_x-1, cursor_y); if (mode_flags & DESTRUCTBS) { clear_area(cursor_x, cursor_y, cursor_x, cursor_y); } } void GTerm::bell() { Bell(); } void GTerm::clear_param() { nparam = 0; memset(param, 0, sizeof(param)); q_mode = 0; got_param = 0; } void GTerm::keypad_numeric() { clear_mode_flag(KEYAPPMODE); } void GTerm::keypad_application() { set_mode_flag(KEYAPPMODE); } void GTerm::save_cursor() { save_attrib = mode_flags; save_x = cursor_x; save_y = cursor_y; } void GTerm::restore_cursor() { mode_flags = (mode_flags & ~15) | (save_attrib & 15); move_cursor(save_x, save_y); } void GTerm::set_tab() { tab_stops[cursor_x] = 1; } void GTerm::index_down() { lf(); } void GTerm::next_line() { lf(); cr(); } void GTerm::index_up() { if (cursor_y > scroll_top) { move_cursor(cursor_x, cursor_y-1); } else { scroll_region(scroll_top, scroll_bot, -1); } } void GTerm::reset() { int i; pending_scroll = 0; bg_color = 0; fg_color = 7; scroll_top = 0; scroll_bot = height-1; for (i=0; i<MAXHEIGHT; i++) linenumbers[i] = i; memset(tab_stops, 0, sizeof(tab_stops)); current_state = GTerm::normal_state; clear_mode_flag(NOEOLWRAP | CURSORAPPMODE | CURSORRELATIVE | NEWLINE | INSERT | UNDERLINE | BLINK | KEYAPPMODE | CURSORINVISIBLE); clear_area(0, 0, width-1, height-1); move_cursor(0, 0); } void GTerm::set_q_mode() { q_mode = 1; } // The verification test used some strange sequence which was // ^[[61"p // in a function called set_level, // but it didn't explain the meaning. Just in case I ever find out, // and just so that it doesn't leave garbage on the screen, I accept // the quote and mark a flag. void GTerm::set_quote_mode() { quote_mode = 1; } // for performance, this grabs all digits void GTerm::param_digit() { got_param = 1; param[nparam] = param[nparam]*10 + (*input_data)-'0'; } void GTerm::next_param() { nparam++; } void GTerm::cursor_left() { int n, x; n = param[0]; if (n<1) n = 1; x = cursor_x-n; if (x<0) x = 0; move_cursor(x, cursor_y); } void GTerm::cursor_right() { int n, x; n = param[0]; if (n<1) n = 1; x = cursor_x+n; if (x>=width) x = width-1; move_cursor(x, cursor_y); } void GTerm::cursor_up() { int n, y; n = param[0]; if (n<1) n = 1; y = cursor_y-n; if (y<0) y = 0; move_cursor(cursor_x, y); } void GTerm::cursor_down() { int n, y; n = param[0]; if (n<1) n = 1; y = cursor_y+n; if (y>=height) y = height-1; move_cursor(cursor_x, y); } void GTerm::cursor_position() { int x, y; x = param[1]; if (x<1) x=1; y = param[0]; if (y<1) y=1; if (mode_flags & CURSORRELATIVE) { move_cursor(x-1, y-1+scroll_top); } else { move_cursor(x-1, y-1); } } void GTerm::device_attrib() { char *str = "\033[?1;2c"; ProcessOutput(strlen(str), (unsigned char *)str); } void GTerm::delete_char() { int n, mx; n = param[0]; if (n<1) n = 1; mx = width-cursor_x; if (n>=mx) { clear_area(cursor_x, cursor_y, width-1, cursor_y); } else { shift_text(cursor_y, cursor_x, width-1, -n); } } void GTerm::set_mode() // h { switch (param[0] + 1000*q_mode) { case 1007: clear_mode_flag(NOEOLWRAP); break; case 1001: set_mode_flag(CURSORAPPMODE); break; case 1006: set_mode_flag(CURSORRELATIVE); break; case 4: set_mode_flag(INSERT); break; case 1003: RequestSizeChange(132, height); break; case 20: set_mode_flag(NEWLINE); break; case 12: clear_mode_flag(LOCALECHO); break; case 1025: clear_mode_flag(CURSORINVISIBLE); move_cursor(cursor_x, cursor_y); break; } } void GTerm::clear_mode() // l { switch (param[0] + 1000*q_mode) { case 1007: set_mode_flag(NOEOLWRAP); break; case 1001: clear_mode_flag(CURSORAPPMODE); break; case 1006: clear_mode_flag(CURSORRELATIVE); break; case 4: clear_mode_flag(INSERT); break; case 1003: RequestSizeChange(80, height); break; case 20: clear_mode_flag(NEWLINE); break; case 1002: current_state = vt52_normal_state; break; case 12: set_mode_flag(LOCALECHO); break; case 1025: set_mode_flag(CURSORINVISIBLE); break; move_cursor(cursor_x, cursor_y); break; } } void GTerm::request_param() { char str[40]; sprintf(str, "\033[%d;1;1;120;120;1;0x", param[0]+2); ProcessOutput(strlen(str), (unsigned char *)str); } void GTerm::set_margins() { int t, b; t = param[0]; if (t<1) t = 1; b = param[1]; if (b<1) b = height; if (pending_scroll) update_changes(); scroll_top = t-1; scroll_bot = b-1; if (cursor_y < scroll_top) move_cursor(cursor_x, scroll_top); if (cursor_y > scroll_bot) move_cursor(cursor_x, scroll_bot); } void GTerm::delete_line() { int n, mx; n = param[0]; if (n<1) n = 1; mx = scroll_bot-cursor_y+1; if (n>=mx) { clear_area(0, cursor_y, width-1, scroll_bot); } else { scroll_region(cursor_y, scroll_bot, n); } } void GTerm::status_report() { char str[20]; if (param[0] == 5) { char *str = "\033[0n"; ProcessOutput(strlen(str), (unsigned char *)str); } else if (param[0] == 6) { sprintf(str, "\033[%d;%dR", cursor_y+1, cursor_x+1); ProcessOutput(strlen(str), (unsigned char *)str); } } void GTerm::erase_display() { switch (param[0]) { case 0: clear_area(cursor_x, cursor_y, width-1, cursor_y); if (cursor_y<height-1) clear_area(0, cursor_y+1, width-1, height-1); break; case 1: clear_area(0, cursor_y, cursor_x, cursor_y); if (cursor_y>0) clear_area(0, 0, width-1, cursor_y-1); break; case 2: clear_area(0, 0, width-1, height-1); break; } } void GTerm::erase_line() { switch (param[0]) { case 0: clear_area(cursor_x, cursor_y, width-1, cursor_y); break; case 1: clear_area(0, cursor_y, cursor_x, cursor_y); break; case 2: clear_area(0, cursor_y, width-1, cursor_y); break; } } void GTerm::insert_line() { int n, mx; n = param[0]; if (n<1) n = 1; mx = scroll_bot-cursor_y+1; if (n>=mx) { clear_area(0, cursor_y, width-1, scroll_bot); } else { scroll_region(cursor_y, scroll_bot, -n); } } void GTerm::set_colors() { int n; if (!nparam && param[0] == 0) { clear_mode_flag(15); fg_color = 7; bg_color = 0; return; } for (n=0; n<=nparam; n++) { if (param[n]/10 == 4) { bg_color = param[n]%10; } else if (param[n]/10 == 3) { fg_color = param[n]%10; } else switch (param[n]) { case 0: clear_mode_flag(15); fg_color = 7; bg_color = 0; break; case 1: set_mode_flag(BOLD); break; case 4: set_mode_flag(UNDERLINE); break; case 5: set_mode_flag(BLINK); break; case 7: set_mode_flag(INVERSE); break; } } } void GTerm::clear_tab() { if (param[0] == 3) { memset(tab_stops, 0, sizeof(tab_stops)); } else if (param[0] == 0) { tab_stops[cursor_x] = 0; } } void GTerm::insert_char() { int n, mx; n = param[0]; if (n<1) n = 1; mx = width-cursor_x; if (n>=mx) { clear_area(cursor_x, cursor_y, width-1, cursor_y); } else { shift_text(cursor_y, cursor_x, width-1, n); } } void GTerm::screen_align() { int y, yp, x, c; c = calc_color(7, 0, 0); for (y=0; y<height; y++) { yp = linenumbers[y]*MAXWIDTH; changed_line(y, 0, width-1); for (x=0; x<width; x++) { text[yp+x] = 'E'; color[yp+x] = c; } } } void GTerm::erase_char() { int n, mx; n = param[0]; if (n<1) n = 1; mx = width-cursor_x; if (n>mx) n = mx; clear_area(cursor_x, cursor_y, cursor_x+n-1, cursor_y); } void GTerm::vt52_cursory() { // store y coordinate param[0] = (*input_data) - 32; if (param[0]<0) param[0] = 0; if (param[0]>=height) param[0] = height-1; } void GTerm::vt52_cursorx() { int x; x = (*input_data)-32; if (x<0) x = 0; if (x>=width) x = width-1; move_cursor(x, param[0]); } void GTerm::vt52_ident() { char *str = "\033/Z"; ProcessOutput(strlen(str), (unsigned char *)str); } #ifdef GTERM_PC void GTerm::pc_begin(void) { //printf("pc_begin...\n"); set_mode_flag(PC); //printf("pc_begin: mode_flags = %x\n", mode_flags); ProcessOutput((unsigned int)strlen(pc_machinename) + 1, (unsigned char *)pc_machinename); pc_oldWidth = Width(); pc_oldHeight = Height(); ResizeTerminal(80, 25); update_changes(); } void GTerm::pc_end(void) { // printf("pc_end...\n"); clear_mode_flag(PC); ResizeTerminal(pc_oldWidth, pc_oldHeight); update_changes(); } void GTerm::pc_cmd(void) { pc_curcmd = *input_data; //printf("pc_cmd: pc_curcmd = %d...\n", pc_curcmd); pc_argcount = 0; switch(pc_curcmd) { case GTERM_PC_CMD_CURONOFF : // <on/off> pc_numargs = 1; break; case GTERM_PC_CMD_MOVECURSOR : // <x> <y> pc_numargs = 2; break; case GTERM_PC_CMD_PUTTEXT : // <x> <y> <wid> <len> pc_numargs = 4; break; case GTERM_PC_CMD_WRITE : // <x> <y> <wid> <attr> pc_numargs = 4; break; case GTERM_PC_CMD_MOVETEXT : // <sx> <sy> <wid> <len> <dx> <dy> pc_numargs = 6; break; case GTERM_PC_CMD_BEEP : Bell(); break; case GTERM_PC_CMD_SELECTPRINTER : pc_numargs = 1; break; case GTERM_PC_CMD_PRINTCHAR : pc_numargs = 1; break; case GTERM_PC_CMD_PRINTCHARS : pc_numargs = 2; break; default : current_state = pc_cmd_state; break; } } void GTerm::pc_arg(void) { int i, yp, yp2; //printf("pc_arg: pc_curcmd = %d...\n", pc_curcmd); pc_args[pc_argcount++] = *input_data; if(pc_argcount == pc_numargs) { switch(pc_curcmd) { case GTERM_PC_CMD_CURONOFF : //printf("pc_arg: curonoff got %d\n", *input_data); if(*input_data) clear_mode_flag(CURSORINVISIBLE); else set_mode_flag(CURSORINVISIBLE); current_state = pc_cmd_state; changed_line(cursor_y, cursor_x, cursor_x); break; case GTERM_PC_CMD_MOVECURSOR : //printf("pc_arg: movecursor (%d, %d)\n", pc_args[0], pc_args[1]); move_cursor(pc_args[0], pc_args[1]); current_state = pc_cmd_state; break; case GTERM_PC_CMD_PUTTEXT : //printf("pc_arg: puttext got %d, %d, %d, %d\n", pc_args[0], pc_args[1], pc_args[2], pc_args[3]); pc_numdata = pc_args[2] * pc_args[3] * 2; pc_datacount = 0; pc_curx = pc_args[0]; pc_cury = pc_args[1]; if(pc_numdata) current_state = pc_data_state; else current_state = pc_cmd_state; break; case GTERM_PC_CMD_WRITE : //printf("pc_arg: write got %d, %d, %d, %d\n", pc_args[0], pc_args[1], pc_args[2], pc_args[3]); pc_numdata = pc_args[2]; pc_datacount = 0; pc_curx = pc_args[0]; pc_cury = pc_args[1]; if(pc_numdata) current_state = pc_data_state; else current_state = pc_cmd_state; break; case GTERM_PC_CMD_MOVETEXT : // <sx> <sy> <wid> <len> <dx> <dy> if(pc_args[1] < pc_args[5]) { for(i = 0; i < pc_args[3]; i++) { yp = linenumbers[pc_args[1] + i] * MAXWIDTH; yp2 = linenumbers[pc_args[5] + i] * MAXWIDTH; memmove(&text[yp2 + pc_args[4]], &text[yp + pc_args[0]], pc_args[2]); memmove(&color[yp2 + pc_args[4]], &color[yp + pc_args[0]], pc_args[2]); changed_line(pc_args[5] + i, pc_args[4], pc_args[4] + pc_args[2] - 1); } } else { for(i = pc_args[3] - 1; i >= 0; i--) { yp = linenumbers[pc_args[1] + i] * MAXWIDTH; yp2 = linenumbers[pc_args[5] + i] * MAXWIDTH; memmove(&text[yp2 + pc_args[4]], &text[yp + pc_args[0]], pc_args[2]); memmove(&color[yp2 + pc_args[4]], &color[yp + pc_args[0]], pc_args[2]); changed_line(pc_args[5] + i, pc_args[4], pc_args[4] + pc_args[2] - 1); } } current_state = pc_cmd_state; break; case GTERM_PC_CMD_SELECTPRINTER : pc_numdata = pc_args[0]; pc_datacount = 0; memset(pc_printername, 0, sizeof(pc_printername)); if(pc_numdata) current_state = pc_data_state; else { SelectPrinter(""); current_state = pc_cmd_state; } break; case GTERM_PC_CMD_PRINTCHAR : PrintChars(1, &pc_args[0]); current_state = pc_cmd_state; break; case GTERM_PC_CMD_PRINTCHARS : pc_numdata = (pc_args[0] << 8) + pc_args[1]; pc_datacount = 0; if(pc_numdata) current_state = pc_data_state; else current_state = pc_cmd_state; break; } } } void GTerm::pc_data(void) { int yp; //printf("pc_data: pc_curcmd = %d, pc_datacount = %d, pc_numdata = %d, pc_curx = %d, pc_cur_y = %d...\n", pc_curcmd, pc_datacount, pc_numdata, pc_curx, pc_cury); switch(pc_curcmd) { case GTERM_PC_CMD_PUTTEXT : yp = linenumbers[pc_cury] * MAXWIDTH; if(!(pc_datacount & 1)) { //printf("pc_data: got char %d\n", *input_data); text[yp + pc_curx] = *input_data; } else { //printf("pc_data: got attr %d\n", *input_data); color[yp + pc_curx] = *input_data << 4; } if(pc_datacount & 1) { changed_line(pc_cury, pc_args[0], pc_curx); pc_curx++; if(pc_curx == pc_args[0] + pc_args[2]) { pc_curx = pc_args[0]; pc_cury++; } } break; case GTERM_PC_CMD_WRITE : yp = linenumbers[pc_cury] * MAXWIDTH; text[yp + pc_curx] = *input_data; color[yp + pc_curx] = (unsigned short)pc_args[3] << 4; changed_line(pc_cury, pc_args[0], pc_curx); pc_curx++; break; case GTERM_PC_CMD_SELECTPRINTER : if(pc_datacount < GTERM_PC_MAXPRINTERNAME - 1) pc_printername[pc_datacount] = *input_data; if(pc_datacount == pc_numdata - 1) SelectPrinter(pc_printername); break; case GTERM_PC_CMD_PRINTCHARS : PrintChars(1, input_data); break; } pc_datacount++; if(pc_datacount == pc_numdata) current_state = pc_cmd_state; } #endif // GTERM_PC
21.319261
161
0.607983
gcasa
3ac7adc8a462e8499a6649ab5f851f6c35367c10
3,459
cpp
C++
test/unit_tests/MessageSerializerTest.cpp
aleks-f/kademlia
aed2841d6c5dae672047381a584b9057db515ca4
[ "BSL-1.0" ]
1
2021-03-17T05:43:12.000Z
2021-03-17T05:43:12.000Z
test/unit_tests/MessageSerializerTest.cpp
aleks-f/kademlia
aed2841d6c5dae672047381a584b9057db515ca4
[ "BSL-1.0" ]
27
2021-03-23T10:49:35.000Z
2021-12-21T08:57:44.000Z
test/unit_tests/MessageSerializerTest.cpp
aleks-f/kademlia
aed2841d6c5dae672047381a584b9057db515ca4
[ "BSL-1.0" ]
2
2021-06-22T14:55:36.000Z
2021-06-24T21:20:55.000Z
// Copyright (c) 2013-2014, David Keller // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the University of California, Berkeley 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 DAVID KELLER 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 REGENTS AND 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 "common.hpp" #include "kademlia/MessageSerializer.h" #include "kademlia/Message.h" #include "gtest/gtest.h" namespace { namespace k = kademlia; namespace kd = k::detail; struct MessageSerializerTest: public ::testing::Test { MessageSerializerTest(): id_{"abcd"} {} kd::id id_; protected: ~MessageSerializerTest() override { } void SetUp() override { } void TearDown() override { } }; TEST_F(MessageSerializerTest, can_be_constructed) { kd::MessageSerializer s{ id_ }; (void)s; } TEST_F(MessageSerializerTest, can_serialize_a_message_with_a_body) { kd::MessageSerializer s{ id_ }; kd::id const searched_id{ "1234" }; kd::id const token{ "ABCD" }; kd::FindPeerRequestBody const expected{ searched_id }; auto const b = s.serialize(expected, token); auto i = std::begin(b), e = std::end(b); kd::Header h; EXPECT_TRUE(! kd::deserialize(i, e, h)); EXPECT_EQ(kd::Header::V1, h.version_); EXPECT_EQ(kd::Header::FIND_PEER_REQUEST, h.type_); EXPECT_EQ(id_, h.source_id_); EXPECT_EQ(token, h.random_token_); kd::FindPeerRequestBody actual; EXPECT_TRUE(! kd::deserialize(i, e, actual)); EXPECT_TRUE(expected.peer_to_find_id_ == actual.peer_to_find_id_); EXPECT_TRUE(i == e); } TEST_F(MessageSerializerTest, can_serialize_a_message_without_body) { kd::MessageSerializer s{ id_ }; kd::id const searched_id{ "1234" }; kd::id const token{ "ABCD" }; auto const b = s.serialize(kd::Header::PING_REQUEST, token); auto i = std::begin(b), e = std::end(b); kd::Header h; EXPECT_TRUE(! kd::deserialize(i, e, h)); EXPECT_EQ(kd::Header::V1, h.version_); EXPECT_EQ(kd::Header::PING_REQUEST, h.type_); EXPECT_EQ(id_, h.source_id_); EXPECT_EQ(token, h.random_token_); EXPECT_TRUE(i == e); } }
32.027778
80
0.706563
aleks-f
3ac7fff21e137e38ff3770b0cde6ab02ffd0445c
261
cpp
C++
firurs_operator/firurs_operator/firurs_operator.cpp
InkaShev7777/figurs_operator
ccd87b8f0b9720cdbf1d6fae918a1ef2b65942d8
[ "Apache-2.0" ]
null
null
null
firurs_operator/firurs_operator/firurs_operator.cpp
InkaShev7777/figurs_operator
ccd87b8f0b9720cdbf1d6fae918a1ef2b65942d8
[ "Apache-2.0" ]
null
null
null
firurs_operator/firurs_operator/firurs_operator.cpp
InkaShev7777/figurs_operator
ccd87b8f0b9720cdbf1d6fae918a1ef2b65942d8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "Krug.h" int main() { Krug krug; Kvadrat kv; std::cout << krug; std::cout << "\nVvedite: "; std::cin >> krug; std::cout << krug; std::cout << "\n"; std::cout << kv; std::cin >> kv; std::cout << "\n"; std::cout << kv; }
13.736842
28
0.536398
InkaShev7777
3acafbe85fbc50e3a9968232f95789208d977ded
4,881
cpp
C++
src/Magnum/Math/Test/TypeTraitsTest.cpp
wivlaro/magnum
c9fb3bae3390bddc397b6cec1c5d74b17129ef22
[ "MIT" ]
null
null
null
src/Magnum/Math/Test/TypeTraitsTest.cpp
wivlaro/magnum
c9fb3bae3390bddc397b6cec1c5d74b17129ef22
[ "MIT" ]
null
null
null
src/Magnum/Math/Test/TypeTraitsTest.cpp
wivlaro/magnum
c9fb3bae3390bddc397b6cec1c5d74b17129ef22
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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 <Corrade/TestSuite/Tester.h> #include "Magnum/Math/TypeTraits.h" #include "Magnum/Math/Constants.h" namespace Magnum { namespace Math { namespace Test { struct TypeTraitsTest: Corrade::TestSuite::Tester { explicit TypeTraitsTest(); void equalsIntegral(); void equalsFloatingPoint0(); void equalsFloatingPoint1(); void equalsFloatingPointLarge(); void equalsFloatingPointInfinity(); void equalsFloatingPointNaN(); private: template<class> void _equalsIntegral(); template<class> void _equalsFloatingPoint0(); template<class> void _equalsFloatingPoint1(); template<class> void _equalsFloatingPointLarge(); template<class> void _equalsFloatingPointInfinity(); template<class> void _equalsFloatingPointNaN(); }; TypeTraitsTest::TypeTraitsTest() { addTests({&TypeTraitsTest::equalsIntegral, &TypeTraitsTest::equalsFloatingPoint0, &TypeTraitsTest::equalsFloatingPoint1, &TypeTraitsTest::equalsFloatingPointLarge, &TypeTraitsTest::equalsFloatingPointInfinity, &TypeTraitsTest::equalsFloatingPointNaN}); } void TypeTraitsTest::equalsIntegral() { _equalsIntegral<UnsignedByte>(); _equalsIntegral<Byte>(); _equalsIntegral<UnsignedShort>(); _equalsIntegral<Short>(); _equalsIntegral<UnsignedInt>(); _equalsIntegral<Int>(); _equalsIntegral<UnsignedLong>(); _equalsIntegral<Long>(); } template<class T> void TypeTraitsTest::_equalsIntegral() { CORRADE_VERIFY(!TypeTraits<T>::equals(1, 1+TypeTraits<T>::epsilon())); } void TypeTraitsTest::equalsFloatingPoint0() { _equalsFloatingPoint0<Float>(); #ifndef MAGNUM_TARGET_GLES _equalsFloatingPoint0<Double>(); #endif } template<class T> void TypeTraitsTest::_equalsFloatingPoint0() { CORRADE_VERIFY(TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()/T(2), T(0))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()*T(2), T(0))); } void TypeTraitsTest::equalsFloatingPoint1() { _equalsFloatingPoint1<Float>(); #ifndef MAGNUM_TARGET_GLES _equalsFloatingPoint1<Double>(); #endif } template<class T> void TypeTraitsTest::_equalsFloatingPoint1() { CORRADE_VERIFY(TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()/T(2), T(1))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()*T(3), T(1))); } void TypeTraitsTest::equalsFloatingPointLarge() { _equalsFloatingPointLarge<Float>(); #ifndef MAGNUM_TARGET_GLES _equalsFloatingPointLarge<Double>(); #endif } template<class T> void TypeTraitsTest::_equalsFloatingPointLarge() { CORRADE_VERIFY(TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(2), T(25))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(75), T(25))); } void TypeTraitsTest::equalsFloatingPointInfinity() { _equalsFloatingPointInfinity<Float>(); #ifndef MAGNUM_TARGET_GLES _equalsFloatingPointInfinity<Double>(); #endif } template<class T> void TypeTraitsTest::_equalsFloatingPointInfinity() { CORRADE_VERIFY(TypeTraits<T>::equals(Constants<T>::inf(), Constants<T>::inf())); } void TypeTraitsTest::equalsFloatingPointNaN() { _equalsFloatingPointNaN<Float>(); #ifndef MAGNUM_TARGET_GLES _equalsFloatingPointNaN<Double>(); #endif } template<class T> void TypeTraitsTest::_equalsFloatingPointNaN() { CORRADE_VERIFY(!TypeTraits<T>::equals(Constants<T>::nan(), Constants<T>::nan())); } }}} CORRADE_TEST_MAIN(Magnum::Math::Test::TypeTraitsTest)
35.115108
88
0.709896
wivlaro
3acd46ea3521c61fe4d866738b24af3ac655a7a2
2,164
cpp
C++
AtCoder/Grand/24/F.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
AtCoder/Grand/24/F.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
AtCoder/Grand/24/F.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool neg=c=='-'; neg?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return neg?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} template<class T>inline void mset(T a,int v,int n){memset(a,v,n*sizeof(a[0]));} const int N=20; int anslen=0; bool stk[N+2]; int ss=0; namespace T{ const int N=1<<23; int f[N]; inline void init(const int n){ mset(f,0,1<<(n+1)); } inline void ins(int s,int i){ for(int x=1;;x=(x<<1)|((s>>--i)&1)){ ++f[x]; if(i==0)break; } } int tmp_f[N]; void dfs_store(const int x){ tmp_f[x]=f[x]; if(f[x]==0)return; dfs_store(x<<1); dfs_store((x<<1)|1); } void dfs_mg(const int x,const int v){ if(tmp_f[v]==0)return; f[x]+=tmp_f[v]; dfs_mg(x<<1,v<<1); dfs_mg((x<<1)|1,(v<<1)|1); } void solve(const int x){ if(f[x]==0)return; const int lson=x<<1,rson=lson|1; solve(lson),solve(rson); dfs_store((lson<<1)|1),dfs_store(rson<<1); dfs_mg(lson,rson<<1),dfs_mg(rson,(lson<<1)|1); } void findans(const int x,const int dep,const int k){ if(f[x]<k)return; apmax(anslen,dep); findans(x<<1,dep+1,k); findans((x<<1)|1,dep+1,k); } bool putans(const int x,const int k){ if(f[x]<k)return false; if(ss==anslen)return true; ss++; stk[ss]=0; if(putans(x<<1,k))return true; stk[ss]=1; if(putans((x<<1)|1,k))return true; ss--; return false; } } int main(){ #ifndef ONLINE_JUDGE freopen("simple.in","r",stdin); freopen("simple.out","w",stdout); #endif const int n=ni; T::init(n); const int k=ni; for(int i=0;i<=n;i++){ static char str[(1<<N)+10]; scanf("%s",str); for(int s=0,ts=1<<i;s<ts;s++){ if(str[s]=='1'){ T::ins(s,i); } } } T::solve(1); T::findans(1,0,k); T::putans(1,k); for(int i=1;i<=ss;i++){ putchar('0'+stk[i]); } putchar('\n'); return 0; }
21.425743
79
0.598429
sshockwave
3acf5defcdea7949350f9bbc406559b90806cb28
4,926
cpp
C++
server/Orthanc-1.7.2/OrthancServer/Sources/QueryRetrieveHandler.cpp
nilaysaha/medimaging
476c87f103a5ff0b4ddc5c6abfe6034c9c981a47
[ "Apache-2.0" ]
1
2020-11-05T08:34:23.000Z
2020-11-05T08:34:23.000Z
server/Orthanc-1.7.2/OrthancServer/Sources/QueryRetrieveHandler.cpp
nilaysaha/medimaging
476c87f103a5ff0b4ddc5c6abfe6034c9c981a47
[ "Apache-2.0" ]
null
null
null
server/Orthanc-1.7.2/OrthancServer/Sources/QueryRetrieveHandler.cpp
nilaysaha/medimaging
476c87f103a5ff0b4ddc5c6abfe6034c9c981a47
[ "Apache-2.0" ]
1
2020-11-12T09:00:30.000Z
2020-11-12T09:00:30.000Z
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017-2020 Osimis S.A., Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "PrecompiledHeadersServer.h" #include "QueryRetrieveHandler.h" #include "OrthancConfiguration.h" #include "../../OrthancFramework/Sources/DicomNetworking/DicomControlUserConnection.h" #include "../../OrthancFramework/Sources/DicomParsing/FromDcmtkBridge.h" #include "../../OrthancFramework/Sources/Logging.h" #include "../../OrthancFramework/Sources/Lua/LuaFunctionCall.h" #include "LuaScripting.h" #include "ServerContext.h" namespace Orthanc { static void FixQueryLua(DicomMap& query, ServerContext& context, const std::string& modality) { static const char* LUA_CALLBACK = "OutgoingFindRequestFilter"; LuaScripting::Lock lock(context.GetLuaScripting()); if (lock.GetLua().IsExistingFunction(LUA_CALLBACK)) { LuaFunctionCall call(lock.GetLua(), LUA_CALLBACK); call.PushDicom(query); call.PushJson(modality); call.ExecuteToDicom(query); } } void QueryRetrieveHandler::Invalidate() { done_ = false; answers_.Clear(); } void QueryRetrieveHandler::Run() { if (!done_) { // Firstly, fix the content of the query for specific manufacturers DicomMap fixed; fixed.Assign(query_); // Secondly, possibly fix the query with the user-provider Lua callback FixQueryLua(fixed, context_, modality_.GetApplicationEntityTitle()); { DicomAssociationParameters params(localAet_, modality_); DicomControlUserConnection connection(params); connection.Find(answers_, level_, fixed, findNormalized_); } done_ = true; } } QueryRetrieveHandler::QueryRetrieveHandler(ServerContext& context) : context_(context), localAet_(context.GetDefaultLocalApplicationEntityTitle()), done_(false), level_(ResourceType_Study), answers_(false), findNormalized_(true) { } void QueryRetrieveHandler::SetModality(const std::string& symbolicName) { Invalidate(); modalityName_ = symbolicName; { OrthancConfiguration::ReaderLock lock; lock.GetConfiguration().GetDicomModalityUsingSymbolicName(modality_, symbolicName); } } void QueryRetrieveHandler::SetLevel(ResourceType level) { Invalidate(); level_ = level; } void QueryRetrieveHandler::SetQuery(const DicomTag& tag, const std::string& value) { Invalidate(); query_.SetValue(tag, value, false); } void QueryRetrieveHandler::CopyStringTag(const DicomMap& from, const DicomTag& tag) { const DicomValue* value = from.TestAndGetValue(tag); if (value == NULL || value->IsNull() || value->IsBinary()) { throw OrthancException(ErrorCode_InexistentTag); } else { SetQuery(tag, value->GetContent()); } } size_t QueryRetrieveHandler::GetAnswersCount() { Run(); return answers_.GetSize(); } void QueryRetrieveHandler::GetAnswer(DicomMap& target, size_t i) { Run(); answers_.GetAnswer(i).ExtractDicomSummary(target); } void QueryRetrieveHandler::SetFindNormalized(bool normalized) { Invalidate(); findNormalized_ = normalized; } }
28.473988
89
0.686561
nilaysaha
3ad012b71fc793e9ed98eb04812f4fcfe6102ee8
1,717
hpp
C++
products/BellHybrid/apps/include/Application.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
null
null
null
products/BellHybrid/apps/include/Application.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
null
null
null
products/BellHybrid/apps/include/Application.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <ApplicationCommon.hpp> namespace app { class Application : public ApplicationCommon { public: using ApplicationCommon::ApplicationCommon; void resumeIdleTimer(); void suspendIdleTimer(); explicit Application(std::string name, std::string parent = "", StatusIndicators statusIndicators = StatusIndicators{}, StartInBackground startInBackground = {false}, uint32_t stackDepth = 4096, sys::ServicePriority priority = sys::ServicePriority::Idle); protected: void attachPopups(const std::vector<gui::popup::ID> &popupsList) override; std::optional<gui::popup::Blueprint> popupBlueprintFallback(gui::popup::ID id) override; void startIdleTimer(); void restartIdleTimer(); void stopIdleTimer(); void stopAllAudio(); virtual void onStop(); private: sys::MessagePointer handleKBDKeyEvent(sys::Message *msgl) override; sys::MessagePointer handleApplicationSwitch(sys::Message *msgl) override; sys::MessagePointer handleAppClose(sys::Message *msgl) override; sys::MessagePointer handleAppFocusLost(sys::Message *msgl) override; void updateStatuses(gui::AppWindow *window) const override; virtual void onKeyPressed(); virtual void onStart(); bool idleTimerActiveFlag = true; }; } // namespace app
39.022727
96
0.619103
GravisZro
3ad257386342a5b08e45b901673d5fb572f1e2eb
2,817
inl
C++
include/glm/gtc/color_space.inl
hamoid/glslViewer
0d9ef4dd5eb9e53fb19a21a2da8fb543e64d6230
[ "BSD-3-Clause" ]
1
2019-11-21T20:56:29.000Z
2019-11-21T20:56:29.000Z
include/glm/gtc/color_space.inl
hamoid/glslViewer
0d9ef4dd5eb9e53fb19a21a2da8fb543e64d6230
[ "BSD-3-Clause" ]
null
null
null
include/glm/gtc/color_space.inl
hamoid/glslViewer
0d9ef4dd5eb9e53fb19a21a2da8fb543e64d6230
[ "BSD-3-Clause" ]
null
null
null
/// @ref gtc_color_space /// @file glm/gtc/color_space.inl namespace glm{ namespace detail { template <typename T, precision P, template <typename, precision> class vecType> struct compute_rgbToSrgb { GLM_FUNC_QUALIFIER static vecType<T, P> call(vecType<T, P> const& ColorRGB, T GammaCorrection) { vecType<T, P> const ClampedColor(clamp(ColorRGB, static_cast<T>(0), static_cast<T>(1))); return mix( pow(ClampedColor, vecType<T, P>(GammaCorrection)) * static_cast<T>(1.055) - static_cast<T>(0.055), ClampedColor * static_cast<T>(12.92), lessThan(ClampedColor, vecType<T, P>(static_cast<T>(0.0031308)))); } }; template <typename T, precision P> struct compute_rgbToSrgb<T, P, tvec4> { GLM_FUNC_QUALIFIER static tvec4<T, P> call(tvec4<T, P> const& ColorRGB, T GammaCorrection) { return tvec4<T, P>(compute_rgbToSrgb<T, P, tvec3>::call(tvec3<T, P>(ColorRGB), GammaCorrection), ColorRGB.w); } }; template <typename T, precision P, template <typename, precision> class vecType> struct compute_srgbToRgb { GLM_FUNC_QUALIFIER static vecType<T, P> call(vecType<T, P> const& ColorSRGB, T Gamma) { return mix( pow((ColorSRGB + static_cast<T>(0.055)) * static_cast<T>(0.94786729857819905213270142180095), vecType<T, P>(Gamma)), ColorSRGB * static_cast<T>(0.07739938080495356037151702786378), lessThanEqual(ColorSRGB, vecType<T, P>(static_cast<T>(0.04045)))); } }; template <typename T, precision P> struct compute_srgbToRgb<T, P, tvec4> { GLM_FUNC_QUALIFIER static tvec4<T, P> call(tvec4<T, P> const& ColorSRGB, T Gamma) { return tvec4<T, P>(compute_srgbToRgb<T, P, tvec3>::call(tvec3<T, P>(ColorSRGB), Gamma), ColorSRGB.w); } }; }//namespace detail template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<T, P> convertLinearToSRGB(vecType<T, P> const& ColorLinear) { return detail::compute_rgbToSrgb<T, P, vecType>::call(ColorLinear, static_cast<T>(0.41666)); } template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<T, P> convertLinearToSRGB(vecType<T, P> const& ColorLinear, T Gamma) { return detail::compute_rgbToSrgb<T, P, vecType>::call(ColorLinear, static_cast<T>(1) / Gamma); } template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<T, P> convertSRGBToLinear(vecType<T, P> const& ColorSRGB) { return detail::compute_srgbToRgb<T, P, vecType>::call(ColorSRGB, static_cast<T>(2.4)); } template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<T, P> convertSRGBToLinear(vecType<T, P> const& ColorSRGB, T Gamma) { return detail::compute_srgbToRgb<T, P, vecType>::call(ColorSRGB, Gamma); } }//namespace glm
37.065789
120
0.724885
hamoid
3ad8bc8a1d712c95f5709fa7c8f496d6484402fd
496
cpp
C++
mp/src/game/client/c_covenbuilding.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/client/c_covenbuilding.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/client/c_covenbuilding.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
#include "cbase.h" #include "c_covenbuilding.h" #undef CCovenBuilding LINK_ENTITY_TO_CLASS(coven_building, C_CovenBuilding); IMPLEMENT_CLIENTCLASS_DT(C_CovenBuilding, DT_CovenBuilding, CCovenBuilding) RecvPropInt(RECVINFO(m_BuildingType)), RecvPropInt(RECVINFO(m_iHealth)), RecvPropInt(RECVINFO(m_iMaxHealth)), RecvPropEHandle(RECVINFO(mOwner)), RecvPropInt(RECVINFO(m_iLevel)), END_RECV_TABLE() C_CovenBuilding::C_CovenBuilding() { m_BuildingType = BUILDING_DEFAULT; mOwner = NULL; }
23.619048
75
0.816532
rendenba
3ad93c6ef74c384cc10c021dc1f4604f9ccee29c
3,894
cc
C++
test/src/unit-cppapi-map.cc
ppetraki/TileDB
16f2423ade38b1b1084e9206462477f1623cd5ae
[ "MIT" ]
null
null
null
test/src/unit-cppapi-map.cc
ppetraki/TileDB
16f2423ade38b1b1084e9206462477f1623cd5ae
[ "MIT" ]
null
null
null
test/src/unit-cppapi-map.cc
ppetraki/TileDB
16f2423ade38b1b1084e9206462477f1623cd5ae
[ "MIT" ]
null
null
null
/** * @file unit-cppapi-map.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2017 TileDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @section DESCRIPTION * * Tests the C++ API for map related functions. */ #include "catch.hpp" #include "tiledb/sm/cpp_api/tiledb" using namespace tiledb; struct CPPMapFx { CPPMapFx() : vfs(ctx) { using namespace tiledb; if (vfs.is_dir("cpp_unit_map")) vfs.remove_dir("cpp_unit_map"); auto a1 = Attribute::create<int>(ctx, "a1"); auto a2 = Attribute::create<std::string>(ctx, "a2"); auto a3 = Attribute::create<std::array<double, 2>>(ctx, "a3"); a1.set_compressor({TILEDB_BLOSC_LZ, -1}); MapSchema schema(ctx); schema.add_attribute(a1).add_attribute(a2).add_attribute(a3); Map::create("cpp_unit_map", schema); } ~CPPMapFx() { if (vfs.is_dir("cpp_unit_map")) vfs.remove_dir("cpp_unit_map"); } Context ctx; VFS vfs; }; TEST_CASE_METHOD(CPPMapFx, "C++ API: Map", "[cppapi]") { Map map(ctx, "cpp_unit_map"); int simple_key = 10; std::vector<double> compound_key = {2.43, 214}; // Via independent item auto i1 = Map::create_item(ctx, simple_key); i1.set("a1", 1.234); i1["a2"] = std::string("someval"); i1["a3"] = std::array<double, 2>({{3, 2.4}}); CHECK_THROWS(map.add_item(i1)); i1["a1"] = 1; map.add_item(i1); map.flush(); using my_cell_t = std::tuple<int, std::string, std::array<double, 2>>; // write via tuple my_cell_t ret = map[simple_key][{"a1", "a2", "a3"}]; CHECK(std::get<0>(ret) == 1); CHECK(std::get<1>(ret) == "someval"); CHECK(std::get<2>(ret).size() == 2); CHECK(std::get<2>(ret)[0] == 3); map[compound_key][{"a1", "a2", "a3"}] = my_cell_t(2, "aaa", {{4.2, 1}}); map.flush(); CHECK((int)map[simple_key]["a1"] == 1); CHECK(map.get_item(simple_key).get<std::string>("a2") == "someval"); CHECK((map[simple_key].get<std::array<double, 2>>("a3").size()) == 2); ret = map[compound_key][{"a1", "a2", "a3"}]; CHECK(std::get<0>(ret) == 2); CHECK(std::get<1>(ret) == "aaa"); CHECK(std::get<2>(ret).size() == 2); CHECK(std::get<2>(ret)[0] == 4.2); } struct CPPMapFromMapFx { CPPMapFromMapFx() : vfs(ctx) { using namespace tiledb; if (vfs.is_dir("cpp_unit_map")) vfs.remove_dir("cpp_unit_map"); std::map<int, std::string> map; map[0] = "0"; map[1] = "12"; map[2] = "123"; Map::create(ctx, "cpp_unit_map", map); } ~CPPMapFromMapFx() { if (vfs.is_dir("cpp_unit_map")) vfs.remove_dir("cpp_unit_map"); } Context ctx; VFS vfs; }; TEST_CASE_METHOD(CPPMapFromMapFx, "C++ API: Map from std::map", "[cppapi]") { Map map(ctx, "cpp_unit_map"); CHECK(map[0].get<std::string>() == "0"); CHECK(map[1].get<std::string>() == "12"); CHECK(map[2].get<std::string>() == "123"); }
28.423358
80
0.642784
ppetraki
3ad98f815e1b52c12f25752956a77f8f0d938095
6,047
cpp
C++
Userland/DevTools/Profiler/SourceModel.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
2
2022-02-08T09:18:50.000Z
2022-02-21T17:57:23.000Z
Userland/DevTools/Profiler/SourceModel.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
null
null
null
Userland/DevTools/Profiler/SourceModel.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include "SourceModel.h" #include "Gradient.h" #include "Profile.h" #include <LibCore/File.h> #include <LibDebug/DebugInfo.h> #include <LibGfx/FontDatabase.h> #include <LibSymbolication/Symbolication.h> #include <stdio.h> namespace Profiler { class SourceFile final { public: struct Line { String content; size_t num_samples { 0 }; }; static constexpr StringView source_root_path = "/usr/src/serenity/"sv; public: SourceFile(StringView filename) { String source_file_name = filename.replace("../../", source_root_path); auto maybe_file = Core::File::open(source_file_name, Core::OpenMode::ReadOnly); if (maybe_file.is_error()) { dbgln("Could not map source file \"{}\". Tried {}. {} (errno={})", filename, source_file_name, maybe_file.error().string_literal(), maybe_file.error().code()); return; } auto file = maybe_file.value(); while (!file->eof()) m_lines.append({ file->read_line(1024), 0 }); } void try_add_samples(size_t line, size_t samples) { if (line < 1 || line - 1 >= m_lines.size()) return; m_lines[line - 1].num_samples += samples; } Vector<Line> const& lines() const { return m_lines; } private: Vector<Line> m_lines; }; SourceModel::SourceModel(Profile& profile, ProfileNode& node) : m_profile(profile) , m_node(node) { FlatPtr base_address = 0; Debug::DebugInfo const* debug_info; if (auto maybe_kernel_base = Symbolication::kernel_base(); maybe_kernel_base.has_value() && m_node.address() >= *maybe_kernel_base) { if (!g_kernel_debuginfo_object.has_value()) return; base_address = maybe_kernel_base.release_value(); if (g_kernel_debug_info == nullptr) g_kernel_debug_info = make<Debug::DebugInfo>(g_kernel_debuginfo_object->elf, String::empty(), base_address); debug_info = g_kernel_debug_info.ptr(); } else { auto const& process = node.process(); auto const* library_data = process.library_metadata.library_containing(node.address()); if (!library_data) { dbgln("no library data for address {:p}", node.address()); return; } base_address = library_data->base; debug_info = &library_data->load_debug_info(base_address); } VERIFY(debug_info != nullptr); // Try to read all source files contributing to the selected function and aggregate the samples by line. HashMap<String, SourceFile> source_files; for (auto const& pair : node.events_per_address()) { auto position = debug_info->get_source_position(pair.key - base_address); if (position.has_value()) { auto it = source_files.find(position.value().file_path); if (it == source_files.end()) { source_files.set(position.value().file_path, SourceFile(position.value().file_path)); it = source_files.find(position.value().file_path); } it->value.try_add_samples(position.value().line_number, pair.value); } } // Process source file map and turn content into view model for (auto const& file_iterator : source_files) { u32 line_number = 0; for (auto const& line_iterator : file_iterator.value.lines()) { line_number++; m_source_lines.append({ (u32)line_iterator.num_samples, line_iterator.num_samples * 100.0f / node.event_count(), file_iterator.key, line_number, line_iterator.content, }); } } } int SourceModel::row_count(GUI::ModelIndex const&) const { return m_source_lines.size(); } String SourceModel::column_name(int column) const { switch (column) { case Column::SampleCount: return m_profile.show_percentages() ? "% Samples" : "# Samples"; case Column::SourceCode: return "Source Code"; case Column::Location: return "Location"; case Column::LineNumber: return "Line"; default: VERIFY_NOT_REACHED(); return {}; } } struct ColorPair { Color background; Color foreground; }; static Optional<ColorPair> color_pair_for(SourceLineData const& line) { if (line.percent == 0) return {}; Color background = color_for_percent(line.percent); Color foreground; if (line.percent > 50) foreground = Color::White; else foreground = Color::Black; return ColorPair { background, foreground }; } GUI::Variant SourceModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const { auto const& line = m_source_lines[index.row()]; if (role == GUI::ModelRole::BackgroundColor) { auto colors = color_pair_for(line); if (!colors.has_value()) return {}; return colors.value().background; } if (role == GUI::ModelRole::ForegroundColor) { auto colors = color_pair_for(line); if (!colors.has_value()) return {}; return colors.value().foreground; } if (role == GUI::ModelRole::Font) { if (index.column() == Column::SourceCode) return Gfx::FontDatabase::default_fixed_width_font(); return {}; } if (role == GUI::ModelRole::Display) { if (index.column() == Column::SampleCount) { if (m_profile.show_percentages()) return ((float)line.event_count / (float)m_node.event_count()) * 100.0f; return line.event_count; } if (index.column() == Column::Location) return line.location; if (index.column() == Column::LineNumber) return line.line_number; if (index.column() == Column::SourceCode) return line.source_code; return {}; } return {}; } }
29.788177
171
0.616835
xspager
3adbba8de456623a6569a7134e05428084b1af56
5,636
hpp
C++
source/context.hpp
Oleh-Kravchenko/binder-aio
46e283e25e1a956f44fd83eadf5b3377885d9c87
[ "MIT" ]
null
null
null
source/context.hpp
Oleh-Kravchenko/binder-aio
46e283e25e1a956f44fd83eadf5b3377885d9c87
[ "MIT" ]
null
null
null
source/context.hpp
Oleh-Kravchenko/binder-aio
46e283e25e1a956f44fd83eadf5b3377885d9c87
[ "MIT" ]
2
2019-02-01T17:22:34.000Z
2020-03-23T10:45:03.000Z
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // Copyright (c) 2016 Sergey Lyskov <sergey.lyskov@jhu.edu> // // All rights reserved. Use of this source code is governed by a // MIT license that can be found in the LICENSE file. /// @file binder/context.hpp /// @brief Data structures to represent root context and modules /// @author Sergey Lyskov #ifndef _INCLUDED_context_hpp_ #define _INCLUDED_context_hpp_ #include <config.hpp> #include <clang/AST/Decl.h> #include <llvm/Support/raw_ostream.h> #include <string> #include <vector> #include <set> #include <unordered_set> #include <unordered_map> namespace binder { class Context; // structure to hold include set information and set of NamedDecl objects that was already queried for includes class IncludeSet { std::vector<std::string> includes_; std::unordered_map<clang::NamedDecl const *, int> stack_; public: // add include to the set void add_include(std::string const &i) { includes_.push_back(i); } // check if declaration is already in stack with level at lease as 'level' or lower and add it if it is not - return true if declaration was added bool add_decl(clang::NamedDecl const *, int level); std::vector<std::string> const &includes() const { return includes_; } // remove all includes and clear up the stack void clear(); }; /// Bindings Generator - represent object that can generate binding info for function, class, enum or data variable class Binder { public: typedef std::string string; virtual ~Binder() {} /// Generate string id that uniquly identify C++ binding object. For functions this is function prototype and for classes forward declaration. virtual string id() const = 0; // return Clang AST NamedDecl pointer to original declaration used to create this Binder virtual clang::NamedDecl * named_decl() const = 0; /// check if generator can create binding virtual bool bindable() const = 0; bool binding_requested() const { return binding_requested_; }; bool skipping_requested() const { return skipping_requested_; }; /// request bindings for this generator void request_bindings() { binding_requested_=true; } /// request skipping for this generator void request_skipping() { skipping_requested_=true; } /// check if user supplied config requested binding for the given declaration and if so request it virtual void request_bindings_and_skipping(Config const &) = 0; /// extract include needed for this generator and add it to includes vector virtual void add_relevant_includes(IncludeSet &) const = 0; /// generate binding code for this object and all its dependencies virtual void bind(Context &) = 0; // return true if code was already generate for this object bool is_binded() const; // return binding code string & code() { return code_; } string const & code() const { return code_; } /// return true if object declared in system header bool is_in_system_header(); // return vector of declarations that need to be binded before this one could virtual std::vector<clang::CXXRecordDecl const *> dependencies() const { return std::vector<clang::CXXRecordDecl const *>(); } /// return prefix portion of bindings code virtual string prefix_code() const { return string(); } /// return unique strting ID for this binder explicit operator std::string() const { return id(); /*named_decl()->getQualifiedNameAsString();*/ } private: bool binding_requested_=false, skipping_requested_=false; string code_; }; typedef std::shared_ptr< Binder > BinderOP; typedef std::vector<BinderOP> Binders; llvm::raw_ostream & operator << (llvm::raw_ostream & os, Binder const &b); /// Context - root, hold bindings info for whole TranslationUnit class Context { typedef std::string string; public: void add(BinderOP &); void generate(Config const &config); // find binder related to given type name and bind it void request_bindings(std::string const &type); /// generate C++ expression for module variable for namespace_ string module_variable_name(string const & namespace_); void add_insertion_operator(clang::FunctionDecl const *f); /// find gloval insertion operator for given type, return nullptr if not such operator find clang::FunctionDecl const * global_insertion_operator(clang::CXXRecordDecl const *); /// generate unique trace line containing `info` to insert into the code std::string trace_line(std::string const &info); private: /// bind all objects residing in namespaces and it dependency void bind(Config const &config); std::set<string> create_all_nested_namespaces(); /// check if forward declaration for CXXRecordDecl needed bool is_forward_needed(clang::CXXRecordDecl const *); /// add given class to 'aleady binded' set void add_to_binded(clang::CXXRecordDecl const *); /// sort vector of binders by dependecy so python imports could work void sort_binders(); /// map of function-ptr -> Decl* for global instertion operators so we can determent for which types can bind __repr__ std::map<std::string, clang::FunctionDecl const *> insertion_operators; /// array of all binderes from translation unit std::vector<BinderOP> binders; /// types → binder std::unordered_map<string, BinderOP> types; /// set of items unique id's to keep track of whats binders being added std::unordered_set<string> ids; /// set of items unique id's to keep track of whats binded and not std::set<string> binded; /// counter to generate unique trace lines for debug int trace_counter = -1; }; } // namespace binder #endif // _INCLUDED_context_hpp_
30.139037
147
0.745564
Oleh-Kravchenko
3adc7da39237ab68d55d9d13ff5cf32f329946ec
2,781
cpp
C++
movo_common/movo_third_party/simple_grasping/src/grasp_planner_node.cpp
aaronsnoswell/kinova-movo
380c7827a9cec12cc0f4f0cc19ce0b88775c6c51
[ "BSD-3-Clause" ]
37
2017-12-13T16:14:32.000Z
2022-02-19T03:12:52.000Z
movo_common/movo_third_party/simple_grasping/src/grasp_planner_node.cpp
aaronsnoswell/kinova-movo
380c7827a9cec12cc0f4f0cc19ce0b88775c6c51
[ "BSD-3-Clause" ]
71
2018-01-17T20:17:03.000Z
2022-03-23T19:48:45.000Z
movo_common/movo_third_party/simple_grasping/src/grasp_planner_node.cpp
aaronsnoswell/kinova-movo
380c7827a9cec12cc0f4f0cc19ce0b88775c6c51
[ "BSD-3-Clause" ]
32
2018-01-08T03:21:18.000Z
2022-02-19T03:12:47.000Z
/* * Copyright 2015, Fetch Robotics Inc. * 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 Fetch Robotics, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Michael Ferguson #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <simple_grasping/shape_grasp_planner.h> #include <grasp_msgs/GraspPlanningAction.h> class GraspPlannerNode { typedef actionlib::SimpleActionServer<grasp_msgs::GraspPlanningAction> server_t; public: GraspPlannerNode(ros::NodeHandle n) { // Planner planner_.reset(new simple_grasping::ShapeGraspPlanner(n)); // Action for grasp planning server_.reset(new server_t(n, "plan", boost::bind(&GraspPlannerNode::executeCallback, this, _1), false)); server_->start(); } private: void executeCallback(const grasp_msgs::GraspPlanningGoalConstPtr& goal) { grasp_msgs::GraspPlanningResult result; planner_->plan(goal->object, result.grasps, goal->gripper); server_->setSucceeded(result); } boost::shared_ptr<simple_grasping::ShapeGraspPlanner> planner_; boost::shared_ptr<server_t> server_; }; int main(int argc, char* argv[]) { ros::init(argc, argv, "grasp_planner"); ros::NodeHandle nh("~"); GraspPlannerNode planning(nh); ros::spin(); return 0; }
37.581081
89
0.730672
aaronsnoswell
3ae07d2568523d9ffa673b8ad8ab3e7f7321b56a
5,505
cc
C++
zircon/tools/kazoo/cdecl_output.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/tools/kazoo/cdecl_output.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/tools/kazoo/cdecl_output.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Fuchsia 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 <algorithm> #include <optional> #include <string_view> #include <utility> #include "tools/kazoo/output_util.h" #include "tools/kazoo/outputs.h" using namespace std::literals; namespace { constexpr std::pair<const char*, std::string_view> kFunctionAttributes[] = { {"const", "__CONST"}, }; constexpr std::pair<std::string_view, std::string_view> kHandleAttributes[] = { {"Acquire", "acquire_handle"}, {"Release", "release_handle"}, {"Use", "use_handle"}, }; bool IsHandleType(const Type& type) { if (type.IsPointer()) { return IsHandleType(type.DataAsPointer().pointed_to_type()); } if (type.IsVector()) { return IsHandleType(type.DataAsVector().contained_type()); } if (type.IsStruct()) { const auto& s = type.DataAsStruct().struct_data(); return std::any_of(s.members().begin(), s.members().end(), [](const auto& m) { return IsHandleType(m.type()); }); } return type.IsHandle(); } std::optional<std::string_view> HandleAnnotation(const StructMember& arg) { if (IsHandleType(arg.type())) { for (const auto [attr, anno] : kHandleAttributes) { if (arg.attributes().count(std::string(attr))) { return anno; } } switch (arg.type().optionality()) { case Optionality::kOutputOptional: case Optionality::kOutputNonOptional: return "acquire_handle"sv; default: return "use_handle"sv; } } return {}; } void CDeclarationMacro(const Syscall& syscall, std::string_view macro, std::string (*type_name)(const Type&), Writer* writer) { std::string decl(macro); decl += "("; decl += syscall.name(); decl += ", "; // First the return type. decl += type_name(syscall.kernel_return_type()); decl += ","; { // Now the function attributes. std::string attrs; if (syscall.is_noreturn()) { attrs += " __NO_RETURN"; } for (const auto [attr, anno] : kFunctionAttributes) { if (syscall.HasAttribute(attr)) { attrs += " "; attrs += anno; } } if (attrs.empty()) { decl += " /* no attributes */"; } else { decl += attrs; } } decl += ", "; // Now the argument count, used in assembly macros. decl += std::to_string(syscall.num_kernel_args()); decl += ",\n "; { // Now the argument list, just the names between parentheses. decl += "("; bool first = true; for (const auto& arg : syscall.kernel_arguments()) { if (!first) { decl += ", "; } first = false; decl += arg.name(); } decl += ")"; } decl += ", "; // Finally, the full prototype. if (syscall.kernel_arguments().empty()) { decl += "(void)"; } else { const bool unchecked = syscall.HasAttribute("HandleUnchecked"); bool first = true; for (const auto& arg : syscall.kernel_arguments()) { decl += first ? "("sv : ","sv; first = false; decl += "\n "; auto anno = HandleAnnotation(arg); if (anno) { decl += "_ZX_SYSCALL_ANNO("; decl += *anno; decl += unchecked ? "(\"FuchsiaUnchecked\")"sv : "(\"Fuchsia\")"sv; decl += ") "; } decl += type_name(arg.type()); decl += " "; decl += arg.name(); } decl += ")"; } decl += ")\n\n"; writer->Puts(decl.c_str()); } constexpr std::string_view PrivateMacro(const Syscall& syscall) { if (syscall.HasAttribute("vdsocall")) return "VDSO_SYSCALL"; if (syscall.HasAttribute("blocking")) return "BLOCKING_SYSCALL"; if (syscall.HasAttribute("internal")) return "INTERNAL_SYSCALL"; return "KERNEL_SYSCALL"; } } // namespace bool PublicDeclarationsOutput(const SyscallLibrary& library, Writer* writer) { if (!CopyrightHeaderWithCppComments(writer)) { return false; } writer->Puts(R"(#ifndef _ZX_SYSCALL_DECL #error "<zircon/syscalls.h> is the public API header" #endif )"); for (const auto& syscall : library.syscalls()) { if (!syscall->HasAttribute("internal") && !syscall->HasAttribute("testonly")) { CDeclarationMacro(*syscall, "_ZX_SYSCALL_DECL", GetCUserModeName, writer); } } return true; } bool TestonlyPublicDeclarationsOutput(const SyscallLibrary& library, Writer* writer) { if (!CopyrightHeaderWithCppComments(writer)) { return false; } writer->Puts(R"(#ifndef _ZX_SYSCALL_DECL #error "<zircon/testonly-syscalls.h> is the public API header" #endif )"); for (const auto& syscall : library.syscalls()) { if (!syscall->HasAttribute("internal") && syscall->HasAttribute("testonly")) { CDeclarationMacro(*syscall, "_ZX_SYSCALL_DECL", GetCUserModeName, writer); } } return true; } bool PrivateDeclarationsOutput(const SyscallLibrary& library, Writer* writer) { if (!CopyrightHeaderWithCppComments(writer)) { return false; } for (const auto& syscall : library.syscalls()) { CDeclarationMacro(*syscall, PrivateMacro(*syscall), GetCUserModeName, writer); } return true; } bool KernelDeclarationsOutput(const SyscallLibrary& library, Writer* writer) { if (!CopyrightHeaderWithCppComments(writer)) { return false; } for (const auto& syscall : library.syscalls()) { CDeclarationMacro(*syscall, PrivateMacro(*syscall), GetCKernelModeName, writer); } return true; }
25.252294
86
0.627611
sysidos
3ae243eac1c270d3e00e4d8c65d6eabc85bafcbc
1,805
cpp
C++
Bullet OAC/Material.cpp
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
Bullet OAC/Material.cpp
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
Bullet OAC/Material.cpp
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
/************************************************************************/ /* File: Material.cpp */ /* Autor: Gustavo Diel */ /* License: WTFLP */ /************************************************************************/ /* Basic Includes */ #include "stdafx.h" #include "Material.h" /* Utility Includes */ #include "Constants.h" #include "TextureLoader.h" Material::Material(const char* texture, glm::vec3 ambient, glm::vec3 specular, float alpha) { this->v3AmbientColor = ambient; this->v3SpecularColor = specular; this->fAlpha = alpha; this->uiTextureId = ptrTextureLoader->LoadTexture(texture); } Material::~Material() { } /** \brief Altera a cor Ambiente \param color cor ambiente */ void Material::SetAmbientColor(glm::vec3 color) { this->v3AmbientColor = color; } /** \brief Altera a cor Ambiente \param r cor vermelha \param g cor verde \param b cor azul */ void Material::SetAmbientColor(float r, float g, float b) { this->v3AmbientColor = vec3(r, g, b); } /** \brief Altera a cor Specular \param color cor Specular */ void Material::SetSpecularColor(glm::vec3 color) { this->v3SpecularColor = color; } /** \brief Altera a cor Specular \param r cor vermelha \param g cor verde \param b cor azul */ void Material::SetSpecularColor(float r, float g, float b) { this->v3SpecularColor = vec3(r, g, b); } /** \brief Altera o alpha do material \param alpha indice alpha */ void Material::SetAlpha(float alpha) { this->fAlpha = alpha; } /** \brief Define a textura do material \param texture caminho para a textura */ void Material::SetTexture(const char* texture) { this->uiTextureId = ptrTextureLoader->LoadTexture(texture); }
23.141026
91
0.593906
Schweigert
3ae27d0c24d259da8601cb958c1c1e76d549c219
1,057
cpp
C++
Source/GameService/GameFlow/GsGameFlowGame.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
3
2019-06-25T05:09:47.000Z
2020-09-30T18:06:17.000Z
Source/GameService/GameFlow/GsGameFlowGame.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
null
null
null
Source/GameService/GameFlow/GsGameFlowGame.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
2
2018-10-15T08:09:16.000Z
2020-04-07T05:25:52.000Z
#include "GsGameFlowGame.h" #include "GameService.h" #include "./Stage/StageGame/GsStageManagerGame.h" FGsGameFlowGame::FGsGameFlowGame() : FGsGameFlowBase(FGsGameFlow::Mode::GAME) { } FGsGameFlowGame::~FGsGameFlowGame() { GSLOG(Warning, TEXT("FGsGameFlowGame : ~FGsGameFlowGame")); } void FGsGameFlowGame::Init() { GSLOG(Warning, TEXT("FGsGameFlowGame : Init")); } void FGsGameFlowGame::Enter() { GSLOG(Warning, TEXT("FGsGameFlowGame : Enter")); _stageManager = TUniquePtr<FGsStageManagerGame>(new FGsStageManagerGame()); if (_stageManager.IsValid()) { _stageManager->InitState(); } } void FGsGameFlowGame::Exit() { if (_stageManager.IsValid()) { _stageManager->RemoveAll(); } GSLOG(Warning, TEXT("FGsGameFlowGame : Exit")); } void FGsGameFlowGame::Update() { GSLOG(Warning, TEXT("FGsGameFlowGame : Update")); } void FGsGameFlowGame::OnReconnectionStart() { GSLOG(Warning, TEXT("FGsGameFlowGame : OnReconectionStart")); } void FGsGameFlowGame::OnReconnectionEnd() { GSLOG(Warning, TEXT("FGsGameFlowGame : OnReconectionEnd")); }
19.943396
77
0.738884
BaekTaehyun
3aea94a88acbb6cc87d5cadb6963a225f09951fb
5,105
hpp
C++
PlayRho/Common/Position.hpp
shybovycha/PlayRho
eb4319022d324ebd6ada458b3410b00d00daac2c
[ "Zlib" ]
null
null
null
PlayRho/Common/Position.hpp
shybovycha/PlayRho
eb4319022d324ebd6ada458b3410b00d00daac2c
[ "Zlib" ]
null
null
null
PlayRho/Common/Position.hpp
shybovycha/PlayRho
eb4319022d324ebd6ada458b3410b00d00daac2c
[ "Zlib" ]
null
null
null
/* * Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef PLAYRHO_COMMON_POSITION_HPP #define PLAYRHO_COMMON_POSITION_HPP #include <PlayRho/Common/Templates.hpp> #include <PlayRho/Common/Settings.hpp> #include <PlayRho/Common/Vector2.hpp> namespace playrho { namespace d2 { /// @brief 2-D positional data structure. /// @details A 2-element length and angle pair suitable for representing a linear and /// angular position in 2-D. /// @note This structure is likely to be 12-bytes large (at least on 64-bit platforms). struct Position { Length2 linear; ///< Linear position. Angle angular; ///< Angular position. }; /// @brief Equality operator. /// @relatedalso Position constexpr bool operator==(const Position& lhs, const Position& rhs) { return (lhs.linear == rhs.linear) && (lhs.angular == rhs.angular); } /// @brief Inequality operator. /// @relatedalso Position constexpr bool operator!=(const Position& lhs, const Position& rhs) { return (lhs.linear != rhs.linear) || (lhs.angular != rhs.angular); } /// @brief Negation operator. /// @relatedalso Position constexpr Position operator- (const Position& value) { return Position{-value.linear, -value.angular}; } /// @brief Positive operator. /// @relatedalso Position constexpr Position operator+ (const Position& value) { return value; } /// @brief Addition assignment operator. /// @relatedalso Position constexpr Position& operator+= (Position& lhs, const Position& rhs) { lhs.linear += rhs.linear; lhs.angular += rhs.angular; return lhs; } /// @brief Addition operator. /// @relatedalso Position constexpr Position operator+ (const Position& lhs, const Position& rhs) { return Position{lhs.linear + rhs.linear, lhs.angular + rhs.angular}; } /// @brief Subtraction assignment operator. /// @relatedalso Position constexpr Position& operator-= (Position& lhs, const Position& rhs) { lhs.linear -= rhs.linear; lhs.angular -= rhs.angular; return lhs; } /// @brief Subtraction operator. /// @relatedalso Position constexpr Position operator- (const Position& lhs, const Position& rhs) { return Position{lhs.linear - rhs.linear, lhs.angular - rhs.angular}; } /// @brief Multiplication operator. constexpr Position operator* (const Position& pos, const Real scalar) { return Position{pos.linear * scalar, pos.angular * scalar}; } /// @brief Multiplication operator. /// @relatedalso Position constexpr Position operator* (const Real scalar, const Position& pos) { return Position{pos.linear * scalar, pos.angular * scalar}; } } // namespace d2 /// @brief Determines if the given value is valid. /// @relatedalso d2::Position template <> constexpr bool IsValid(const d2::Position& value) noexcept { return IsValid(value.linear) && IsValid(value.angular); } namespace d2 { /// Gets the position between two positions at a given unit interval. /// @param pos0 Position at unit interval value of 0. /// @param pos1 Position at unit interval value of 1. /// @param beta Unit interval (value between 0 and 1) of travel between position 0 and /// position 1. /// @return position 0 if <code>pos0 == pos1</code> or <code>beta == 0</code>, /// position 1 if <code>beta == 1</code>, or at the given unit interval value /// between position 0 and position 1. /// @relatedalso Position constexpr Position GetPosition(const Position pos0, const Position pos1, const Real beta) noexcept { assert(IsValid(pos0)); assert(IsValid(pos1)); assert(IsValid(beta)); // Note: have to be careful how this is done. // If pos0 == pos1 then return value should always be equal to pos0 too. // But if Real is float, pos0 * (1 - beta) + pos1 * beta can fail this requirement. // Meanwhile, pos0 + (pos1 - pos0) * beta always works. // pos0 * (1 - beta) + pos1 * beta // pos0 - pos0 * beta + pos1 * beta // pos0 + (pos1 * beta - pos0 * beta) // pos0 + (pos1 - pos0) * beta return pos0 + (pos1 - pos0) * beta; } } // namespace d2 } // namespace playrho #endif // PLAYRHO_COMMON_POSITION_HPP
31.90625
94
0.701077
shybovycha
3aef98d451de32eb721d8d70369cca0251478a29
208
cpp
C++
documentation/tutorial/examples/process/path-of-executable/path-of-executable.cpp
progrock-libraries/kickstart
d62c22efc92006dd76d455cf8f9d4f2a045e9126
[ "MIT" ]
2
2021-09-21T18:34:27.000Z
2022-02-13T02:50:57.000Z
documentation/tutorial/examples/process/path-of-executable/path-of-executable.cpp
progrock-libraries/kickstart
d62c22efc92006dd76d455cf8f9d4f2a045e9126
[ "MIT" ]
null
null
null
documentation/tutorial/examples/process/path-of-executable/path-of-executable.cpp
progrock-libraries/kickstart
d62c22efc92006dd76d455cf8f9d4f2a045e9126
[ "MIT" ]
null
null
null
#include <kickstart/all.hpp> using namespace kickstart::all; void cppmain() { out << fsx::path_of_executable().to_string() << endl; } auto main() -> int { return with_exceptions_displayed( cppmain ); }
20.8
67
0.697115
progrock-libraries