blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
a058664831b68baaa21694b4700617e5b2fecdd4
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/APPS/SipSymbol/SipSymbol.cpp
a0b5003886e0c9551acd55ebf8c7d05d65174fc8
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
17,185
cpp
#include <windows.h> // For all that Windows stuff #include "resource.h" #include "SipSymbol.h" // Program-specific stuff #include "ETC.h" #include "s1d13521.h" //---------------------------------------------------------------------- // Global data HINSTANCE g_hInstance; // Program instance handle HWND g_hWndMain = NULL; HINSTANCE g_hCoreDll = NULL; HHOOK g_hKeyHook = NULL; SETWINDOWSHOOKEX g_fnSetWindowsHookEx; UNHOOKWINDOWSHOOKEX g_fnUnhookWindowsHookEx; CALLNEXTHOOKEX g_fnCallNextHookEx; #define CANDXSIZE 239 #define CANDYSIZE 30 #define CANDPAGESIZE 9 const static RECT rcCandCli = { 0, 0, 239, 29 }; const static RECT rcLArrow = { 2, 4, 14, 25 }, rcRArrow = { 225, 4, 236, 25 }; const static RECT rcBtn[9] = { { 17, 4, 38, 25 }, { 40, 4, 61, 25 }, { 63, 4, 84, 25 }, { 86, 4, 107, 25 }, { 109, 4, 130, 25 }, { 132, 4, 153, 25 }, { 155, 4, 176, 25 }, { 178, 4, 199, 25 }, { 201, 4, 222, 25 } }; HBITMAP g_hBMCand, g_hBMCandNum, g_hBMCandArr[2]; BOOL g_bWifiOnOff = FALSE; BOOL g_bSysVolCtrl = FALSE; static struct _CANDLIST { TCHAR szKey[3]; TCHAR chVKey; BOOL bShift; } CandList[] = { {_T("!"), _T('1'), TRUE}, {_T("@"), _T('2'), TRUE}, {_T("#"), _T('3'), TRUE}, {_T("$"), _T('4'), TRUE}, {_T("%"), _T('5'), TRUE}, {_T("^"), _T('6'), TRUE}, {_T("&&"), _T('7'), TRUE}, {_T("*"), _T('8'), TRUE}, {_T("("), _T('9'), TRUE}, {_T(")"), _T('0'), TRUE}, {_T("-"), VK_SUBTRACT, FALSE}, {_T("_"), VK_HYPHEN, TRUE}, {_T("="), VK_EQUAL, FALSE}, {_T("+"), VK_EQUAL, TRUE}, {_T("["), VK_LBRACKET, FALSE}, {_T("{"), VK_LBRACKET, TRUE}, {_T("}"), VK_RBRACKET, TRUE}, {_T("]"), VK_RBRACKET, FALSE}, {_T("\\"), VK_BACKSLASH, FALSE}, {_T("|"), VK_BACKSLASH, TRUE}, {_T(";"), VK_SEMICOLON, FALSE}, {_T(":"), VK_SEMICOLON, TRUE}, {_T("\'"), VK_APOSTROPHE, FALSE}, {_T("\""), VK_APOSTROPHE, TRUE}, {_T("<"), VK_COMMA, TRUE}, {_T(">"), VK_COMMA, FALSE}, {_T("?"), VK_SLASH, TRUE}, {_T("`"), VK_BACKQUOTE, FALSE}, {_T("~"), VK_BACKQUOTE, TRUE}, {_T(","), VK_PERIOD, TRUE}, }; const static DWORD CANDLISTCOUNT = dim(CandList); static DWORD g_dwCLSelect; UINT g_uMsgUfn = RegisterWindowMessage(_T("OMNIBOOK_MESSAGE_UFN")); UINT g_uMsgBatState = RegisterWindowMessage(_T("OMNIBOOK_MESSAGE_BATSTATE")); int g_nModeUfn = -1; BOOL g_bIsAttachUfn = FALSE; extern int ufnGetCurrentClientName(void); extern BOOL ufnChangeCurrentClient(int nMode); extern int ufnGetCurrentMassStorage(void); extern BOOL ufnChangeCurrentMassStorage(int nType); //====================================================================== // Program entry point int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { MSG msg; int rc = 0; HWND hwndMain; if (IsAlreadyExist(lpCmdLine)) return 0x01; // Initialize this instance. hwndMain = InitInstance(hInstance, lpCmdLine, nCmdShow); if (hwndMain == 0) return 0x10; g_nModeUfn = ufnGetCurrentClientName(); // Application message loop while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Instance cleanup return TermInstance(hInstance, msg.wParam); } BOOL IsAlreadyExist(LPWSTR lpCmdLine) { HWND hWnd = FindWindow(CLASS_NAME, NULL); if (hWnd) { if (0 == wcsncmp(lpCmdLine, L"EXIT", 4)) { PostMessage(hWnd, WM_CLOSE, 0, 0); } else { SetForegroundWindow(hWnd); } return TRUE; } return FALSE; } //---------------------------------------------------------------------- // InitInstance - Instance initialization HWND InitInstance(HINSTANCE hInstance, LPWSTR lpCmdLine, int nCmdShow) { WNDCLASS wc; HWND hWnd; // Save program instance handle in global variable. g_hInstance = hInstance; g_hCoreDll = LoadLibrary(_T("coredll.dll")); if (NULL == g_hCoreDll) return 0; g_fnSetWindowsHookEx = (SETWINDOWSHOOKEX)GetProcAddress(g_hCoreDll, L"SetWindowsHookExW"); g_fnUnhookWindowsHookEx = (UNHOOKWINDOWSHOOKEX)GetProcAddress(g_hCoreDll, L"UnhookWindowsHookEx"); g_fnCallNextHookEx = (CALLNEXTHOOKEX)GetProcAddress(g_hCoreDll, L"CallNextHookEx"); g_hKeyHook = g_fnSetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyHookProc, hInstance, 0); // Register application main window class. wc.style = CS_VREDRAW | CS_HREDRAW | CS_IME;//0; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);//0 wc.lpszMenuName = NULL; wc.lpszClassName = CLASS_NAME; if (RegisterClass(&wc) == 0) return 0; // Create main window. hWnd = CreateWindowEx(WS_EX_TOPMOST | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW, CLASS_NAME, _T("SipSymbol"), WS_POPUP, 600-CANDXSIZE, 800-CANDYSIZE, CANDXSIZE, CANDYSIZE, NULL, NULL, hInstance, NULL); if (!IsWindow(hWnd)) return 0; // Standard show and update calls ShowWindow(hWnd, SW_HIDE); UpdateWindow(hWnd); return hWnd; } //---------------------------------------------------------------------- // TermInstance - Program cleanup int TermInstance(HINSTANCE hInstance, int nDefRC) { if (g_hKeyHook) { g_fnUnhookWindowsHookEx(g_hKeyHook); g_hKeyHook = NULL; } if (g_hCoreDll) { FreeLibrary(g_hCoreDll); g_hCoreDll = NULL; } return nDefRC; } void DrawBitmap(HDC hDC, long xStart, long yStart, HBITMAP hBitmap) { HDC hMemDC; HBITMAP hBMOld; BITMAP bm; POINT pt; hMemDC = CreateCompatibleDC(hDC); hBMOld = (HBITMAP) SelectObject(hMemDC, hBitmap); GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm); pt.x = bm.bmWidth; pt.y = bm.bmHeight; BitBlt(hDC, xStart, yStart, pt.x, pt.y, hMemDC, 0, 0, SRCCOPY); SelectObject(hMemDC, hBMOld); DeleteDC(hMemDC); return; } BOOL CheckOmnibookRegistry(LPCTSTR lpValueName) { BOOL bRet = FALSE; HKEY hKey; if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Omnibook"), 0, KEY_ALL_ACCESS, &hKey)) { DWORD dwType = REG_DWORD, cbData = sizeof(bRet); RegQueryValueEx(hKey, lpValueName, NULL, &dwType, (LPBYTE)&bRet, &cbData); RegCloseKey(hKey); } return bRet; } //====================================================================== // Message handling procedures for main window //---------------------------------------------------------------------- LRESULT DoUfnMain(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { // wParam : UFN_DETACH(0), UFN_ATTACH(1) // lParam : ... RETAILMSG(0, (_T("DoUfnMain(%d, %d)\r\n"), wParam, lParam)); if (0 == g_nModeUfn) // Serial_Class { if (0 == wParam) // UFN_DETACH g_bIsAttachUfn = FALSE; else if (1 == wParam) // UFN_ATTACH g_bIsAttachUfn = TRUE; } else if (1 == g_nModeUfn) // Mass_Storage_Class { if (0 == wParam) // UFN_DETACH { if (TRUE == g_bIsAttachUfn) { HDC hDC = GetDC(HWND_DESKTOP); ExtEscape(hDC, DRVESC_SET_DSPUPDSTATE, DSPUPD_PART, NULL, 0, NULL); ExtEscape(hDC, DRVESC_SET_WAVEFORMMODE, WAVEFORM_GC, NULL, 0, NULL); ExtEscape(hDC, DRVESC_SET_DIRTYRECT, TRUE, NULL, 0, NULL); { DISPUPDATE du; du.bWriteImage = TRUE; du.pRect = NULL; du.duState = DSPUPD_FULL; du.bBorder = FALSE; du.wfMode = WAVEFORM_GC; ExtEscape(hDC, DRVESC_DISP_UPDATE, sizeof(du), (LPCSTR)&du, 0, NULL); } ReleaseDC(HWND_DESKTOP, hDC); } g_bIsAttachUfn = FALSE; } else if (1 == wParam) // UFN_ATTACH { g_bIsAttachUfn = TRUE; SYSTEM_POWER_STATUS_EX2 sps = {0,}; GetSystemPowerStatusEx2(&sps, sizeof(sps), TRUE); BYTE fAcOn = !((1<<0) & sps.BatteryAverageCurrent); BYTE fChgDone = !((1<<2) & sps.BatteryAverageCurrent); //if (fAcOn) { TCHAR szCmdLine[MAX_PATH] = {0,}; _stprintf_s(szCmdLine, MAX_PATH, fChgDone ? _T("BATCOMPLETE") : _T("BATCHARGING")); LPCTSTR lpszPathName = _T("\\Windows\\Omnibook_Command.exe"); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (CreateProcess(lpszPathName, szCmdLine, 0, 0, 0, 0, 0, 0, 0, &pi)) { WaitForSingleObject(pi.hThread, 5000); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } } } return 0; } LRESULT DoBatStateMain(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { BYTE fBatteryState = (BYTE)wParam; BYTE fAcOn = !((1<<0) & fBatteryState); BYTE fChgDone = !((1<<2) & fBatteryState); RETAILMSG(0, (_T("DoBatStateMain(%d, %d, %d)\r\n"), fAcOn, fChgDone, g_bIsAttachUfn)); if (0 == g_nModeUfn) // Serial_Class { } else if (1 == g_nModeUfn) // Mass_Storage_Class { if (g_bIsAttachUfn && fAcOn) { TCHAR szCmdLine[MAX_PATH] = {0,}; _stprintf_s(szCmdLine, MAX_PATH, fChgDone ? _T("BATCOMPLETE") : _T("BATCHARGING")); LPCTSTR lpszPathName = _T("\\Windows\\Omnibook_Command.exe"); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (CreateProcess(lpszPathName, szCmdLine, 0, 0, 0, 0, 0, 0, 0, &pi)) { WaitForSingleObject(pi.hThread, 5000); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } } return 0; } LRESULT DoPaintMain(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { HDC hDC; PAINTSTRUCT ps; DWORD iLoop, iStart; int iSaveBkMode; RECT rect; hDC = BeginPaint(hWnd, &ps); if (1) { DrawBitmap(hDC, 0, 0, g_hBMCand); iSaveBkMode = SetBkMode(hDC, TRANSPARENT); iStart = (g_dwCLSelect / CANDPAGESIZE) * CANDPAGESIZE; for (iLoop=0; iLoop<CANDPAGESIZE && iStart+iLoop<CANDLISTCOUNT; iLoop++) { rect.left = rcBtn[iLoop].left + 2; rect.right = rcBtn[iLoop].right + 2; rect.top = rcBtn[iLoop].top; rect.bottom = rcBtn[iLoop].bottom; DrawText(hDC, CandList[iStart + iLoop].szKey, (_T('&') == CandList[iStart + iLoop].szKey[0]) ? 2 : 1, &rect, DT_CENTER | DT_VCENTER); } SetBkMode(hDC, iSaveBkMode); for (; iLoop < 9; iLoop++) DrawBitmap(hDC, rcBtn[iLoop].left + 1, rcBtn[iLoop].top + 6, g_hBMCandNum); if (iStart) DrawBitmap(hDC, 6, 8, g_hBMCandArr[0]); if (iStart + 9 < CANDLISTCOUNT) DrawBitmap(hDC, 228, 8, g_hBMCandArr[1]); } EndPaint(hWnd, &ps); return 0; } LRESULT DoLbuttonDown(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { DestroyWindow(hWnd); return 0; } LRESULT DoDestroy(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { DeleteObject(g_hBMCand); DeleteObject(g_hBMCandNum); DeleteObject(g_hBMCandArr[0]); DeleteObject(g_hBMCandArr[1]); PostQuitMessage(0); return 0; } LRESULT DoCreate(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam; g_hWndMain = hWnd; g_hBMCand = LoadBitmap(lpcs->hInstance, MAKEINTRESOURCE(IDB_CANDIDATE)); g_hBMCandNum = LoadBitmap(lpcs->hInstance, MAKEINTRESOURCE(IDB_CANDNUMBER)); g_hBMCandArr[0] = LoadBitmap(lpcs->hInstance, MAKEINTRESOURCE(IDB_CANDARROW1)); g_hBMCandArr[1] = LoadBitmap(lpcs->hInstance, MAKEINTRESOURCE(IDB_CANDARROW2)); g_bWifiOnOff = CheckOmnibookRegistry(_T("CfgWifiOnOff")); g_bSysVolCtrl = CheckOmnibookRegistry(_T("CfgSysVolCtrl")); RETAILMSG(1, (_T("g_bWifiOnOff(%d), g_bSysVolCtrl(%d)\r\n"), g_bWifiOnOff, g_bSysVolCtrl)); return 0; } //---------------------------------------------------------------------- // MainWndProc - Callback function for application window LRESULT CALLBACK MainWndProc(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { // Message dispatch table for MainWindowProc const struct decodeUINT MainMessages[] = { g_uMsgUfn, DoUfnMain, g_uMsgBatState, DoBatStateMain, WM_PAINT, DoPaintMain, WM_LBUTTONDOWN, DoLbuttonDown, WM_DESTROY, DoDestroy, WM_CREATE, DoCreate, }; // Search message list to see if we need to handle this message. If in list, call procedure. for (INT i=0; i<dim(MainMessages); i++) { if (wMsg == MainMessages[i].Code) return (*MainMessages[i].Fxn)(hWnd, wMsg, wParam, lParam); } return DefWindowProc(hWnd, wMsg, wParam, lParam); } LRESULT CALLBACK KeyHookProc(int nCode, WPARAM wParam, LPARAM lParam) { static BOOL static_bIsNumSkip = FALSE; if (g_bIsAttachUfn && (1 == g_nModeUfn)) // Mass_Storage_Class { RETAILMSG(0, (_T("KeyHookProc() : g_bIsAttachUfn = %d\r\n"), g_bIsAttachUfn)); return 1; } if (HC_ACTION == nCode && (WM_KEYDOWN == wParam || WM_KEYUP == wParam)) { PKBDLLHOOKSTRUCT key = (PKBDLLHOOKSTRUCT)lParam; BOOL bIsKeyUp = (WM_KEYUP == wParam) ? TRUE : FALSE; BOOL bIsVisible = IsWindowVisible(g_hWndMain); BOOL bIsRet = TRUE; if (VK_F21 == key->vkCode) // SYM { if (bIsKeyUp) { g_dwCLSelect = 0; ShowWindow(g_hWndMain, bIsVisible ? SW_HIDE : SW_SHOWNOACTIVATE); } } else if (VK_F22 == key->vkCode) // Test Program... { if (bIsKeyUp) { LPCTSTR lpszPathName = _T("\\Storage Card\\testOmnibook\\testOmnibook.exe"); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (CreateProcess(lpszPathName, NULL, 0, 0, 0, 0, 0, 0, 0, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } bIsRet = FALSE; } else if (g_bWifiOnOff && VK_BROWSER_REFRESH == key->vkCode) { if (bIsKeyUp) { HANDLE hEtc = CreateFile(ETC_DRIVER_NAME, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if (INVALID_HANDLE_VALUE != hEtc) { BOOL bIsWifi = DeviceIoControl(hEtc, IOCTL_GET_POWER_WLAN, NULL, 0, NULL, 0, NULL, NULL); RETAILMSG(0, (_T("IOCTL_GET_POWER_WLAN = %d\r\n"), bIsWifi)); bIsWifi = DeviceIoControl(hEtc, IOCTL_SET_POWER_WLAN, NULL, !bIsWifi, NULL, 0, NULL, NULL); RETAILMSG(0, (_T("IOCTL_SET_POWER_WLAN = %d\r\n"), bIsWifi)); CloseHandle(hEtc); } } } else if (g_bSysVolCtrl && (VK_BROWSER_BACK == key->vkCode || VK_BROWSER_FORWARD == key->vkCode)) // System Volume Down or Up { if (bIsKeyUp) { DWORD dwVolume; int nSoundLevel; waveOutGetVolume(NULL, &dwVolume); nSoundLevel = dwVolume / 0x11111111; RETAILMSG(0, (_T("waveOutGetVolume = %d, %X\r\n"), nSoundLevel, dwVolume)); if (VK_BROWSER_BACK == key->vkCode) nSoundLevel--; else //if (VK_BROWSER_FORWARD == key->vkCode) nSoundLevel++; if (15 < nSoundLevel) nSoundLevel = 15; else if (0 > nSoundLevel) nSoundLevel = 0; dwVolume = (0x11111111 * nSoundLevel); waveOutSetVolume(NULL, dwVolume); RETAILMSG(0, (_T("waveOutSetVolume = %d, %X\r\n"), nSoundLevel, dwVolume)); } } else if (bIsVisible) { if (VK_LEFT == key->vkCode) { if (bIsKeyUp && (CANDPAGESIZE-1) < g_dwCLSelect) { g_dwCLSelect -= CANDPAGESIZE; InvalidateRect(g_hWndMain, NULL, FALSE); } } else if (VK_RIGHT == key->vkCode) { if (bIsKeyUp && (CANDLISTCOUNT-CANDPAGESIZE) > g_dwCLSelect) { g_dwCLSelect += CANDPAGESIZE; InvalidateRect(g_hWndMain, NULL, FALSE); } } else if (_T('1') <= key->vkCode && _T('9') >= key->vkCode) { if (TRUE == static_bIsNumSkip) { if (bIsKeyUp) static_bIsNumSkip = FALSE; return g_fnCallNextHookEx(g_hKeyHook, nCode, wParam, lParam); } if (bIsKeyUp) { int nIdx = key->vkCode - _T('1') + g_dwCLSelect; if (_T('1') <= CandList[nIdx].chVKey && _T('9') >= CandList[nIdx].chVKey) static_bIsNumSkip = TRUE; if (CandList[nIdx].bShift) keybd_event(VK_SHIFT, 0, 0, 0); keybd_event((BYTE)CandList[nIdx].chVKey, 0, 0, 0); keybd_event((BYTE)CandList[nIdx].chVKey, 0, KEYEVENTF_KEYUP, 0); if (CandList[nIdx].bShift) keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0); //ShowWindow(g_hWndMain, SW_HIDE); RETAILMSG(0, (_T("CandList - szKey(%s), chVKey(0x%X), bShift(%d)\r\n"), CandList[nIdx].szKey, CandList[nIdx].chVKey, CandList[nIdx].bShift)); } } else if (VK_PROCESSKEY == key->vkCode) // ??? { bIsRet = FALSE; } else { if (bIsKeyUp) { ShowWindow(g_hWndMain, SW_HIDE); if (_T('U') == key->vkCode) { g_nModeUfn = ufnGetCurrentClientName(); if (0 == g_nModeUfn) // Serial_Class { g_nModeUfn = 1; // Mass_Storage_Class ufnChangeCurrentClient(g_nModeUfn); RETAILMSG(1, (_T("USB Mode Change : <<< Mass_Storage_Class >>>\r\n"))); } else if (1 == g_nModeUfn) // Mass_Storage_Class { g_nModeUfn = 0; // Serial_Class ufnChangeCurrentClient(g_nModeUfn); RETAILMSG(1, (_T("USB Mode Change : <<< Serial_Class >>>\r\n"))); } else { // ... } } } bIsRet = FALSE; } } else bIsRet = FALSE; RETAILMSG(0, (_T("KeyHookProc => message(0x%x), vkey(0x%x)\r\n"), wParam, key->vkCode)); if (bIsRet) return 1; } return g_fnCallNextHookEx(g_hKeyHook, nCode, wParam, lParam); }
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 607 ] ] ]
a7f05700b4dbc0d184db04ffa5141ccb622f76fe
064195ded8860567e6d9e5cfad00bdb13d2d701d
/Tree.h
9b6cea82c4a7d2effab034ee9c3b84264d3b1c8e
[]
no_license
ryanbahneman/botsbcc
6aa8324d386c91f71946cd14384f0f47bbf13135
9f9a9b3fb4ce94b6c5fbdcb23176adcf0b8fa926
refs/heads/master
2021-01-15T18:50:56.961002
2009-04-02T20:59:32
2009-04-02T20:59:32
32,125,981
0
0
null
null
null
null
UTF-8
C++
false
false
867
h
#ifndef TREE_H_INCLUDED #define TREE_H_INCLUDED #include "Node.h" class Tree { private: Node* Current; Node* Head; Node* Tail; public: //to create tree pass in tile of start position for first node Tree(Tile* startTile); Tree(Node node); Tree(); void add(Tile* tile); void remove(Tile* tile); void next(void); void prev(void); // void setNext(Node* next); // Node* getPrev(void); //void setPrev(Node* prev); Tile* getCurrentTile(void); Node getCurrentNode(void); void setCurrentNode(Node* cur); void add(Node node); void remove(Node node); }; #endif // TREE_H_INCLUDED
[ "[email protected]@545e0bd2-1449-11de-9d52-39b120432c5d" ]
[ [ [ 1, 42 ] ] ]
1ccf73f1071a4d30cd60a862fb696803f6040b32
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/packages/dScene/dNodeInfo.h
19d70b75c2237ae2e5eba78f0d761aab1ed151ff
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
5,378
h
///////////////////////////////////////////////////////////////////////////// // Name: dNodeInfo.h // Purpose: // Author: Julio Jerez // Modified by: // Created: 22/05/2010 08:02:08 // RCS-ID: // Copyright: Copyright (c) <2010> <Newton Game Dynamics> // License: // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely ///////////////////////////////////////////////////////////////////////////// #ifndef _D_NODEINFO_H_ #define _D_NODEINFO_H_ #include "dScene.h" #include "dVariable.h" #define NE_MAX_NAME_SIZE 64 class dNodeInfo; #define D_DEFINE_CLASS_NODE_ESSENCIALS(className,baseClass) \ dAddRtti(baseClass); \ virtual dNodeInfo* MakeCopy () const \ { \ return new className(*this); \ } \ virtual dNodeInfo* MetaFunction(dScene* const world) const \ { \ return new className(world); \ } \ static const char* BaseClassName () \ { \ return #baseClass; \ } \ static const className& GetSingleton() \ { \ return m_singletonClass; \ } \ static className m_singletonClass; #define D_DEFINE_CLASS_NODE(className,baseClass) \ virtual const char* GetClassName () const \ { \ return #className; \ } \ D_DEFINE_CLASS_NODE_ESSENCIALS(className,baseClass) #define D_IMPLEMENT_CLASS_NODE(className) \ dInitRtti(className); \ className className::m_singletonClass; \ static className::dRegisterSingleton m_registerSingletonAgent (#className, &className::m_singletonClass); #define SerialiseBase(baseClass,rootNode) \ TiXmlElement* baseClassNode = new TiXmlElement (#baseClass); \ rootNode->LinkEndChild(baseClassNode); \ baseClass::Serialize(baseClassNode); #define DeserialiseBase(baseClass,rootNode,revision) \ TiXmlElement* baseClassNode = (TiXmlElement*) rootNode->FirstChild (baseClass::GetClassName()); \ baseClass::Deserialize (baseClassNode, revision); class dNodeInfo: public dClassInfo, public dVariableList { public: enum dGizmoMode { m_selection, m_translation, m_rotation, m_scale }; enum dGizmoHandle { m_noHandle, m_xHandle, m_yHandle, m_zHandle, m_xyHandle, m_yzHandle, m_zxHandle, m_xyzHandle }; class dRegisterSingleton { public: dRegisterSingleton (const char* const className, const dNodeInfo* const singleton); }; dNodeInfo(); dNodeInfo(const dNodeInfo& me); virtual ~dNodeInfo(void); virtual dNodeInfo* MakeCopy () const; virtual const char* GetClassName () const; virtual const char* GetBaseClassName () const; virtual dNodeInfo* MetaFunction(dScene* const world) const; virtual const char* GetName () const; virtual void SetName (const char* name); virtual void SerializeBinary (FILE* const file) const; virtual void Serialize (TiXmlElement* const rootNode) const; virtual bool Deserialize (TiXmlElement* const rootNode, int revisionNumber); // draw scene in wire frame mode virtual void DrawWireFrame(dScene* const world, dScene::dTreeNode* const myNode, const dVector& color) const{}; // draw scene in solid wire frame mode virtual void DrawSolidWireFrame(dScene* const world, dScene::dTreeNode* const myNode, const dVector& color) const{}; // draw scene in Gouraud shaded virtual void DrawGouraudShaded(dScene* const world, dScene::dTreeNode* const myNode, const dVector& color) const{}; // draw scene in using shaders virtual void DrawShaded(dScene* const world, dScene::dTreeNode* const myNode, const dVector& color) const{}; // Draw selection gizmo virtual void DrawGizmo(dScene* const world, dScene::dTreeNode* const myNode, const dMatrix& coordinaSystem, const dVector& color, dGizmoMode mode, dFloat size) const{}; virtual dGizmoHandle GetHighlightedGizmoHandle(dScene* const world, dScene::dTreeNode* const myNode, const dMatrix& coordinaSystem, const dVector& screenPosition, dGizmoMode mode, dFloat size) const {return m_noHandle;} virtual void DrawGizmoHandle(dScene* world, const dMatrix& coordinaSystem, dGizmoMode mode, dGizmoHandle handle, const dVector& color, dFloat size) const {}; virtual void BakeTransform (const dMatrix& transform){}; virtual unsigned GetUniqueID() const {return m_uniqueID;} // virtual dVariableList& GetVariableList(); // virtual dVariable* CreateVariable (const char* name); // virtual dVariable* FindVariable(const char* name) const; static dNodeInfo* CreateFromClassName (const char* className, dScene* world); static dTree<const dNodeInfo*, dCRCTYPE>& GetSingletonDictionary(); static void ReplaceSingletonClass (const char* const className, const dNodeInfo* const singleton); dAddRtti(dClassInfo); private: char m_name[NE_MAX_NAME_SIZE]; // dVariableList m_variables; unsigned m_uniqueID; static unsigned m_uniqueIDCounter; }; #endif
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 168 ] ] ]
616f2accd7c6424a06ccf79f90725a26496e61c4
1ad310fc8abf44dbcb99add43f6c6b4c97a3767c
/samples_c++/cc/sprite_anime/App.cc
38349b73dbc2e97f10ca3d59a78e2db2ddd4a7e1
[]
no_license
Jazzinghen/spamOSEK
fed44979b86149809f0fe70355f2117e9cb954f3
7223a2fb78401e1d9fa96ecaa2323564c765c970
refs/heads/master
2020-06-01T03:55:48.113095
2010-05-19T14:37:30
2010-05-19T14:37:30
580,640
1
2
null
null
null
null
UTF-8
C++
false
false
1,717
cc
#include "App.h" //the sprite graphics frames extern const char shiki_intro_spr_start[]; extern const char shiki_walkforward_spr_start[]; extern const char shiki_taunt_spr_start[]; extern const char shiki_breathe_spr_start[]; //the set of all of the sprites const char* shikiDataSet[] = { shiki_intro_spr_start, shiki_walkforward_spr_start, shiki_taunt_spr_start, shiki_breathe_spr_start, }; //anim command come in pairs of 2 (frame number, time in 20msec) or (anim command, parameter) const char shikiAppearAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,254,0}; const char shikiWalkAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,253,1,0,3,1,3,2,3,3,3,4,3,5,3,255,0}; const char shikiTauntAnim[] = {0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,255,0}; const char shikiBreatheAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,6,3,7,3,8,3,255,0}; //the set of all animations for shiki since we'll be chaining them together const char* shikiAnimset[] = { shikiAppearAnim, shikiWalkAnim, shikiTauntAnim, shikiBreatheAnim }; App::App() : mCurrentAnim(0) , mShiki(shikiDataSet[0], shikiAnimset[0]) { mShiki.setScriptInterface(this); mShiki.setID(eSprite_Shiki); } void App::init() { mScreen.newSprite(&mShiki); } //run animation actions on the sprites as they call new commands void App::animCommand(Sprite *sprite, int command) { switch(sprite->getID()) { case eSprite_Shiki: runShikiAnim(sprite, command); break; } } void App::runShikiAnim(Sprite *sprite, int command) { if(++mCurrentAnim == 4) { mCurrentAnim = 0; } sprite->changeGfx(shikiDataSet[mCurrentAnim], shikiAnimset[mCurrentAnim]); } void App::update() { mScreen.update(); }
[ "jazzinghen@Jehuty.(none)" ]
[ [ [ 1, 71 ] ] ]
643a5472fb3247ca89e5b1e9ee608b738ac3f296
a04058c189ce651b85f363c51f6c718eeb254229
/Src/Forms/NetflixEnterLoginForm.cpp
785cc22a91fd262e86207f80ad73cd7e1d1d3aa4
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
3,297
cpp
#include <FormObject.hpp> #include "MoriartyApplication.hpp" #include "NetflixEnterLoginForm.hpp" #include "LookupManager.hpp" #include <Text.hpp> #include <SysUtils.hpp> #define assignedText _T("-ASSIGNED-") using ArsLexis::String; NetflixEnterLoginForm::NetflixEnterLoginForm(MoriartyApplication& app): MoriartyForm(app, netflixEnterLoginForm, true), loginField_(*this), passwordField_(*this) { setFocusControlId(loginField); } void NetflixEnterLoginForm::resize(const ArsRectangle& screenBounds) { ArsRectangle rect(2, screenBounds.height()-91, screenBounds.width()-4, 89); setBounds(rect); update(); } void NetflixEnterLoginForm::attachControls() { MoriartyForm::attachControls(); loginField_.attach(loginField); passwordField_.attach(passwordField); } bool NetflixEnterLoginForm::handleOpen() { bool result = MoriartyForm::handleOpen(); Preferences::NetflixPreferences* prefs = &application().preferences().netflixPreferences; if (!prefs->login.empty()) loginField_.setEditableText(prefs->login); if (!prefs->password.empty()) passwordField_.setEditableText(assignedText); return result; } void NetflixEnterLoginForm::handleControlSelect(const EventType& event) { if (okButton==event.data.ctlSelect.controlID) { const char* text = loginField_.text(); const char* pwd = passwordField_.text(); if (NULL != text && NULL != pwd) { if (StrEmpty(text) || StrEmpty(pwd)) { MoriartyApplication::alert(noLoginaOrPasswordAlert); return; } Preferences::NetflixPreferences* prefs = &application().preferences().netflixPreferences; prefs->forgetCredentials(); prefs->login.assign(text); if (prefs->password.empty() || tstrcmp(pwd, assignedText) != 0) prefs->password.assign(pwd); status_t err = prefs->sendLoginAndPasswordToServer(); if (errNone != err) MoriartyApplication::alert(notEnoughMemoryAlert); } } closePopup(); } bool NetflixEnterLoginForm::handleEvent(EventType& event) { bool handled=false; switch (event.eType) { case ctlSelectEvent: handleControlSelect(event); handled=true; break; case keyDownEvent: if (chrCarriageReturn==event.data.keyDown.chr || chrLineFeed==event.data.keyDown.chr) { Control control(*this, okButton); control.hit(); } break; case fldEnterEvent: //no break if (passwordField == event.data.fldEnter.fieldID) { const char_t* pwd = passwordField_.text(); if (NULL != pwd) { if (0 == tstrcmp(pwd, assignedText)) passwordField_.erase(); } } default: handled=MoriartyForm::handleEvent(event); } return handled; } NetflixEnterLoginForm::~NetflixEnterLoginForm() {}
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 107 ] ] ]
989a28bbd1ecc65d8633b0cb5e992dc5c668698d
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/impl/DOMElementImpl.hpp
8766cd80064336ffd396e75b8518f3fcf5db39d2
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,023
hpp
#ifndef DOMElementImpl_HEADER_GUARD_ #define DOMElementImpl_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * 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. */ /* * $Id: DOMElementImpl.hpp,v 1.9 2004/09/20 15:00:50 amassari Exp $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/dom/DOMElement.hpp> #include "DOMChildNode.hpp" #include "DOMNodeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMAttrMapImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN class DOMTypeInfo; class DOMNodeList; class DOMAttrMapImpl; class DOMDocument; class CDOM_EXPORT DOMElementImpl: public DOMElement { public: DOMNodeImpl fNode; DOMParentNode fParent; DOMChildNode fChild; DOMAttrMapImpl *fAttributes; DOMAttrMapImpl *fDefaultAttributes; const XMLCh *fName; public: DOMElementImpl(DOMDocument *ownerDoc, const XMLCh *name); DOMElementImpl(const DOMElementImpl &other, bool deep=false); virtual ~DOMElementImpl(); // Declare functions from DOMNode. They all must be implemented by this class DOMNODE_FUNCTIONS; // Functions introduced on Element... virtual const XMLCh* getAttribute(const XMLCh *name) const; virtual DOMAttr* getAttributeNode(const XMLCh *name) const; virtual DOMNodeList* getElementsByTagName(const XMLCh *tagname) const; virtual const XMLCh* getTagName() const; virtual void removeAttribute(const XMLCh *name); virtual DOMAttr* removeAttributeNode(DOMAttr * oldAttr); virtual void setAttribute(const XMLCh *name, const XMLCh *value); virtual DOMAttr* setAttributeNode(DOMAttr *newAttr); virtual void setReadOnly(bool readOnly, bool deep); //Introduced in DOM Level 2 virtual const XMLCh* getAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual void setAttributeNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName, const XMLCh *value); virtual void removeAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName); virtual DOMAttr* getAttributeNodeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMAttr* setAttributeNodeNS(DOMAttr *newAttr); virtual DOMNodeList* getElementsByTagNameNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual bool hasAttribute(const XMLCh *name) const; virtual bool hasAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; //Introduced in DOM level 3 virtual void setIdAttribute(const XMLCh* name); virtual void setIdAttributeNS(const XMLCh* namespaceURI, const XMLCh* localName); virtual void setIdAttributeNode(const DOMAttr *idAttr); virtual const DOMTypeInfo * getTypeInfo() const; // for handling of default attribute virtual DOMAttr* setDefaultAttributeNode(DOMAttr *newAttr); virtual DOMAttr* setDefaultAttributeNodeNS(DOMAttr *newAttr); virtual DOMAttrMapImpl* getDefaultAttributes() const; // helper function for DOM Level 3 renameNode virtual DOMNode* rename(const XMLCh* namespaceURI, const XMLCh* name); protected: // default attribute helper functions virtual void setupDefaultAttributes(); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMElementImpl & operator = (const DOMElementImpl &); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 127 ] ] ]
462539ac6d348a334fe908607ac9bde4b541b955
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/source/OEBase/OELogFileMgr_Impl.h
698aa07d8ab8c5166e83f0bb7ff04f3a69f398c8
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
834
h
/*! * \file OELogFileMgr_Impl.h * \date 26-7-2009 10:32:30 * * * \author zjhlogo ([email protected]) */ #ifndef __OELOGFILEMGR_IMPL_H__ #define __OELOGFILEMGR_IMPL_H__ #include <OEBase/IOELogFileMgr.h> #include <OEBase/IOEFile.h> class COELogFileMgr_Impl : public IOELogFileMgr { public: RTTI_DEF(COELogFileMgr_Impl, IOELogFileMgr); COELogFileMgr_Impl(); virtual ~COELogFileMgr_Impl(); virtual bool Initialize(); virtual void Terminate(); virtual void SetLogFile(const tstring& strFile); virtual void LogOut(const tstring& strLogMsg); virtual tstring& GetStringBuffer(); private: bool Init(); void Destroy(); bool CreateLogFile(const tstring& strFileName); private: tstring m_strFile; tstring m_strBuffer; IOEFile* m_pLogFile; }; #endif // __OELOGFILEMGR_IMPL_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 41 ] ] ]
f5c2f2ab93dcaacccfa801e4a056746596713ee2
718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1
/soft micros/Codigo/codigo portable/Aparatos/Propiedades/propiedadesAlarma.cpp
432afef5656e35498f45dec9df75c2f0365fd4b1
[]
no_license
jonyMarino/microsdhacel
affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca
66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3
refs/heads/master
2020-05-18T19:53:51.301695
2011-05-30T20:40:24
2011-05-30T20:40:24
34,532,512
0
0
null
null
null
null
UTF-8
C++
false
false
7,204
cpp
#include "propiedadesAlarma.hpp" #include "AlarmaControl.hpp" #include "ValorControl.hpp" #include "Retransmision.hpp" #include "CoordinadorLazosAlCntrRet.hpp" #include "configuracionValorControl.hpp" #include "configuracionAlarmas.hpp" #include "ConfiguracionAdapSalida.hpp" #pragma MESSAGE DISABLE C1825 /* Disable warning C5703 "Parameter is not referenced" */ #define ADAPTAR_FUNCION_GET(NOMBRE,METODO)\ int NOMBRE(void*conf){ \ return ((AlarmaControl&)((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl()).METODO(); \ } #define ADAPTAR_FUNCION_SET(NOMBRE,METODO) \ void NOMBRE(void*conf,int valor){ \ ((AlarmaControl&)((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl()).METODO(valor); \ } #define ADAPTAR_FUNCION_RET_GET(NOMBRE,METODO)\ int NOMBRE(void*conf){ \ return ((Retransmision&)((CoordinadorLazosAlCntrRet*)conf)->getRetransmision()).METODO(); \ } #define ADAPTAR_FUNCION_RET_SET(NOMBRE,METODO) \ void NOMBRE(void*conf,int valor){ \ ((Retransmision&)((CoordinadorLazosAlCntrRet*)conf)->getRetransmision()).METODO(valor); \ } #define ADAPTAR_FUNCION_LAZO_ALARMAS_GET(NOMBRE,METODO)\ int NOMBRE(void*conf){ \ return ((CoordinadorLazosAlCntrRet*)conf)->METODO(); \ } #define ADAPTAR_FUNCION_LAZO_ALARMAS_SET(NOMBRE,METODO) \ void NOMBRE(void*conf,int valor){ \ ((CoordinadorLazosAlCntrRet*)conf)->METODO(valor); \ } #define ADAPTAR_FUNCION_ADAP_SAL_GET(NOMBRE,METODO)\ int NOMBRE(void*conf){ \ return (*(AdaptadorSalida*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl())).getAdaptadorSalida()).METODO(); \ } #define ADAPTAR_FUNCION_VAL_CONTROL_GET(NOMBRE,METODO)\ int NOMBRE(void*conf){ \ return (*(ValorControl*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl())).getValorControl()).METODO(); \ } #define ADAPTAR_FUNCION_VAL_CONTROL_SET(NOMBRE,METODO) \ void NOMBRE(void*conf,int valor){ \ (*(ConfiguracionValorControlado*)&((*(ValorControl*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl()))).getConfiguracion())).METODO(valor); \ } void setValorControladorAl(void * alarma,int valor){ ValorControl * v= &(*(ValorControl*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)alarma)->getAlarmaControl())).getValorControl()); (*(ConfiguracionValorControlado*)&(v->getConfiguracion())).setValorControlador(valor); } uchar getDecimalesAlarma(void*alarma){ Sensor * s= &(*(ValorControl*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)alarma)->getAlarmaControl())).getValorControl()).getSensor(); return s->getDecimales(); } /*****************************/ /********PROPIEDADES**********/ /*****************************/ //Potencia static int getPotencia (void * alarma){ return ((CoordinadorLazosAlCntrRet*)alarma)-> getSalida().getPotencia(); } const struct ConstructorPropGetterNumerico cPropiedadGetPotencia={ &propGetterNumericoFactory,getPotencia,"PotA",1 }; //A const char * const modosAlarma[5]={ "ErEt", "drEt", "dbLK", "d", "E" }; const char * ms_getText_a(byte modo){ return modosAlarma[modo]; } ADAPTAR_FUNCION_GET(getAdaptadorSalidaAlam,getAdaptadorSalidaAlarm) ADAPTAR_FUNCION_SET(setAdaptadorSalidaAlam,setAdaptadorSalidaAlarm) const struct ConstructorPropiedadTextual cPropiedadModoAlarma={ &propiedadTextualFactory,getAdaptadorSalidaAlam,"A",setAdaptadorSalidaAlam,ms_getText_a,5 }; //AL const char * const tipoCtrlAlarma[3]={ "AbS", "rEL", "bAn", }; const char * ms_getText_b(byte modo){ return tipoCtrlAlarma[modo]; } ADAPTAR_FUNCION_GET(getTipoControl,getTipoControl) ADAPTAR_FUNCION_SET(setTipoControl,setTipoControl) const struct ConstructorPropiedadTextual cPropiedadTipoCtrlAlarma={ &propiedadTextualFactory,getTipoControl,"AL",setTipoControl,ms_getText_b,3 }; //Funcion de alarma const char * const funcAlarma[2]={ "ALm", "rEt", }; const char * ms_getText_f(byte modo){ return funcAlarma[modo]; } ADAPTAR_FUNCION_LAZO_ALARMAS_GET(getLazo,getLazo) ADAPTAR_FUNCION_LAZO_ALARMAS_SET(setLazo,setLazo) const struct ConstructorPropiedadTextual cPropiedadTipoLazo={ &propiedadTextualFactory,getLazo,"LA",setLazo,ms_getText_f,2 }; //retransmision //limite inferior ADAPTAR_FUNCION_RET_GET(getLimiteInferior,getLimiteInferior) ADAPTAR_FUNCION_RET_SET(setLimiteInferior,setLimiteInferior) const struct ConstructorPropNumLFPF cPropiedadRetLimInf={ &propNumLFPFFactory,getLimiteInferior,"AnL",setLimiteInferior,0,9999,0 }; //limite superior ADAPTAR_FUNCION_RET_GET(getLimiteSuperior,getLimiteSuperior) ADAPTAR_FUNCION_RET_SET(setLimiteSuperior,setLimiteSuperior) const struct ConstructorPropNumLFPF cPropiedadRetLimSup={ &propNumLFPFFactory,getLimiteSuperior,"AnH",setLimiteSuperior,0,9999,0 }; //Histeresis de Alarma ADAPTAR_FUNCION_ADAP_SAL_GET(getHisteresisAlarma,getHisteresis) void setHisteresisAlarma(void*conf,int valor){ const AdaptadorSalidaConfiguracion& config = (*(AdaptadorSalida*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl())).getAdaptadorSalida()).getConfiguracion(); ((ConfiguracionAdapSalida*)&config)->setHisteresis(valor); } const char * histeresisAlarmaVista(PropGetterVisual * prop){ int valObj=prop->getVal(); if(valObj<0) return "HA "; return "AbA"; } const struct ConstructorPropDescripcionVariablePV cPropiedadHistAlarma={ &propDescripcionVariablePVFactory,getHisteresisAlarma,"HA",setHisteresisAlarma,-9999,9999,getDecimalesAlarma,histeresisAlarmaVista }; //tipo salida const char * const tipoSalida[2]={ "onoff", "ProP", }; const char * ms_getText_c(byte modo){ return tipoSalida[modo]; } ADAPTAR_FUNCION_ADAP_SAL_GET(getTipoSalida,getTipoSalida) void setTipoSalida(void*conf,int valor){ const AdaptadorSalidaConfiguracion& config = (*(AdaptadorSalida*)&(*(LazoControl*)&(((CoordinadorLazosAlCntrRet*)conf)->getAlarmaControl())).getAdaptadorSalida()).getConfiguracion(); ((ConfiguracionAdapSalida*)&config)->setTipoSalida(valor); } const struct ConstructorPropiedadTextual cPropiedadTipoSalida={ &propiedadTextualFactory,getTipoSalida,"AL",setTipoSalida,ms_getText_c,2 }; //SetPoint de Alarma ADAPTAR_FUNCION_VAL_CONTROL_GET(getValorControlador,getValorControlador) //ADAPTAR_FUNCION_VAL_CONTROL_SET(setValorControlador,setValorControlador) const struct ConstructorPropNumLFPV cPropiedadSetPointAlarma={ &propNumLFPVFactory,getValorControlador,"A",setValorControladorAl,-9999,9999,getDecimalesAlarma };
[ "jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549" ]
[ [ [ 1, 208 ] ] ]
dd842364998f741a3b13fac4c1d240b0589da5f5
8f1601062c4a5452f2bdd0f75f3d12a79b98ba62
/examples/aegis/me519/paint/wpaint.cpp
84a74199fe49cc97f1869cd481eba245e92daba9
[]
no_license
chadaustin/isugamedev
200a54f55a2581cd2c62c94eb96b9e238abcf3dd
d3008ada042d2dd98c6e05711773badf6f1fd85c
refs/heads/master
2016-08-11T17:59:38.504631
2005-01-25T23:17:11
2005-01-25T23:17:11
36,483,500
1
0
null
null
null
null
UTF-8
C++
false
false
11,692
cpp
#include <algorithm> #include <functional> #include <list> #include <stdlib.h> #include <GL/glut.h> using namespace std; struct Point { Point(int x_ = 0, int y_ = 0) { x = x_; y = y_; } int x; int y; }; struct Color { float red, green, blue, alpha; }; static const Color white = { 1, 1, 1 }; static const Color black = { 0, 0, 0 }; static const Color red = { 1, 0, 0 }; static const Color green = { 0, 1, 0 }; static const Color blue = { 0, 0, 1 }; static const Color cyan = { 0, 1, 1 }; static const Color magenta = { 1, 0, 1 }; static const Color yellow = { 1, 1, 0 }; inline void glColor(const Color& c) { glColor4f(c.red, c.green, c.blue, c.alpha); } inline void glVertex(const Point& p) { glVertex2i(p.x, p.y); } struct Command { virtual ~Command() {} void destroy() { delete this; } virtual void draw() = 0; }; struct PointCommand : Command { PointCommand(Point p_, Color c_, int size_) { p = p_; c = c_; size = size_; } void draw() { glPointSize(size); glBegin(GL_POINTS); glColor(c); glVertex(p); glEnd(); } private: Point p; Color c; int size; }; struct LineCommand : Command { LineCommand(Point p1_, Point p2_, Color c_, int width_) { p1 = p1_; p2 = p2_; c = c_; width = width_; } void draw() { glLineWidth(width); glColor(c); glBegin(GL_LINES); glVertex(p1); glVertex(p2); glEnd(); } private: Point p1; Point p2; Color c; int width; }; struct RectangleCommand : Command { RectangleCommand(Point p1_, Point p2_, Color c_, int width_) { p1 = p1_; p2 = p2_; c = c_; width = width_; } void draw() { glLineWidth(width); glColor(c); glBegin(GL_LINE_STRIP); glVertex(p1); glVertex2i(p2.x, p1.y); glVertex(p2); glVertex2i(p1.x, p2.y); glVertex(p1); glEnd(); } private: Point p1; Point p2; Color c; int width; }; struct FilledRectangleCommand : Command { FilledRectangleCommand(Point p1_, Point p2_, Color c_) { p1 = p1_; p2 = p2_; c = c_; } void draw() { glColor(c); glBegin(GL_QUADS); glVertex(p1); glVertex2i(p2.x, p1.y); glVertex(p2); glVertex2i(p1.x, p2.y); glEnd(); } private: Point p1; Point p2; Color c; }; struct CommandList { void add(Command* c) { for_each(redos.begin(), redos.end(), mem_fun(&Command::destroy)); redos.clear(); commands.push_back(c); glutPostRedisplay(); } void undo() { if (commands.size()) { redos.push_back(commands.back()); commands.pop_back(); glutPostRedisplay(); } } void redo() { if (redos.size()) { commands.push_back(redos.back()); redos.pop_back(); glutPostRedisplay(); } } void clear() { for_each(commands.begin(), commands.end(), mem_fun(&Command::destroy)); commands.clear(); for_each(redos.begin(), redos.end(), mem_fun(&Command::destroy)); redos.clear(); glutPostRedisplay(); } void draw() { for_each(commands.begin(), commands.end(), mem_fun(&Command::draw)); } private: list<Command*> commands; list<Command*> redos; }; // since all tools use the same color... Color g_color = white; float g_alpha = 1; int g_line_width = 1; int g_point_size = 1; CommandList g_commands; Color CreateColor() { Color c = g_color; c.alpha = g_alpha; return c; } struct Tool { virtual void onMouseDown(Point p) { } virtual void onMouseMove(Point p) { } static void pushCommand(Command* c) { g_commands.add(c); } static void popCommand() { g_commands.undo(); } }; struct PointToolClass : Tool { void onMouseDown(Point p) { pushCommand(new PointCommand(p, CreateColor(), g_point_size)); } } PointTool; struct ScribbleToolClass : Tool { void onMouseDown(Point p) { m_last_point = p; } void onMouseMove(Point p) { pushCommand(new LineCommand(m_last_point, p, CreateColor(), g_line_width)); m_last_point = p; } private: Point m_last_point; } ScribbleTool; struct LineToolClass : Tool { void onMouseDown(Point p) { m_start = p; pushCommand(getCommand(p)); } void onMouseMove(Point p) { popCommand(); pushCommand(getCommand(p)); } private: Command* getCommand(Point p) { return new LineCommand(m_start, p, CreateColor(), g_line_width); } Point m_start; } LineTool; struct RectangleToolClass : Tool { RectangleToolClass() { m_filled = false; } void onMouseDown(Point p) { m_start = p; pushCommand(getCommand(p)); } void onMouseMove(Point p) { popCommand(); pushCommand(getCommand(p)); } void setFill(bool filled) { m_filled = filled; } private: Command* getCommand(Point p) { if (m_filled) { return new FilledRectangleCommand(m_start, p, CreateColor()); } else { return new RectangleCommand(m_start, p, CreateColor(), g_line_width); } } private: Point m_start; bool m_filled; } RectangleTool; int g_width; int g_height; Tool* g_tool = &PointTool; void display() { glViewport(0, 0, g_width, g_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, g_width, g_height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT); g_commands.draw(); glutSwapBuffers(); } void reshape(int x, int y) { g_width = x; g_height = y; glutPostRedisplay(); } void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { g_tool->onMouseDown(Point(x, y)); } } void motion(int x, int y) { g_tool->onMouseMove(Point(x, y)); } // menu commands enum { TOOL_POINT, TOOL_SCRIBBLE, TOOL_LINE, TOOL_RECTANGLE, COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_CYAN, COLOR_MAGENTA, COLOR_YELLOW, TRANSPARENCY_0, TRANSPARENCY_10, TRANSPARENCY_20, TRANSPARENCY_30, TRANSPARENCY_40, TRANSPARENCY_50, TRANSPARENCY_60, TRANSPARENCY_70, TRANSPARENCY_80, TRANSPARENCY_90, TRANSPARENCY_100, POINT_SIZE_1, POINT_SIZE_2, POINT_SIZE_4, POINT_SIZE_8, LINE_WIDTH_1, LINE_WIDTH_2, LINE_WIDTH_4, LINE_WIDTH_8, FILL_ON, FILL_OFF, COMMAND_REDO, COMMAND_UNDO, COMMAND_CLEAR, COMMAND_QUIT, }; void main_menu(int value) { switch (value) { case COMMAND_UNDO: g_commands.undo(); break; case COMMAND_REDO: g_commands.redo(); break; case COMMAND_CLEAR: g_commands.clear(); break; case COMMAND_QUIT: exit(EXIT_SUCCESS); } } void tool_menu(int value) { switch (value) { case TOOL_POINT: g_tool = &PointTool; break; case TOOL_SCRIBBLE: g_tool = &ScribbleTool; break; case TOOL_LINE: g_tool = &LineTool; break; case TOOL_RECTANGLE: g_tool = &RectangleTool; break; } } void color_menu(int value) { switch (value) { case COLOR_WHITE: g_color = white; break; case COLOR_BLACK: g_color = black; break; case COLOR_RED: g_color = red; break; case COLOR_GREEN: g_color = green; break; case COLOR_BLUE: g_color = blue; break; case COLOR_CYAN: g_color = cyan; break; case COLOR_MAGENTA: g_color = magenta; break; case COLOR_YELLOW: g_color = yellow; break; } } void transparency_menu(int value) { switch (value) { case TRANSPARENCY_0: g_alpha = 0.0f; break; case TRANSPARENCY_10: g_alpha = 0.1f; break; case TRANSPARENCY_20: g_alpha = 0.2f; break; case TRANSPARENCY_30: g_alpha = 0.3f; break; case TRANSPARENCY_40: g_alpha = 0.4f; break; case TRANSPARENCY_50: g_alpha = 0.5f; break; case TRANSPARENCY_60: g_alpha = 0.6f; break; case TRANSPARENCY_70: g_alpha = 0.7f; break; case TRANSPARENCY_80: g_alpha = 0.8f; break; case TRANSPARENCY_90: g_alpha = 0.9f; break; case TRANSPARENCY_100: g_alpha = 1.0f; break; } } void point_size_menu(int value) { switch (value) { case POINT_SIZE_1: g_point_size = 1; break; case POINT_SIZE_2: g_point_size = 2; break; case POINT_SIZE_4: g_point_size = 4; break; case POINT_SIZE_8: g_point_size = 8; break; } } void line_width_menu(int value) { switch (value) { case LINE_WIDTH_1: g_line_width = 1; break; case LINE_WIDTH_2: g_line_width = 2; break; case LINE_WIDTH_4: g_line_width = 4; break; case LINE_WIDTH_8: g_line_width = 8; break; } } void fill_menu(int value) { RectangleTool.setFill(value == FILL_ON); } void create_menu() { int tool = glutCreateMenu(tool_menu); glutAddMenuEntry("Point", TOOL_POINT); glutAddMenuEntry("Scribble", TOOL_SCRIBBLE); glutAddMenuEntry("Line", TOOL_LINE); glutAddMenuEntry("Rectangle", TOOL_RECTANGLE); int color = glutCreateMenu(color_menu); glutAddMenuEntry("White", COLOR_WHITE); glutAddMenuEntry("Black", COLOR_BLACK); glutAddMenuEntry("Red", COLOR_RED); glutAddMenuEntry("Green", COLOR_GREEN); glutAddMenuEntry("Blue", COLOR_BLUE); glutAddMenuEntry("Cyan", COLOR_CYAN); glutAddMenuEntry("Magenta", COLOR_MAGENTA); glutAddMenuEntry("Yellow", COLOR_YELLOW); int transparency = glutCreateMenu(transparency_menu); glutAddMenuEntry("0%", TRANSPARENCY_0); glutAddMenuEntry("10%", TRANSPARENCY_10); glutAddMenuEntry("20%", TRANSPARENCY_20); glutAddMenuEntry("30%", TRANSPARENCY_30); glutAddMenuEntry("40%", TRANSPARENCY_40); glutAddMenuEntry("50%", TRANSPARENCY_50); glutAddMenuEntry("60%", TRANSPARENCY_60); glutAddMenuEntry("70%", TRANSPARENCY_70); glutAddMenuEntry("80%", TRANSPARENCY_80); glutAddMenuEntry("90%", TRANSPARENCY_90); glutAddMenuEntry("100%", TRANSPARENCY_100); int point_size = glutCreateMenu(point_size_menu); glutAddMenuEntry("1", POINT_SIZE_1); glutAddMenuEntry("2", POINT_SIZE_2); glutAddMenuEntry("4", POINT_SIZE_4); glutAddMenuEntry("8", POINT_SIZE_8); int line_width = glutCreateMenu(line_width_menu); glutAddMenuEntry("1", LINE_WIDTH_1); glutAddMenuEntry("2", LINE_WIDTH_2); glutAddMenuEntry("4", LINE_WIDTH_4); glutAddMenuEntry("8", LINE_WIDTH_8); int fill = glutCreateMenu(fill_menu); glutAddMenuEntry("On", FILL_ON); glutAddMenuEntry("Off", FILL_OFF); glutCreateMenu(main_menu); glutAddMenuEntry("Undo", COMMAND_UNDO); glutAddMenuEntry("Redo", COMMAND_REDO); glutAddSubMenu("Tool", tool); glutAddSubMenu("Color", color); glutAddSubMenu("Transparency", transparency); glutAddSubMenu("Point Size", point_size); glutAddSubMenu("Line Width", line_width); glutAddSubMenu("Fill", fill); glutAddMenuEntry("Clear", COMMAND_CLEAR); glutAddMenuEntry("Quit", COMMAND_QUIT); glutAttachMenu(GLUT_RIGHT_BUTTON); } void initialize() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_POINT_SMOOTH); } int main(int argc, char** argv) { // initialize GLUT glutInit(&argc, argv); glutInitWindowSize(640, 480); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); // create primary window glutCreateWindow("Paint"); // callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); create_menu(); initialize(); glutMainLoop(); }
[ "aegis@84b32ba4-53c3-423c-be69-77cca6335494" ]
[ [ [ 1, 526 ] ] ]
31568d0f836d137f63967072d2469027147ae9b3
ff5313a6e6c9f9353f7505a37a57255c367ff6af
/wtl_hello/stdafx.h
e18df8bf55c9af71f7658ce5cb6d1d00bf5297aa
[]
no_license
badcodes/vc6
467d6d513549ac4d435e947927d619abf93ee399
0c11d7a81197793e1106c8dd3e7ec6b097a68248
refs/heads/master
2016-08-07T19:14:15.611418
2011-07-09T18:05:18
2011-07-09T18:05:18
1,220,419
1
0
null
null
null
null
UTF-8
C++
false
false
1,454
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #if !defined(AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_) #define AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_ // Change these values to use different versions #define WINVER 0x0400 //#define _WIN32_WINNT 0x0400 #define _WIN32_IE 0x0400 #define _RICHEDIT_VER 0x0100 #include <atlbase.h> #include <atlapp.h> extern CAppModule _Module; /* #define _WTL_SUPPORT_SDK_ATL3 // Support for VS2005 Express & SDK ATL #ifdef _WTL_SUPPORT_SDK_ATL3 #define _CRT_SECURE_NO_DEPRECATE #pragma conform(forScope, off) #pragma comment(linker, "/NODEFAULTLIB:atlthunk.lib") #endif // _WTL_SUPPORT_SDK_ATL3 #include <atlbase.h> // Support for VS2005 Express & SDK ATL #ifdef _WTL_SUPPORT_SDK_ATL3 namespace ATL { inline void * __stdcall __AllocStdCallThunk() { return ::HeapAlloc(::GetProcessHeap(), 0, sizeof(_stdcallthunk)); } inline void __stdcall __FreeStdCallThunk(void *p) { ::HeapFree(::GetProcessHeap(), 0, p); } }; #endif // _WTL_SUPPORT_SDK_ATL3 */ #include <atlwin.h> //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_)
[ [ [ 1, 54 ] ] ]
25ca0444727e6dae8898251229c6edf51a494ce6
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Loader/XMLGameObject.cpp
a43531ec2ce1c3329fcaee6b6a0065300f308f02
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
761
cpp
#include "OUAN_Precompiled.h" #include "XMLGameObject.h" using namespace OUAN; XMLGameObject::XMLGameObject() { XMLNodeDreams=0; XMLNodeNightmares=0; XMLNodeCustomProperties=0; } XMLGameObject::~XMLGameObject() { } TiXmlElement * XMLGameObject::getMainXMLNode() { //Object exists both in dreams and nightmares if(XMLNodeDreams && XMLNodeNightmares) { //If it exists in both worlds we use Dreams parameters for render components return XMLNodeDreams; } //Object exists only in dreams else if(XMLNodeDreams && !XMLNodeNightmares) { return XMLNodeDreams; } //Object exists only in nightmares else if(!XMLNodeDreams && XMLNodeNightmares) { return XMLNodeNightmares; } else { return NULL; } }
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 2 ] ], [ [ 3, 15 ], [ 17, 41 ] ], [ [ 16, 16 ] ] ]
6fdfdb21b43778cad92a8a1a847660dd7276edba
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/cwf/renders.cpp
b66af41f1ed492287030c6e9ecd5f0cfdfc96dfc
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include <google/template_dictionary.h> #include "cwf/render.hpp" // google::TemplateDictionary * dict); namespace cwf { RenderResult NullRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *response, ResponsePipe *) { response->set_success(); return RR_SUCCEEDED; } RenderResult ServerErrorRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *response, ResponsePipe *) { response->set_error(http::HC_SERVICE_UNAVAILABLE); return RR_SUCCEEDED; } RenderResult StaticRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *request, http::HttpResponse *response, ResponsePipe *) { // load file, doc_root? // gzip std::string accepted = request->hasHeader(http::HH_ACCEPT_ENCODING); return RR_SUCCEEDED; } }
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 27 ] ] ]
fb1876875ac41eba166aa6452445a13e7121008f
0c6762dfc935c47fb27ca431bf8137372eb54ca9
/mywindow.h
f9d4da99f36681b92e66a8231805b0ec01a27807
[]
no_license
Baku/kereorgreurseuseu
1c98e27b9e1184ff925cd1026329255042f92f40
ebd7dbe577dcdcf97757ee3d15f29e754b58445c
refs/heads/master
2021-01-13T01:40:17.727968
2010-12-18T10:20:14
2010-12-18T10:20:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
649
h
#ifndef MYWINDOW_H #define MYWINDOW_H #include <QtGui> class MyWindow : public QWidget { Q_OBJECT public: /* MyWindow(); ~MyWindow();*/ void run(); QPushButton *add; QPushButton *del; QPushButton *edit; QStringList feedlist; QStringListModel *feedlistmodel; QListView *feedview; QStringList *itemlist; QStringListModel *itemlistmodel; QListView *itemview; private: QStringList flux; public slots: void addRss(); void delRss(); void editRss(); }; #endif // MYWINDOW_H
[ "pfad_a@pc-NETWORKING=yes.(none)" ]
[ [ [ 1, 35 ] ] ]
0d5a0cb4a41591b892956a83d0410d13f39c17d9
f95341dd85222aa39eaa225262234353f38f6f97
/DesktopX/Plugins/DXTaskbar7/DXTaskbar7/stdafx.cpp
d668b5671439dc0300e7050c8a9b79cd12c9acfe
[]
no_license
Templier/threeoaks
367b1a0a45596b8fe3607be747b0d0e475fa1df2
5091c0f54bd0a1b160ddca65a5e88286981c8794
refs/heads/master
2020-06-03T11:08:23.458450
2011-10-31T04:33:20
2011-10-31T04:33:20
32,111,618
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
// stdafx.cpp : source file that includes just the standard includes // DXTaskbar7.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 5 ] ] ]
d2dbc4eff802e6133b9134acea2263f9d13b7d11
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第四章 数组和指针/20090321_习题4.33_把int型vector对象复制给int型数组.cpp
34d2f7c15f3d670793fbd37093933f52a6fc303f
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
//20090321 Care of DELETE #include <iostream> #include <vector> using namespace std; int main() { int ival; vector<int> ivec; cout << "Enter some integers(Ctrl+Z to end):" << endl; while (cin >> ival) { ivec.push_back(ival); } cin.clear(); int *parr = new int[ivec.size()]; size_t ix; vector<int>::iterator iter = ivec.begin(); for (ix = 0; ix != ivec.size(); ++ix) { parr[ix] = *iter++; cout << parr[ix] << " "; if ((ix + 1) % 10 == 0) cout << endl; } cout << endl; delete [] parr; //IMPORTANT return 0; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 32 ] ] ]
fdb80b0ba63efa6ef34f0e160a899dbbb67b1370
69aab86a56c78cdfb51ab19b8f6a71274fb69fba
/Code/inc/HUD/GameLabel.h
c02b1a30360757d07577132c67accdb068352cba
[ "BSD-3-Clause" ]
permissive
zc5872061/wonderland
89882b6062b4a2d467553fc9d6da790f4df59a18
b6e0153eaa65a53abdee2b97e1289a3252b966f1
refs/heads/master
2021-01-25T10:44:13.871783
2011-08-11T20:12:36
2011-08-11T20:12:36
38,088,714
0
0
null
null
null
null
UTF-8
C++
false
false
1,847
h
/* * GameLabel.h * * Created on: 2011-01-10 * Author: artur.m */ #ifndef GAMELABEL_H_ #define GAMELABEL_H_ #include "GameControl.h" #include "GamePanel.h" #include "MathHelper.h" #include "GameBitmap.h" #include "GameCommon.h" #include <string> #include <vector> #include <memory> class GamePanel; class GameLabel : public GameControl { public: virtual std::string getType() const { return "GameLabel"; } static shared_ptr<GameLabel> spawn(const Rectangle& rect); virtual ~GameLabel(); void setText(const std::string& text); const std::string& getText() const; void setTextVerticalAlignment(Common::VerticalAlignment align); Common::VerticalAlignment getTextVerticalAlignment() const { return m_vAlign; } void setTextHorizontalAlignment(Common::HorizontalAlignment align); Common::HorizontalAlignment getTextHorizontalAlignment() const { return m_hAlign; } void setTextAlignment(Common::HorizontalAlignment hAlign, Common::VerticalAlignment vAlign); void setTextColor(unsigned char r, unsigned char g, unsigned char b); Common::Color getTextColor() const { return m_color; } int getTextSize() const { return m_fontSize; } void setFontSize(int size); private: GameLabel(const Rectangle& bounds); void initialize(); void cleanOldText(); // Creates the bitmap which holds the rendered by FreeType text void createBitmap(); // Updates the color of the text in the rendered bitmap void updateColor(); private: static int s_instances; std::string m_text; std::string m_bitmapId; Common::HorizontalAlignment m_hAlign; Common::VerticalAlignment m_vAlign; Common::Color m_color; int m_fontSize; }; #endif /* GAMELABEL_H_ */
[ [ [ 1, 71 ] ] ]
ff2a51e7654fda9efa2d73057908c0789cb54ad4
9c99641d20454681792481c25cd93503449b174d
/WEBGL_lesson7/src/testApp.h
05ec2e26c864f3e8f6cf45cee925c5fefb43d660
[]
no_license
fazeaction/OF_LearningWebGL_Examples
a8befc8c65dd2f9ffc0c45a3c54548f5a05295aa
b608e252b58129bab844c32cc6a7929f3643e145
refs/heads/master
2021-03-12T23:58:57.355788
2010-05-17T22:35:15
2010-05-17T22:35:15
665,483
4
1
null
null
null
null
UTF-8
C++
false
false
1,529
h
#ifndef _TEST_APP #define _TEST_APP #include "ofMain.h" #include "ofxShader.h" #include "ofxVectorMath.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void setupScreenForLesson(); void setMatrixUniforms(); void checkForKeys(); void setAmbientLightColor(); void setDirectLightColor(); void setPositionLight(); GLuint vboId[2]; GLint locationID[6]; GLfloat pMatrix[16]; GLfloat mvMatrix[16]; float xRot; float xSpeed; float yRot; float ySpeed; float xRotLight; float yRotLight; float z; //AMBIENT COLOR VALUES float ambient_red_value; float ambient_green_value; float ambient_blue_value; //DIRECT LIGHT COLOR VALUES float direct_red_value; float direct_green_value; float direct_blue_value; //POSITION LIGTH float xpos; float ypos; float zpos; bool of_key_backspace_pressed; bool of_key_page_up_pressed; bool of_key_page_down_pressed; bool of_key_left_pressed; bool of_key_right_pressed; bool of_key_up_pressed; bool of_key_down_pressed; bool use_lighting; ofImage neheTexture; ofTrueTypeFont verdana; ofxShader shader; ofxVec3f lightDirection; }; #endif
[ [ [ 1, 85 ] ] ]
da615f41049a5a84931e1703b1b602c5156ded62
8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076
/code/Materials/fxLayer.cpp
8bf0783777201b76a2ea4b918f8295aaf50cc6fe
[]
no_license
BackupTheBerlios/insane
fb4c5c6a933164630352295692bcb3e5163fc4bc
7dc07a4eb873d39917da61e0a21e6c4c843b2105
refs/heads/master
2016-09-05T11:28:43.517158
2001-01-31T20:46:38
2001-01-31T20:46:38
40,043,333
0
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
//--------------------------------------------------------------------------- #include "fxLayer.h" #include "fxTextureMng.h" //--------------------------------------------------------------------------- fxLayer::~fxLayer(void) { fxTextureMng * tm; for (int i=0; i<nummaps; i++) { tm = (fxTextureMng*)maps[i]->TextureMng; tm->DeleteTexture(maps[i]); } }
[ "josef" ]
[ [ [ 1, 14 ] ] ]
14f0b95d0b3437401c55784d1b862b5c3b2fd49b
221e3e713891c951e674605eddd656f3a4ce34df
/core/OUE/Broadcast.h
a7c15c413cc4a2a9edde643193c6a850c786f342
[ "MIT" ]
permissive
zacx-z/oneu-engine
da083f817e625c9e84691df38349eab41d356b76
d47a5522c55089a1e6d7109cebf1c9dbb6860b7d
refs/heads/master
2021-05-28T12:39:03.782147
2011-10-18T12:33:45
2011-10-18T12:33:45
null
0
0
null
null
null
null
GB18030
C++
false
false
2,004
h
/* This source file is part of OneU Engine. Copyright (c) 2011 Ladace 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 Broadcast.h * @brief 广播类 * @author Ladace * @version 1.0.0.1 * @date 2011-04-09 */ #pragma once #include "Event.h" namespace OneU { /** * @addtogroup group_game */ //@{ /* ----------------------------------------------------------------------------*/ /** * @brief 广播接口 * * Game基本组成之一。负责处理全局事件和发送信息(日志)。 */ /* ----------------------------------------------------------------------------*/ class IBroadcast : public IEventDispatcher { public: }; /* ----------------------------------------------------------------------------*/ /** * @brief 广播对象工厂 * * @returns 广播对象接口 */ /* ----------------------------------------------------------------------------*/ ONEU_API IBroadcast* BroadCast_create(); //@} }
[ "[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c" ]
[ [ [ 1, 61 ] ] ]
ea4d91c72080e96d50d49f2ad74155727e39004b
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/rules/src/JournalEntry.cpp
ab42257db92b763f093a758c553d4c3d10154445
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,679
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "JournalEntry.h" #include "QuestBook.h" namespace rl { const Ogre::String JournalEntry::PROPERTY_TEXT = "text"; const Ogre::String JournalEntry::PROPERTY_CAPTION = "caption"; JournalEntry::JournalEntry(const CeGuiString &id, const CeGuiString &caption, const CeGuiString &text) : mCaption(caption), mText(text), SaveAble(id) { } JournalEntry::~JournalEntry() { } CeGuiString JournalEntry::getCaption() const { return mCaption; } CeGuiString JournalEntry::getText() const { return mText; } JournalEvent::JournalEvent(QuestBook* src, int reason, JournalEntry* entry) : EventObject(src, reason), mJournalEntry(entry) { } JournalEvent::~JournalEvent() { } JournalEntry* JournalEvent::getJournalEntry() const { return mJournalEntry; } }
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 58 ] ] ]
0f20f210e31119336d6df243fdb18e651ade9c75
bfe8eca44c0fca696a0031a98037f19a9938dd26
/libjingle-0.4.0/talk/base/time.h
2ada9e3723500247e97ded302bfb1d6618631560
[ "BSD-3-Clause" ]
permissive
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
2,127
h
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TALK_BASE_TIME_H__ #define TALK_BASE_TIME_H__ #include "talk/base/basictypes.h" namespace talk_base { // Returns the current time in milliseconds. uint32 Time(); // Approximate time when the program started. uint32 StartTime(); // Elapsed milliseconds since StartTime() uint32 ElapsedTime(); // TODO: Delete this old version. #define GetMillisecondCount Time // Comparisons between time values, which can wrap around. bool TimeIsBetween(uint32 later, uint32 middle, uint32 earlier); int32 TimeDiff(uint32 later, uint32 earlier); } // namespace talk_base #endif // TALK_BASE_TIME_H__
[ "[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 53 ] ] ]
0e3ad750aab1e21a3176a5fb085abed2b13d70da
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Utilities/include/SparseGraph.h
08a1cf21227794910087e5ad2bc1584980039c58
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
10,076
h
#pragma once #ifndef __SPARSE_GRAPH_H__ #define __SPARSE_GRAPH_H__ #ifndef __GRAPH_DEFINES_H__ #error S'ha d'incloure "GraphDefines.h" i no "SparseGraph.h" #endif #include "base.h" #include <list> class CRenderManager; class CSparseGraph { public: //a couple more typedefs to save my fingers and to help with the formatting //of the code on the printed page typedef std::vector<CGraphNode> NodeVector; typedef std::list<CGraphEdge> EdgeList; typedef std::vector<EdgeList> EdgeListVector; private: //the nodes that comprise this graph NodeVector m_Nodes; //a vector of adjacency edge lists. (each node index keys into the //list of edges associated with that node) EdgeListVector m_Edges; //is this a directed graph? bool m_bDigraph; //the index of the next node to be added int m_iNextNodeIndex; //returns true if an edge is not already present in the graph. Used //when adding edges to make sure no duplicates are created. bool UniqueEdge(int from, int to)const; //iterates through all the edges in the graph and removes any that point //to an invalidated node void CullInvalidEdges(); public: //ctor CSparseGraph(bool digraph): m_iNextNodeIndex(0), m_bDigraph(digraph){} void DebugRender(CRenderManager* _pRM) const; //returns the node at the given index const CGraphNode& GetNode(int idx)const; //non const version CGraphNode& GetNode(int idx); int GetClosestNode(const Vect3f& _vPosition); int GetClosestNode(const Vect3f& _vPosition, int _iMaxDistance); //const method for obtaining a reference to an edge const CGraphEdge& GetEdge(int from, int to)const; //non const version CGraphEdge& GetEdge(int from, int to); //retrieves the next free node index int GetNextFreeNodeIndex()const{return m_iNextNodeIndex;} //adds a node to the graph and returns its index int AddNode(const CGraphNode& node); //removes a node by setting its index to invalid_node_index void RemoveNode(int node); //Use this to add an edge to the graph. The method will ensure that the //edge passed as a parameter is valid before adding it to the graph. If the //graph is a digraph then a similar edge connecting the nodes in the opposite //direction will be automatically added. void AddEdge(const CGraphEdge& edge); //removes the edge connecting from and to from the graph (if present). If //a digraph then the edge connecting the nodes in the opposite direction //will also be removed. void RemoveEdge(int from, int to); //sets the cost of an edge void SetEdgeCost(int from, int to, float cost); //returns the number of active + inactive nodes present in the graph int NumNodes()const{return m_Nodes.size();} //returns the number of active nodes present in the graph (this method's //performance can be improved greatly by caching the value) int NumActiveNodes()const { int count = 0; for (unsigned int n=0; n<m_Nodes.size(); ++n) if (m_Nodes[n].GetIndex() != INVALID_GRAPH_NODE_INDEX) ++count; return count; } //returns the total number of edges present in the graph int NumEdges()const { int tot = 0; for (EdgeListVector::const_iterator curEdge = m_Edges.begin(); curEdge != m_Edges.end(); ++curEdge) { tot += curEdge->size(); } return tot; } //returns true if the graph is directed bool isDigraph()const{return m_bDigraph;} //returns true if the graph contains no nodes bool isEmpty()const{return m_Nodes.empty();} //returns true if a node with the given index is present in the graph bool isNodePresent(int nd)const; //returns true if an edge connecting the nodes 'to' and 'from' //is present in the graph bool isEdgePresent(int from, int to)const; //methods for loading and saving graphs from an open file stream or from //a file name //bool Save(const char* FileName)const; //bool Save(std::ofstream& stream)const; //bool Load(const char* FileName); //bool Load(std::ifstream& stream); //clears the graph ready for new node insertions void Clear(){m_iNextNodeIndex = 0; m_Nodes.clear(); m_Edges.clear();} void RemoveEdges() { for (EdgeListVector::iterator it = m_Edges.begin(); it != m_Edges.end(); ++it) { it->clear(); } } //non const class used to iterate through all the edges connected to a specific node. class EdgeIterator { private: EdgeList::iterator curEdge; CSparseGraph& G; const int NodeIndex; public: EdgeIterator(CSparseGraph& graph, int node): G(graph), NodeIndex(node) { /* we don't need to check for an invalid node index since if the node is invalid there will be no associated edges */ curEdge = G.m_Edges[NodeIndex].begin(); } CGraphEdge* begin() { curEdge = G.m_Edges[NodeIndex].begin(); if(end()) return 0; return &(*curEdge); } CGraphEdge* next() { ++curEdge; if(end()) return 0; return &(*curEdge); } //return true if we are at the end of the edge list bool end() { return (curEdge == G.m_Edges[NodeIndex].end()); } }; friend class EdgeIterator; //const class used to iterate through all the edges connected to a specific node. class ConstEdgeIterator { private: EdgeList::const_iterator curEdge; const CSparseGraph& G; const int NodeIndex; public: ConstEdgeIterator(const CSparseGraph& graph, int node): G(graph), NodeIndex(node) { /* we don't need to check for an invalid node index since if the node is invalid there will be no associated edges */ curEdge = G.m_Edges[NodeIndex].begin(); } const CGraphEdge* begin() { curEdge = G.m_Edges[NodeIndex].begin(); if(end()) return 0; return &(*curEdge); } const CGraphEdge* next() { ++curEdge; if(end()) return 0; return &(*curEdge); } //return true if we are at the end of the edge list bool end() { return (curEdge == G.m_Edges[NodeIndex].end()); } }; friend class ConstEdgeIterator; //non const class used to iterate through the nodes in the graph class NodeIterator { private: NodeVector::iterator curNode; CSparseGraph& G; //if a graph node is removed, it is not removed from the //vector of nodes (because that would mean changing all the indices of //all the nodes that have a higher index). This method takes a node //iterator as a parameter and assigns the next valid element to it. void GetNextValidNode(NodeVector::iterator& it) { if ( curNode == G.m_Nodes.end() || it->GetIndex() != INVALID_GRAPH_NODE_INDEX) return; while ( (it->GetIndex() == INVALID_GRAPH_NODE_INDEX) ) { ++it; if (curNode == G.m_Nodes.end()) break; } } public: NodeIterator(CSparseGraph &graph):G(graph) { curNode = G.m_Nodes.begin(); } CGraphNode* begin() { curNode = G.m_Nodes.begin(); GetNextValidNode(curNode); if(end()) return 0; return &(*curNode); } CGraphNode* next() { ++curNode; GetNextValidNode(curNode); if(end()) return 0; return &(*curNode); } bool end() { return (curNode == G.m_Nodes.end()); } }; friend class NodeIterator; //const class used to iterate through the nodes in the graph class ConstNodeIterator { private: NodeVector::const_iterator curNode; const CSparseGraph& G; //if a graph node is removed or switched off, it is not removed from the //vector of nodes (because that would mean changing all the indices of //all the nodes that have a higher index. This method takes a node //iterator as a parameter and assigns the next valid element to it. void GetNextValidNode(NodeVector::const_iterator& it) { if ( curNode == G.m_Nodes.end() || it->GetIndex() != INVALID_GRAPH_NODE_INDEX) return; while ( (it->GetIndex() == INVALID_GRAPH_NODE_INDEX) ) { ++it; if (curNode == G.m_Nodes.end()) break; } } public: ConstNodeIterator(const CSparseGraph &graph):G(graph) { curNode = G.m_Nodes.begin(); } const CGraphNode* begin() { curNode = G.m_Nodes.begin(); GetNextValidNode(curNode); if(end()) return 0; return &(*curNode); } const CGraphNode* next() { ++curNode; GetNextValidNode(curNode); if(end()) return 0; return &(*curNode); } bool end() { return (curNode == G.m_Nodes.end()); } }; friend class ConstNodeIterator; }; #endif
[ "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "mudarra@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 64 ], [ 67, 77 ], [ 79, 86 ], [ 88, 379 ] ], [ [ 65, 66 ] ], [ [ 78, 78 ], [ 87, 87 ] ] ]
12a4678e3c257105de9c6ff49fde4842068f6147
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/interface-ethernet.h
fb10d5d021921f5a2bbeb3bf55b023155129777e
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
9,325
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - InterfaceEthernet class // Mohamed Abd Elhafez. Georgia Tech, Spring 2004 // Define class to model network link interfaces // Implements the Layer 2 protocols #ifndef __interface_ethernet_h__ #define __interface_ethernet_h__ #include "G_common_defs.h" #include "simulator.h" #include "protocol.h" #include "packet.h" #include "handler.h" #include "ipaddr.h" #include "notifier.h" #include "macaddr.h" #include "node.h" #include "link.h" #include "link-real.h" #include "eventcq.h" #include "interface.h" #include "interface-real.h" #include "ethernet.h" #define INITIAL_BACKOFF 1 // Initial value for the max contention window #define SLOT_TIME 512 // Slot time in bit times #define BACKOFF_LIMIT 1024 // maximum allowable contention window #define ATTEMPT_LIMIT 16 // number of retransmit before giving up #define JAM_TIME 32 // Jam time in bit times #define INTER_FRAME_GAP 96 // Slot time in bit times // Define the event subclass for link events //Doc:ClassXRef class EthernetEvent : public LinkEvent { public: typedef enum { PACKET_RX, // Packet receive event PACKET_TX, // Packet transmit completed succesfuly NOTIFY, // Notify clients of available buffer space FBR, // First Bit Received CLR, // Packet transmit aborted, link free RETRANSMIT, // Start packet transmit UPDATE_NODES, // Updae Node List CHAN_ACQ // Channel acquired event } EthernetEvent_t; public: EthernetEvent() : mac(MACAddr::NONE), type(0), size(0) { } EthernetEvent(Event_t ev) : LinkEvent(ev), mac(MACAddr::NONE), type(0), size(0) { } EthernetEvent(Event_t ev, Packet* pkt) : LinkEvent(ev, pkt), mac(MACAddr::NONE), type(0), size(pkt->Size()) { } EthernetEvent(Event_t ev, Size_t s) : LinkEvent(ev), mac(MACAddr::NONE), type(0), size(s) { } EthernetEvent(Event_t ev, const MACAddr& dst, Size_t s) : LinkEvent(ev), mac(dst), type(0), size(s) { } EthernetEvent(Event_t ev, Packet* pkt, const MACAddr& dst, int t) : LinkEvent(ev, pkt), mac(dst), type(t) { } virtual ~EthernetEvent() { } public: MACAddr mac; // Receiver Mac address int type; // Type for sending the packet Size_t size; // The size of the packet Interface* sender; // The sender interface, used to notify the sender that it has acquired the chanell succesfuly }; //Doc:ClassXRef class NodeIfTime { public: NodeIfTime(Node* n, Interface* i, Time_t t) : node(n), iface(i), time(t) { } public: Node* node; Interface* iface; Time_t time; }; typedef std::vector<NodeIfTime> NodeTimeVec_t; // Neighbors,Iface w/time typedef std::vector<LinkEvent*> LinkEventVec_t; //Doc:ClassXRef class InterfaceEthernet : public InterfaceReal { //Doc:Class InterfaceEthernet is an interface that handles the collision //Doc:Class detection algorithm in the 802.3 standrad public: //Doc:Method InterfaceEthernet(const L2Proto& l2 = L2Proto802_3(), IPAddr_t i = IPADDR_NONE, Mask_t m = MASK_ALL, MACAddr mac = MACAddr::NONE, bool bootstrap = false); //Doc:Desc Constructs a new ethernet interface object. //Doc:Arg1 The layer 2 protocol type to associate with this interface. //Doc:Arg2 The \IPA\ to assign to this interface. //Doc:Arg3 The address mask to assign to this interface. //Doc:Arg4 The {\tt MAC} address to assign to this interface. virtual ~InterfaceEthernet(); virtual bool IsEthernet() const { return true;} // True if ethernet interface // Handler virtual void Handle(Event*, Time_t); //Doc:Method bool Send(Packet*, const MACAddr&, int); // Enque and transmit //Doc:Desc Send a packet on this interface. //Doc:Arg1 Packet to send. //Doc:Arg2 MAC address of destination //Doc:Arg3 LLC/SNAP type //Doc:Return True if packet sent or enqued, false if dropped. //Doc:Method virtual void RegisterRxEvent(LinkEvent*); // Register the last rx event issued by this interface //Doc:Desc Keep a reference of the last Rx event made by a packet from this interfcae. //Doc:Arg1 Last PACKET_RX event //Doc:Method virtual void AddRxEvent(LinkEvent*); // add to the list of rx events , used in case of broadcast //Doc:Desc Add to the list of rx events, This method is used in case the last packet was broadcast. //Doc:Arg1 Last PACKET_RX event virtual void Notify(void* v); //Doc:Method //virtual void LasPktIsBcast(bool); // true of last packet is broad cast //Doc:Desc Set the bCast flag indicating wether the last packet was broadcast or not //Doc:Method bool Retransmit(Packet* p); //Doc:Desc Tries to retransmit the packet on the link //Doc:Arg1 The packet to be retransmitted //Doc:Method bool SenseChannel(); //Doc:Desc Tries to retransmit the packet on the link //Doc:Arg1 The packet to be retransmitted private: //Doc:Method Time_t TimeDelay(Node*); //Doc:Desc Calculate time between this node and specified peer node. //Doc:Arg1 Peer node pointer. //Doc:Return Time (Time_t). //Doc:Method void NeighbourList(NodeTimeVec_t& ntv); //Doc:Desc Get a list of all neighbor nodes on the same ethernet link //Doc:Arg1 vector will be populated with nodes and their delay times //Doc:Method void HandleFBR(EthernetEvent* e, Time_t t); //Doc:Desc Handles the first bit received event //Doc:Arg1 The Ethernet event //Doc:Arg1 Time of the event //Doc:Method Time_t SlotTime(); //Doc:Desc Calculate the slot time for this link. //Doc:Return slot Time (Time_t). private: Time_t busyendtime; // Time when the link will be free again Time_t holdtime; // Time to hold back all packets when collision occurs Time_t maxbackoff; // Maximum backoff timer Time_t backofftimer; // Backoff timer Time_t maxwaittime; // maximum delay Count_t busycount; // How many stations are transmitting Packet* lastpacketsent; // last packet sent by this interface LinkEvent* lastrxevent; // Last rx event scheduled by the link from this interface LinkEvent* lastchanacq; // Last channel acquired event scheduled by this interface LinkEvent* lasttransmit; // Last retransmit event scheduled by this interface NodeTimeVec_t nodeTimes; // vector containing neighbour nodes and their time delay Time_t tx_finishtime; // Transmit finish time bool bCast; // True if the last packet sent was a broadcast bool collision; LinkEventVec_t rxEvents; // A list of rx event pointers used when broadcasting Time_t slottime; // the slot time in seconds Time_t rtime; // time to retransmit Uniform* generator; // random number generator }; #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 248 ] ] ]
6d2d05cf0d25111a2d581cbf120903baccbf3f14
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaCommon/Python.hpp
19e08e655f2c0140d26d09309246e3e3278c73e7
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,122
hpp
#ifndef PYTHON_HPP_INCLUDED #define PYTHON_HPP_INCLUDED /* Copyright © 2009 Christopher Joseph Dean Schaefer (disks86) 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. */ #ifdef ENIGMA_PLATFORM_WINDOWS #pragma warning( push ) #pragma warning( disable : 4061 ) #pragma warning( disable : 4100 ) #pragma warning( disable : 4127 ) #pragma warning( disable : 4217 ) #pragma warning( disable : 4242 ) #pragma warning( disable : 4244 ) #pragma warning( disable : 4280 ) #pragma warning( disable : 4514 ) #pragma warning( disable : 4619 ) #pragma warning( disable : 4668 ) #pragma warning( disable : 4710 ) #pragma warning( disable : 4820 ) #include <boost/python.hpp> #pragma warning( pop ) #define PYTHON_LOADED 1 #endif #ifdef ENIGMA_PLATFORM_LINUX #include <boost/python.hpp> #define PYTHON_LOADED 2 #endif #ifdef ENIGMA_PLATFORM_MAC #include <boost/python.hpp> #define PYTHON_LOADED 3 #endif #ifdef ENIGMA_PLATFORM_BSD #include <boost/python.hpp> #define PYTHON_LOADED 4 #endif #ifdef ENIGMA_PLATFORM_OPENSOLARIS #include <boost/python.hpp> #define PYTHON_LOADED 5 #endif #ifndef PYTHON_LOADED #include <boost/python.hpp> #define PYTHON_LOADED 6 #endif #endif // PYTHON_HPP_INCLUDED
[ [ [ 1, 60 ] ] ]
e43b097fb79790581b0f54244831f6da538815e5
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/samples/SAX2Count/SAX2Count.cpp
2b3e29c0621153baf83a508c5be433d1f5656047
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
14,833
cpp
/* * Copyright 1999-2001,2004 The Apache Software Foundation. * * 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. */ /* * $Log: SAX2Count.cpp,v $ * Revision 1.29 2004/09/08 13:55:33 peiyongz * Apache License Version 2.0 * * Revision 1.28 2004/09/02 14:59:29 cargilld * Add OutOfMemoryException block to samples. * * Revision 1.27 2004/04/13 19:40:47 peiyongz * usage * * Revision 1.26 2004/04/13 16:47:02 peiyongz * command line option to turn on/off Identity Constraint checking * * Revision 1.25 2003/05/30 09:36:36 gareth * Use new macros for iostream.h and std:: issues. * * Revision 1.24 2002/12/10 13:34:51 tng * Samples minor update in usage information. * * Revision 1.23 2002/11/08 16:18:50 peiyongz * no message * * Revision 1.22 2002/11/07 18:30:42 peiyongz * command line option for "locale" * * Revision 1.21 2002/11/04 14:09:06 tng * [Bug 14201] use of ios::nocreate breaks build. * * Revision 1.20 2002/11/01 22:05:57 tng * Samples/Test update: Issue error if the list file failed to open. * * Revision 1.19 2002/09/27 19:24:57 tng * Samples Fix: wrong length in memset * * Revision 1.18 2002/07/17 18:58:35 tng * samples update: for testing special encoding purpose. * * Revision 1.17 2002/06/17 15:33:05 tng * Name Xerces features as XMLUni::fgXercesXXXX instead of XMLUni::fgSAX2XercesXXXX so that they can be shared with DOM parser. * * Revision 1.16 2002/02/13 16:11:06 knoaman * Update samples to use SAX2 features/properties constants from XMLUni. * * Revision 1.15 2002/02/06 16:36:51 knoaman * Added a new flag '-p' to SAX2 samples to set the 'namespace-prefixes' feature. * * Revision 1.14 2002/02/01 22:38:52 peiyongz * sane_include * * Revision 1.13 2001/10/29 17:02:57 tng * Fix typo in samples. * * Revision 1.12 2001/10/25 15:18:33 tng * delete the parser before XMLPlatformUtils::Terminate. * * Revision 1.11 2001/10/19 19:02:43 tng * [Bug 3909] return non-zero an exit code when error was encounted. * And other modification for consistent help display and return code across samples. * * Revision 1.10 2001/08/15 12:41:04 tng * Initialize the fURI array to zeros, in case, some compilers like AIX xlC_r doesn't reset the memory. * * Revision 1.9 2001/08/08 12:12:32 tng * Print the file name only if doList is on. * * Revision 1.8 2001/08/03 15:08:17 tng * close the list file. * * Revision 1.7 2001/08/02 17:10:29 tng * Allow DOMCount/SAXCount/IDOMCount/SAX2Count to take a file that has a list of xml file as input. * * Revision 1.6 2001/08/01 19:11:01 tng * Add full schema constraint checking flag to the samples and the parser. * * Revision 1.5 2001/05/11 13:24:56 tng * Copyright update. * * Revision 1.4 2001/05/03 15:59:55 tng * Schema: samples update with schema * * Revision 1.3 2000/08/09 22:46:06 jpolast * replace occurences of SAXCount with SAX2Count * * Revision 1.2 2000/08/09 22:40:15 jpolast * updates for changes to sax2 core functionality. * * Revision 1.1 2000/08/08 17:17:20 jpolast * initial checkin of SAX2Count * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "SAX2Count.hpp" #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/sax2/SAX2XMLReader.hpp> #include <xercesc/sax2/XMLReaderFactory.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <fstream> #else #include <fstream.h> #endif #include <xercesc/util/OutOfMemoryException.hpp> // --------------------------------------------------------------------------- // Local helper methods // --------------------------------------------------------------------------- void usage() { XERCES_STD_QUALIFIER cout << "\nUsage:\n" " SAX2Count [options] <XML file | List file>\n\n" "This program invokes the SAX2XMLReader, and then prints the\n" "number of elements, attributes, spaces and characters found\n" "in each XML file, using SAX2 API.\n\n" "Options:\n" " -l Indicate the input file is a List File that has a list of xml files.\n" " Default to off (Input file is an XML file).\n" " -v=xxx Validation scheme [always | never | auto*].\n" " -f Enable full schema constraint checking processing. Defaults to off.\n" " -p Enable namespace-prefixes feature. Defaults to off.\n" " -n Disable namespace processing. Defaults to on.\n" " NOTE: THIS IS OPPOSITE FROM OTHER SAMPLES.\n" " -s Disable schema processing. Defaults to on.\n" " NOTE: THIS IS OPPOSITE FROM OTHER SAMPLES.\n" " -i Disable identity constraint checking. Defaults to on.\n" " NOTE: THIS IS OPPOSITE FROM OTHER SAMPLES.\n" " -locale=ll_CC specify the locale, default: en_US.\n" " -? Show this help.\n\n" " * = Default if not provided explicitly.\n" << XERCES_STD_QUALIFIER endl; } // --------------------------------------------------------------------------- // Program entry point // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Check command line and extract arguments. if (argC < 2) { usage(); return 1; } const char* xmlFile = 0; SAX2XMLReader::ValSchemes valScheme = SAX2XMLReader::Val_Auto; bool doNamespaces = true; bool doSchema = true; bool schemaFullChecking = false; bool identityConstraintChecking = true; bool doList = false; bool errorOccurred = false; bool namespacePrefixes = false; bool recognizeNEL = false; char localeStr[64]; memset(localeStr, 0, sizeof localeStr); int argInd; for (argInd = 1; argInd < argC; argInd++) { // Break out on first parm not starting with a dash if (argV[argInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[argInd], "-?")) { usage(); return 2; } else if (!strncmp(argV[argInd], "-v=", 3) || !strncmp(argV[argInd], "-V=", 3)) { const char* const parm = &argV[argInd][3]; if (!strcmp(parm, "never")) valScheme = SAX2XMLReader::Val_Never; else if (!strcmp(parm, "auto")) valScheme = SAX2XMLReader::Val_Auto; else if (!strcmp(parm, "always")) valScheme = SAX2XMLReader::Val_Always; else { XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl; return 2; } } else if (!strcmp(argV[argInd], "-n") || !strcmp(argV[argInd], "-N")) { doNamespaces = false; } else if (!strcmp(argV[argInd], "-s") || !strcmp(argV[argInd], "-S")) { doSchema = false; } else if (!strcmp(argV[argInd], "-f") || !strcmp(argV[argInd], "-F")) { schemaFullChecking = true; } else if (!strcmp(argV[argInd], "-i") || !strcmp(argV[argInd], "-I")) { identityConstraintChecking = false; } else if (!strcmp(argV[argInd], "-l") || !strcmp(argV[argInd], "-L")) { doList = true; } else if (!strcmp(argV[argInd], "-p") || !strcmp(argV[argInd], "-P")) { namespacePrefixes = true; } else if (!strcmp(argV[argInd], "-special:nel")) { // turning this on will lead to non-standard compliance behaviour // it will recognize the unicode character 0x85 as new line character // instead of regular character as specified in XML 1.0 // do not turn this on unless really necessary recognizeNEL = true; } else if (!strncmp(argV[argInd], "-locale=", 8)) { // Get out the end of line strcpy(localeStr, &(argV[argInd][8])); } else { XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[argInd] << "', ignoring it\n" << XERCES_STD_QUALIFIER endl; } } // // There should be only one and only one parameter left, and that // should be the file name. // if (argInd != argC - 1) { usage(); return 1; } // Initialize the XML4C2 system try { if (strlen(localeStr)) { XMLPlatformUtils::Initialize(localeStr); } else { XMLPlatformUtils::Initialize(); } if (recognizeNEL) { XMLPlatformUtils::recognizeNEL(recognizeNEL); } } catch (const XMLException& toCatch) { XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n" << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl; return 1; } // // Create a SAX parser object. Then, according to what we were told on // the command line, set it to validate or not. // SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(); parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces); parser->setFeature(XMLUni::fgXercesSchema, doSchema); parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking); parser->setFeature(XMLUni::fgXercesIdentityConstraintChecking, identityConstraintChecking); parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes); if (valScheme == SAX2XMLReader::Val_Auto) { parser->setFeature(XMLUni::fgSAX2CoreValidation, true); parser->setFeature(XMLUni::fgXercesDynamic, true); } if (valScheme == SAX2XMLReader::Val_Never) { parser->setFeature(XMLUni::fgSAX2CoreValidation, false); } if (valScheme == SAX2XMLReader::Val_Always) { parser->setFeature(XMLUni::fgSAX2CoreValidation, true); parser->setFeature(XMLUni::fgXercesDynamic, false); } // // Create our SAX handler object and install it on the parser, as the // document and error handler. // SAX2CountHandlers handler; parser->setContentHandler(&handler); parser->setErrorHandler(&handler); // // Get the starting time and kick off the parse of the indicated // file. Catch any exceptions that might propogate out of it. // unsigned long duration; bool more = true; XERCES_STD_QUALIFIER ifstream fin; // the input is a list file if (doList) fin.open(argV[argInd]); if (fin.fail()) { XERCES_STD_QUALIFIER cerr <<"Cannot open the list file: " << argV[argInd] << XERCES_STD_QUALIFIER endl; return 2; } while (more) { char fURI[1000]; //initialize the array to zeros memset(fURI,0,sizeof(fURI)); if (doList) { if (! fin.eof() ) { fin.getline (fURI, sizeof(fURI)); if (!*fURI) continue; else { xmlFile = fURI; XERCES_STD_QUALIFIER cerr << "==Parsing== " << xmlFile << XERCES_STD_QUALIFIER endl; } } else break; } else { xmlFile = argV[argInd]; more = false; } //reset error count first handler.resetErrors(); try { const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); parser->parse(xmlFile); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; errorOccurred = true; continue; } catch (const XMLException& e) { XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(e.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl; errorOccurred = true; continue; } catch (...) { XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n"; errorOccurred = true; continue; } // Print out the stats that we collected and time taken if (!handler.getSawErrors()) { XERCES_STD_QUALIFIER cout << xmlFile << ": " << duration << " ms (" << handler.getElementCount() << " elems, " << handler.getAttrCount() << " attrs, " << handler.getSpaceCount() << " spaces, " << handler.getCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl; } else errorOccurred = true; } if (doList) fin.close(); // // Delete the parser itself. Must be done prior to calling Terminate, below. // delete parser; // And call the termination method XMLPlatformUtils::Terminate(); if (errorOccurred) return 4; else return 0; }
[ [ [ 1, 434 ] ] ]
75a9e9d3139ace25ca3695ad17ce9383f6b535dc
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestdocandinit/src/bctestDocAndInitappui.cpp
cc0334c67c31c100431f53a0dbbab44701b45b95
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,296
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: test bc for DocAndInit control api(s) * */ #include <avkon.hrh> #include <aknsutils.h> #include "bctestdocandinitAppUi.h" #include "bctestdocandinit.hrh" #include "bctestdocandinitview.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // ctro do nothing // --------------------------------------------------------------------------- // CBCTestDocAndInitAppUi::CBCTestDocAndInitAppUi() { } // --------------------------------------------------------------------------- // symbian 2nd phase ctor // --------------------------------------------------------------------------- // void CBCTestDocAndInitAppUi::ConstructL() { BaseConstructL(); AknsUtils::SetAvkonSkinEnabledL( ETrue ); // init view CBCTestDocAndInitView* view = CBCTestDocAndInitView::NewL(); CleanupStack::PushL( view ); AddViewL( view ); CleanupStack::Pop( view ); ActivateLocalViewL( view->Id() ); } // ---------------------------------------------------------------------------- // CBCTestDocAndInitAppUi::~CBCTestDocAndInitAppUi() // Destructor. // ---------------------------------------------------------------------------- // CBCTestDocAndInitAppUi::~CBCTestDocAndInitAppUi() { } // ---------------------------------------------------------------------------- // handle menu command events // ---------------------------------------------------------------------------- // void CBCTestDocAndInitAppUi::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EAknSoftkeyBack: case EEikCmdExit: { Exit(); return; } default: break; } } // End of File
[ "none@none" ]
[ [ [ 1, 81 ] ] ]
6e4a29eeca5b23eb55124122915f0a4f77e44deb
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/public/sample_ext/sdk/smsdk_ext.cpp
674e04e435b17e699689ccfff98bed142d9fd5ea
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,786
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod Base Extension Code * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include <stdio.h> #include <malloc.h> #include "smsdk_ext.h" /** * @file smsdk_ext.cpp * @brief Contains wrappers for making Extensions easier to write. */ IExtension *myself = NULL; /**< Ourself */ IShareSys *g_pShareSys = NULL; /**< Share system */ IShareSys *sharesys = NULL; /**< Share system */ ISourceMod *g_pSM = NULL; /**< SourceMod helpers */ ISourceMod *smutils = NULL; /**< SourceMod helpers */ #if defined SMEXT_ENABLE_FORWARDSYS IForwardManager *g_pForwards = NULL; /**< Forward system */ IForwardManager *forwards = NULL; /**< Forward system */ #endif #if defined SMEXT_ENABLE_HANDLESYS IHandleSys *g_pHandleSys = NULL; /**< Handle system */ IHandleSys *handlesys = NULL; /**< Handle system */ #endif #if defined SMEXT_ENABLE_PLAYERHELPERS IPlayerManager *playerhelpers = NULL; /**< Player helpers */ #endif //SMEXT_ENABLE_PLAYERHELPERS #if defined SMEXT_ENABLE_DBMANAGER IDBManager *dbi = NULL; /**< DB Manager */ #endif //SMEXT_ENABLE_DBMANAGER #if defined SMEXT_ENABLE_GAMECONF IGameConfigManager *gameconfs = NULL; /**< Game config manager */ #endif //SMEXT_ENABLE_DBMANAGER #if defined SMEXT_ENABLE_MEMUTILS IMemoryUtils *memutils = NULL; #endif //SMEXT_ENABLE_DBMANAGER #if defined SMEXT_ENABLE_GAMEHELPERS IGameHelpers *gamehelpers = NULL; #endif #if defined SMEXT_ENABLE_TIMERSYS ITimerSystem *timersys = NULL; #endif #if defined SMEXT_ENABLE_ADTFACTORY IADTFactory *adtfactory = NULL; #endif #if defined SMEXT_ENABLE_THREADER IThreader *threader = NULL; #endif #if defined SMEXT_ENABLE_LIBSYS ILibrarySys *libsys = NULL; #endif #if defined SMEXT_ENABLE_PLUGINSYS SourceMod::IPluginManager *plsys; #endif #if defined SMEXT_ENABLE_MENUS IMenuManager *menus = NULL; #endif #if defined SMEXT_ENABLE_ADMINSYS IAdminSystem *adminsys = NULL; #endif #if defined SMEXT_ENABLE_TEXTPARSERS ITextParsers *textparsers = NULL; #endif #if defined SMEXT_ENABLE_USERMSGS IUserMessages *usermsgs = NULL; #endif /** Exports the main interface */ PLATFORM_EXTERN_C IExtensionInterface *GetSMExtAPI() { return g_pExtensionIface; } SDKExtension::SDKExtension() { #if defined SMEXT_CONF_METAMOD m_SourceMMLoaded = false; m_WeAreUnloaded = false; m_WeGotPauseChange = false; #endif } bool SDKExtension::OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late) { g_pShareSys = sharesys = sys; myself = me; #if defined SMEXT_CONF_METAMOD m_WeAreUnloaded = true; if (!m_SourceMMLoaded) { if (error) { snprintf(error, maxlength, "Metamod attach failed"); } return false; } #endif SM_GET_IFACE(SOURCEMOD, g_pSM); smutils = g_pSM; #if defined SMEXT_ENABLE_HANDLESYS SM_GET_IFACE(HANDLESYSTEM, g_pHandleSys); handlesys = g_pHandleSys; #endif #if defined SMEXT_ENABLE_FORWARDSYS SM_GET_IFACE(FORWARDMANAGER, g_pForwards); forwards = g_pForwards; #endif #if defined SMEXT_ENABLE_PLAYERHELPERS SM_GET_IFACE(PLAYERMANAGER, playerhelpers); #endif #if defined SMEXT_ENABLE_DBMANAGER SM_GET_IFACE(DBI, dbi); #endif #if defined SMEXT_ENABLE_GAMECONF SM_GET_IFACE(GAMECONFIG, gameconfs); #endif #if defined SMEXT_ENABLE_MEMUTILS SM_GET_IFACE(MEMORYUTILS, memutils); #endif #if defined SMEXT_ENABLE_GAMEHELPERS SM_GET_IFACE(GAMEHELPERS, gamehelpers); #endif #if defined SMEXT_ENABLE_TIMERSYS SM_GET_IFACE(TIMERSYS, timersys); #endif #if defined SMEXT_ENABLE_ADTFACTORY SM_GET_IFACE(ADTFACTORY, adtfactory); #endif #if defined SMEXT_ENABLE_THREADER SM_GET_IFACE(THREADER, threader); #endif #if defined SMEXT_ENABLE_LIBSYS SM_GET_IFACE(LIBRARYSYS, libsys); #endif #if defined SMEXT_ENABLE_PLUGINSYS SM_GET_IFACE(PLUGINSYSTEM, plsys); #endif #if defined SMEXT_ENABLE_MENUS SM_GET_IFACE(MENUMANAGER, menus); #endif #if defined SMEXT_ENABLE_ADMINSYS SM_GET_IFACE(ADMINSYS, adminsys); #endif #if defined SMEXT_ENABLE_TEXTPARSERS SM_GET_IFACE(TEXTPARSERS, textparsers); #endif #if defined SMEXT_ENABLE_USERMSGS SM_GET_IFACE(USERMSGS, usermsgs); #endif if (SDK_OnLoad(error, maxlength, late)) { #if defined SMEXT_CONF_METAMOD m_WeAreUnloaded = true; #endif return true; } return false; } bool SDKExtension::IsMetamodExtension() { #if defined SMEXT_CONF_METAMOD return true; #else return false; #endif } void SDKExtension::OnExtensionPauseChange(bool state) { #if defined SMEXT_CONF_METAMOD m_WeGotPauseChange = true; #endif SDK_OnPauseChange(state); } void SDKExtension::OnExtensionsAllLoaded() { SDK_OnAllLoaded(); } void SDKExtension::OnExtensionUnload() { #if defined SMEXT_CONF_METAMOD m_WeAreUnloaded = true; #endif SDK_OnUnload(); } const char *SDKExtension::GetExtensionAuthor() { return SMEXT_CONF_AUTHOR; } const char *SDKExtension::GetExtensionDateString() { return SMEXT_CONF_DATESTRING; } const char *SDKExtension::GetExtensionDescription() { return SMEXT_CONF_DESCRIPTION; } const char *SDKExtension::GetExtensionVerString() { return SMEXT_CONF_VERSION; } const char *SDKExtension::GetExtensionName() { return SMEXT_CONF_NAME; } const char *SDKExtension::GetExtensionTag() { return SMEXT_CONF_LOGTAG; } const char *SDKExtension::GetExtensionURL() { return SMEXT_CONF_URL; } bool SDKExtension::SDK_OnLoad(char *error, size_t maxlength, bool late) { return true; } void SDKExtension::SDK_OnUnload() { } void SDKExtension::SDK_OnPauseChange(bool paused) { } void SDKExtension::SDK_OnAllLoaded() { } #if defined SMEXT_CONF_METAMOD PluginId g_PLID = 0; /**< Metamod plugin ID */ ISmmPlugin *g_PLAPI = NULL; /**< Metamod plugin API */ SourceHook::ISourceHook *g_SHPtr = NULL; /**< SourceHook pointer */ ISmmAPI *g_SMAPI = NULL; /**< SourceMM API pointer */ IVEngineServer *engine = NULL; /**< IVEngineServer pointer */ IServerGameDLL *gamedll = NULL; /**< IServerGameDLL pointer */ /** Exposes the extension to Metamod */ SMM_API void *PL_EXPOSURE(const char *name, int *code) { #if defined METAMOD_PLAPI_VERSION if (name && !strcmp(name, METAMOD_PLAPI_NAME)) #else if (name && !strcmp(name, PLAPI_NAME)) #endif { if (code) { *code = IFACE_OK; } return static_cast<void *>(g_pExtensionIface); } if (code) { *code = IFACE_FAILED; } return NULL; } bool SDKExtension::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) { PLUGIN_SAVEVARS(); #if !defined METAMOD_PLAPI_VERSION GET_V_IFACE_ANY(serverFactory, gamedll, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL); GET_V_IFACE_CURRENT(engineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER); #else GET_V_IFACE_ANY(GetServerFactory, gamedll, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL); GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER); #endif m_SourceMMLoaded = true; return SDK_OnMetamodLoad(ismm, error, maxlen, late); } bool SDKExtension::Unload(char *error, size_t maxlen) { if (!m_WeAreUnloaded) { if (error) { snprintf(error, maxlen, "This extension must be unloaded by SourceMod."); } return false; } return SDK_OnMetamodUnload(error, maxlen); } bool SDKExtension::Pause(char *error, size_t maxlen) { if (!m_WeGotPauseChange) { if (error) { snprintf(error, maxlen, "This extension must be paused by SourceMod."); } return false; } m_WeGotPauseChange = false; return SDK_OnMetamodPauseChange(true, error, maxlen); } bool SDKExtension::Unpause(char *error, size_t maxlen) { if (!m_WeGotPauseChange) { if (error) { snprintf(error, maxlen, "This extension must be unpaused by SourceMod."); } return false; } m_WeGotPauseChange = false; return SDK_OnMetamodPauseChange(false, error, maxlen); } const char *SDKExtension::GetAuthor() { return GetExtensionAuthor(); } const char *SDKExtension::GetDate() { return GetExtensionDateString(); } const char *SDKExtension::GetDescription() { return GetExtensionDescription(); } const char *SDKExtension::GetLicense() { return SMEXT_CONF_LICENSE; } const char *SDKExtension::GetLogTag() { return GetExtensionTag(); } const char *SDKExtension::GetName() { return GetExtensionName(); } const char *SDKExtension::GetURL() { return GetExtensionURL(); } const char *SDKExtension::GetVersion() { return GetExtensionVerString(); } bool SDKExtension::SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlength, bool late) { return true; } bool SDKExtension::SDK_OnMetamodUnload(char *error, size_t maxlength) { return true; } bool SDKExtension::SDK_OnMetamodPauseChange(bool paused, char *error, size_t maxlength) { return true; } #endif /* Overload a few things to prevent libstdc++ linking */ #if defined __linux__ extern "C" void __cxa_pure_virtual(void) { } void *operator new(size_t size) { return malloc(size); } void *operator new[](size_t size) { return malloc(size); } void operator delete(void *ptr) { free(ptr); } void operator delete[](void * ptr) { free(ptr); } #endif
[ [ [ 1, 2 ], [ 7, 7 ], [ 28, 41 ], [ 44, 44 ], [ 48, 48 ], [ 97, 112 ], [ 114, 114 ], [ 116, 124 ], [ 126, 130 ], [ 137, 137 ], [ 182, 182 ], [ 184, 258 ], [ 260, 288 ], [ 292, 292 ], [ 294, 313 ], [ 315, 316 ], [ 321, 412 ], [ 414, 417 ], [ 419, 422 ], [ 424, 455 ] ], [ [ 3, 6 ], [ 8, 15 ], [ 17, 18 ], [ 20, 27 ], [ 113, 113 ], [ 125, 125 ], [ 183, 183 ], [ 259, 259 ], [ 413, 413 ], [ 418, 418 ], [ 423, 423 ] ], [ [ 16, 16 ], [ 19, 19 ], [ 42, 43 ], [ 45, 47 ], [ 49, 96 ], [ 115, 115 ], [ 131, 136 ], [ 138, 181 ], [ 289, 291 ], [ 293, 293 ], [ 317, 320 ] ], [ [ 314, 314 ] ] ]
297cd7f5f095f643d4649606a678b19adb7bded6
d826e0dcc5b51f57101f2579d65ce8e010f084ec
/pre/FSOLIDCreateProtrusionSweep.h
789d76dde2f2dd5ea15fbc99074b040adaf64a4b
[]
no_license
crazyhedgehog/macro-parametric
308d9253b96978537a26ade55c9c235e0442d2c4
9c98d25e148f894b45f69094a4031b8ad938bcc9
refs/heads/master
2020-05-18T06:01:30.426388
2009-06-26T15:00:02
2009-06-26T15:00:02
38,305,994
0
0
null
null
null
null
UTF-8
C++
false
false
797
h
#pragma once #include "Feature.h" class Part; class FSketch; class FSOLIDCreateProtrusionSweep : public Feature { public: //! A constructor /*! \param part Part class pointer \param fTag Object Tag tag_t \param pFSketch FSketch class pointer */ FSOLIDCreateProtrusionSweep(Part * part, tag_t fTag); virtual ~FSOLIDCreateProtrusionSweep(void) {} void SetProSket(FSketch * fps) {_pProFSket=fps;} FSketch * GetProSket() {return _pProFSket;} void SetGuideCurve(FSketch * fgc) {_pGuiFSket=fgc;} FSketch * GetGuideSketch() {return _pGuiFSket;} virtual void GetUGInfo(); virtual void ToTransCAD(); private : static int _proSweepCount; //!< Solid Create Protrusion Extrude Sweep count protected: FSketch * _pProFSket; FSketch * _pGuiFSket; };
[ "surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e" ]
[ [ [ 1, 35 ] ] ]
6651829bc898f5c113858f2bb5183b2d0f00c964
da3ff7f7300b77809c7d8b59bfb943ee6ebb9a39
/Share/stock.hpp
bc9fe16f6cc71e1c9fd9408f2cbeeabeaaf3690a
[]
no_license
coolboy/cpper
329540795ee86820ef81b44afa2c71a1c19168f2
109790a102fdb3ccd3e0055bcb2098940c1a9b03
refs/heads/master
2021-01-23T20:21:31.469730
2009-05-05T05:02:12
2009-05-05T05:02:12
32,131,620
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
hpp
#pragma once #include <string> namespace network { /// Structure to hold information about a single stock. struct stock { std::string code; std::string name; double open_price; double high_price; double low_price; double last_price; double buy_price; int buy_quantity; double sell_price; int sell_quantity; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & code; ar & name; ar & open_price; ar & high_price; ar & low_price; ar & last_price; ar & buy_price; ar & buy_quantity; ar & sell_price; ar & sell_quantity; } }; std::ostream& operator << (std::ostream& ostrm, const stock& obj) { ostrm << " code: " << obj.code << "\n"; ostrm << " name: " << obj.name << "\n"; ostrm << " open_price: " << obj.open_price << "\n"; ostrm << " high_price: " << obj.high_price << "\n"; ostrm << " low_price: " << obj.low_price << "\n"; ostrm << " last_price: " << obj.last_price << "\n"; ostrm << " buy_price: " << obj.buy_price << "\n"; ostrm << " buy_quantity: " << obj.buy_quantity << "\n"; ostrm << " sell_price: " << obj.sell_price << "\n"; ostrm << " sell_quantity: " << obj.sell_quantity << "\n"; return ostrm; } } // namespace network
[ "coolcute@bca9f61a-c139-0410-b77b-8f19f4552143" ]
[ [ [ 1, 52 ] ] ]
ac8c720b59a5e4c8d405244476341979498c8a8a
d826e0dcc5b51f57101f2579d65ce8e010f084ec
/pre/FSOLIDOperateFilletingFilletConstant.cpp
0c60ee76109d57beb9c492b7698921e0fd35da7e
[]
no_license
crazyhedgehog/macro-parametric
308d9253b96978537a26ade55c9c235e0442d2c4
9c98d25e148f894b45f69094a4031b8ad938bcc9
refs/heads/master
2020-05-18T06:01:30.426388
2009-06-26T15:00:02
2009-06-26T15:00:02
38,305,994
0
0
null
null
null
null
UHC
C++
false
false
4,540
cpp
#include ".\FSOLIDOperateFilletingFilletConstant.h" #include <iostream> #include <uf_vec.h> #include <uf_modl.h> #include <uf_sket.h> #include <uf_obj.h> #include <uf_object_types.h> #include "UGPre.h" #include "Part.h" #include "Feature.h" #include "FSketch.h" #include "FSOLIDCreateProtrusionExtrude.h" using namespace std; int FSOLIDOperateFilletingFilletConstant::_fillCnt = 0; FSOLIDOperateFilletingFilletConstant::FSOLIDOperateFilletingFilletConstant(Part * part, tag_t fTag) : Feature(part, fTag) { } void FSOLIDOperateFilletingFilletConstant::GetUGInfo() { //--------- get the blended edge geometry information ---------// UF_MODL_edge_blend_data_t ugBlendEdge; UF_CALL(UF_MODL_ask_edge_blend(_fTag,&ugBlendEdge) ); // output to be freeed : later tag_t blendedEdgeTag = ugBlendEdge.edge_data->edge; cout << " " << "Num of Points : " << ugBlendEdge.edge_data->number_points << endl; // Set fillet dR and Propagation Type _dR = atof(ugBlendEdge.blend_radius); _PropType = Minimal; //DEBUG cout << " " << "Num of Blended edges : " << ugBlendEdge.number_edges << endl; cout << " " << "Edge Tag : " << blendedEdgeTag << endl; int edge_type; double* edge_data; UF_CURVE_struct_p_t edge_struct_p_t; UF_CALL( UF_CURVE_ask_curve_struct(blendedEdgeTag, &edge_struct_p_t) ); UF_CALL( UF_CURVE_ask_curve_struct_data(edge_struct_p_t, &edge_type, &edge_data) ); if( edge_type == UF_line_type) // UF_line_type : 3 { cout << " " << " Edge_Type " << edge_type << endl; cout << " " << edge_data[3] << " " << edge_data[4] << " " << edge_data[5] << endl; cout << " " << edge_data[6] << " " << edge_data[7] << " " << edge_data[8] << endl; ValRndPnt(edge_data+3); ValRndPnt(edge_data+6); // UF_CURVE_ask_curve_struct_data 부정확하므로 소수 6자리 이하 Rounding!! _sP = Point3D(edge_data+3); _eP = Point3D(edge_data+6); _pP = (_sP+_eP) * 0.5 ; } else { cout << " " << "Cannot support Blended Edge Type!!" << endl; cout << " " << "Only support Linear Edge!!" << endl; } UF_CALL(UF_CURVE_free_curve_struct(edge_struct_p_t)); UF_free(edge_data); //--------- Get the Related Skech Info ---------// int num_parents, num_children; tag_t *parent_array, *children_array; UF_MODL_ask_feat_relatives(GetFTag(),&num_parents,&parent_array, &num_children,&children_array); cout << " " << "No. of Parents : " << num_parents << endl; for(int i=0; i<num_parents ; i++) { char* feat_type; UF_MODL_ask_feat_type(parent_array[i],&feat_type); cout << " " << "Parent[" << i << "] : " << feat_type << " Type" << endl; Feature* pFeature = GetPart()->GetFeatureByTag(parent_array[0]); if (pFeature) { double sketInfo[12]; bool bInfo = 0; switch (pFeature->GetFType()) { case SOLID_Create_Protrusion_Extrude : ((FSOLIDCreateProtrusionExtrude*)pFeature)->GetProSket()->GetSketInfo(sketInfo); bInfo = 1; break; default : break; } if (bInfo) { Map(sketInfo,&(_sP[0])); Map(sketInfo,&(_eP[0])); Map(sketInfo,&(_pP[0])); break; } } } ValRndPnt(&(_sP[0])); ValRndPnt(&(_eP[0])); ValRndPnt(&(_pP[0])); UF_free(parent_array); UF_free(children_array); //---------------- Set Result_Object_Name -----------------// char buffer[20]; _itoa( _fillCnt++, buffer, 10 ); SetName("fillet" + (string)buffer); } void FSOLIDOperateFilletingFilletConstant::ToTransCAD() { //return; //if (_fillCnt==2) {_fillCnt++; return;} // Select object //TransCAD::IReferencePtr spReference = GetPart()->_spPart->SelectBrepByName( // "proExtrude0,sketch0,line2D2,0,0,0,ExtrudeFeature:0,0:0;0#proExtrude0,sketch0,line2D3,0,0,0,ExtrudeFeature:0,0:0;0"); TransCAD::IReferencePtr spReference = GetPart()->_spPart->SelectCurveBy3Points( _sP[0],_sP[1],_sP[2],_eP[0],_eP[1],_eP[2],_pP[0],_pP[1],_pP[2]); //TransCAD::IReferencePtr spReference =0; if (spReference) { // Fillet Edges TransCAD::IReferencesPtr spReferences = GetPart()->_spPart->CreateReferences(); spReferences->Add(spReference); // Create a fillet constant feature GetPart()->_spFeatures->AddNewSolideFilletConstantFeature(GetName().c_str(), spReferences, GetRadius(), (TransCAD::PropagationType)GetPropType()); cout << " " <<_sP[0]<<" "<<_sP[1]<<" "<<_sP[2]<<endl; cout << " " <<_eP[0]<<" "<<_eP[1]<<" "<<_eP[2]<<endl; cout << " " <<_pP[0]<<" "<<_pP[1]<<" "<<_pP[2]<<endl; } }
[ "surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e" ]
[ [ [ 1, 135 ] ] ]
5136c9dec85dcc18130c16f3e52a06bfb4b846c4
f02d9d86fb32f26a1f2615be8240539cac92f9c2
/FiniteStateMachine.cpp
7f1a951df6d1bb4921165f4a62bab359db9519b8
[]
no_license
MarSik/MarSclock
30cc546c5cba98c3d28eaf348de50004e6b6f066
4df639a1b3cd19e75ae9ef599bdab0841e64ce8d
refs/heads/master
2020-12-24T14:36:59.876220
2011-02-22T22:21:57
2011-02-22T22:21:57
1,200,961
0
0
null
null
null
null
UTF-8
C++
false
false
2,373
cpp
/* || || @file FiniteStateMachine.cpp || @version 1.7 || @author Alexander Brevig || @contact [email protected] || || @description || | Provide an easy way of making finite state machines || # || || @license || | This library is free software; you can redistribute it and/or || | modify it under the terms of the GNU Lesser General Public || | License as published by the Free Software Foundation; version || | 2.1 of the License. || | || | This library is distributed in the hope that it will be useful, || | but WITHOUT ANY WARRANTY; without even the implied warranty of || | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU || | Lesser General Public License for more details. || | || | You should have received a copy of the GNU Lesser General Public || | License along with this library; if not, write to the Free Software || | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA || # || */ #include "FiniteStateMachine.h" //FINITE STATE MACHINE FiniteStateMachine::FiniteStateMachine(State& current){ needToTriggerEnter = true; currentState = nextState = &current; //stateChangeTime = 0; } FiniteStateMachine& FiniteStateMachine::update() { //simulate a transition to the first state //this only happens the first time update is called if (needToTriggerEnter) { currentState->enter(); needToTriggerEnter = false; } else { if (currentState != nextState){ immediateTransitionTo(*nextState); } currentState->update(); } return *this; } FiniteStateMachine& FiniteStateMachine::transitionTo(State& state){ nextState = &state; //stateChangeTime = millis(); return *this; } FiniteStateMachine& FiniteStateMachine::immediateTransitionTo(State& state){ currentState->exit(); currentState = nextState = &state; currentState->enter(); // stateChangeTime = millis(); return *this; } //return the current state State& FiniteStateMachine::getCurrentState() { return *currentState; } //check if state is equal to the currentState boolean FiniteStateMachine::isInState( State &state ) const { if (&state == currentState) { return true; } else { return false; } } //unsigned long FiniteStateMachine::timeInCurrentState() { // return millis() - stateChangeTime; //} //END FINITE STATE MACHINE
[ [ [ 1, 86 ] ] ]
ca6494175114249f170a93fcdb9d1edf9cc11735
11dfb7197905169a3f0544eeaf507fe108d50f7e
/slmdll_ga/slmcontrol.cpp
ead6b654cd8c31942ec7aed591c5f8c43a2afd7b
[]
no_license
rahulbhadani/adaptive-optics
67791a49ecbb085ac8effdc44e5177b0357b0fa7
e2b296664b7674e87a5a68ec7b794144b37ae74d
refs/heads/master
2020-04-28T00:08:24.585833
2011-08-09T22:28:11
2011-08-09T22:28:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,251
cpp
#include "stdafx.h" #include "slmproject.h" #include "slmcontrol.h" //classes SlmCom::SlmCom() { FrameNum = 0; ImgWidth = SLMSIZE; ImgHeight = SLMSIZE; } bool SlmCom::InitSlm() { CString BoardName = "512A_SLM"; unsigned short LC_Type = 1; unsigned short TrueFrames = 3; bool VerifyHardware; CBNSFactory boardFactory; theBoard = boardFactory.BuildBoard(BoardName, LC_Type, TrueFrames, &VerifyHardware); //if Verify hardware is false, then the wrong board class was built for //the hardware in the machine. So we need to build a different board class //all the other variables passed to the function remain the same if(!VerifyHardware) { //deconstruct the old board class, it is important to clean up what was //wrongly built delete theBoard; //assign the new board name to the BoardName variable BoardName = "256A_SLM"; //build the new board class theBoard = boardFactory.BuildBoard(BoardName, LC_Type, TrueFrames, &VerifyHardware); } //initialize that this program is not going to use continuous //downloads. Instead it will sequence through a series of //pre-loaded images. bool ContinuousDownload = true; theBoard->SetDownloadMode(ContinuousDownload); unsigned short FrameRate = 1000; unsigned short LaserDuty = 50; unsigned short TrueLaserGain = 255; unsigned short InverseLaserGain = 255; theBoard->SetRunParameters(FrameRate, LaserDuty, TrueLaserGain, InverseLaserGain); bPowerOn = (bool)theBoard->GetPower(); if(bPowerOn != true) { bPowerOn = true; theBoard->SetPower(bPowerOn); } //establish our image dimensions based on some Board Spec parameters ImgWidth = theBoard->BoardSpec()->FrameWidth; ImgHeight = theBoard->BoardSpec()->FrameHeight; memset(LUTBuf,0, 500*sizeof(unsigned char)); readlut(LUTBuf, LUTFILE); return true; } void SlmCom::readlut(unsigned char *LUT, CString lutfilename) { FILE *stream; int i, seqnum, ReturnVal, tmpLUT; //the LUT file stream = fopen(lutfilename,"r"); if (stream != NULL) { //read in all 256 values for (i=0; i<256; i++) { ReturnVal=fscanf(stream, "%d %d", &seqnum, &tmpLUT); if (ReturnVal!=2 || seqnum!=i || tmpLUT<0 || tmpLUT>255) { fclose(stream); printf("\nThere is error in lut file, while reading lut.\n"); break; } LUT[i] = (unsigned char) tmpLUT; } fclose(stream); return; } //if there was an error reading in the LUT, then default to a linear LUT for (i=0; i<256; i++) // linear // LUT[i]=i; // LUT[i]=0; printf("\nThere is error when open lut file, lut is set to linear.\n"); return; } void SlmCom::receiveData(unsigned char *Data) { #ifdef DEBUG_OUTPUT int tp, tp2; FILE *pfold; pfold = fopen("c:/slmcontrol/dumpout/VC_output0.txt","wt"); for (tp = 0; tp < 512; tp ++) { fprintf(pfold, "\n"); for (tp2 = 0; tp2 < 512; tp2++) fprintf(pfold, "%d, ", Data[tp*512 + tp2]); } fclose(pfold); #endif ImageData = (unsigned char *) malloc(ImgWidth*ImgHeight); for(int i = 0; i< ImgWidth*ImgHeight; i++) { ImageData[i] = LUTBuf[(Data[i])%256]; } return; } bool SlmCom::SendtoDlm(bool FrameNumchange) { if (!theBoard->WriteFrameBuffer(FrameNum, ImageData)) { free(ImageData); return false; } #ifdef DEBUG_OUTPUT int tp, tp2; FILE *pfold; pfold = fopen("c:/slmcontrol/dumpout/VC_output1.txt","wt"); for (tp = 0; tp < 512; tp ++) { fprintf(pfold, "\n"); for (tp2 = 0; tp2 < 512; tp2++) fprintf(pfold, "%d, ", ImageData[tp*512 + tp2]); } fclose(pfold); #endif if (FrameNumchange == true) { FrameNum ++; } free(ImageData); theBoard->SelectImage(FrameNum); return true; } void SlmCom::CloseSlm() { bPowerOn = false; theBoard->SetPower(bPowerOn); delete theBoard; theBoard = NULL; return; } void SlmCom::OpenSlm() { if (theBoard == NULL) { InitSlm(); } return; } void SlmCom::GetFramNum(int *frnum) { *frnum = FrameNum; return; } void SlmCom::GetWH(int *Wid, int *Height) { *Wid = ImgWidth; *Height = ImgHeight; return; }
[ [ [ 1, 201 ] ] ]
f222f522b67e9e08eb4a3fdec7333b2001185c1b
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/util.cpp
ba04999cebdc3a7190ea571bcf4c9686aadfbfcc
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
GB18030
C++
false
false
20,646
cpp
#include "stdafx.h" #include "util.h" #include <string> #include "./md5/md5sum.h" #include "./file/FileClass.h" #include "./update/verinfo.h" CString GetExePath() { TCHAR szBuffer[MAX_PATH]; ::GetModuleFileName(NULL, szBuffer, sizeof(szBuffer) / sizeof(TCHAR)); CString strPath(szBuffer); int nFind = strPath.ReverseFind(_T('\\')); if(nFind < 0) { return ""; } return strPath.Left(nFind + 1); } #ifndef _UNICODE CString Convert(CString str, int sourceCodepage, int targetCodepage) { int len=str.GetLength(); /* char* pChar = TranslateUTF_8ToGB( str.GetBuffer(len), len ); CString rt = ""; if ( pChar ) { len = strlen(pChar); rt.Format("%s",pChar); std::string strTemp = pChar; rt = strTemp.c_str(); delete [] pChar; } */ int unicodeLen = MultiByteToWideChar(sourceCodepage,0,str,-1,NULL,0); wchar_t* pUnicode; pUnicode=new wchar_t[unicodeLen+1]; memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); MultiByteToWideChar(sourceCodepage,0,str,-1,(LPWSTR)pUnicode,unicodeLen); BYTE * pTargetData = NULL; int targetLen = WideCharToMultiByte(targetCodepage,0,(LPWSTR)pUnicode,-1,(char *)pTargetData,0,NULL,NULL); pTargetData = new BYTE[targetLen+1]; memset(pTargetData,0,targetLen+1); WideCharToMultiByte(targetCodepage,0,(LPWSTR)pUnicode,-1,(char *)pTargetData,targetLen,NULL,NULL); CString rt; std::string strTemp = (char *)pTargetData; //rt.Format("%s",pTargetData); rt = strTemp.c_str(); delete [] pUnicode; delete [] pTargetData; /* static BOOL bStat = FALSE; if ( !bStat ) { bStat = TRUE; std::ofstream* g_logfile = new std::ofstream; g_logfile->open("c:\\tidy\\in.html", std::ios::out|std::ios::app); *g_logfile << str.GetBuffer(str.GetLength()) << std::endl; g_logfile->close(); delete g_logfile; g_logfile = new std::ofstream; g_logfile->open("c:\\tidy\\out.html", std::ios::out|std::ios::app); *g_logfile << rt.GetBuffer(rt.GetLength()) << std::endl; g_logfile->close(); delete g_logfile; len = rt.GetLength(); } */ return rt; } #endif // ifndef _UNICODE CString HexToBin(CString string)//将16进制数转换成2进制 { if( string == "0") return "0000"; if( string == "1") return "0001"; if( string == "2") return "0010"; if( string == "3") return "0011"; if( string == "4") return "0100"; if( string == "5") return "0101"; if( string == "6") return "0110"; if( string == "7") return "0111"; if( string == "8") return "1000"; if( string == "9") return "1001"; if( string == "a") return "1010"; if( string == "b") return "1011"; if( string == "c") return "1100"; if( string == "d") return "1101"; if( string == "e") return "1110"; if( string == "f") return "1111"; return ""; } CString BinToHex(CString BinString)//将2进制数转换成16进制 { if( BinString == "0000") return "0"; if( BinString == "0001") return "1"; if( BinString == "0010") return "2"; if( BinString == "0011") return "3"; if( BinString == "0100") return "4"; if( BinString == "0101") return "5"; if( BinString == "0110") return "6"; if( BinString == "0111") return "7"; if( BinString == "1000") return "8"; if( BinString == "1001") return "9"; if( BinString == "1010") return "a"; if( BinString == "1011") return "b"; if( BinString == "1100") return "c"; if( BinString == "1101") return "d"; if( BinString == "1110") return "e"; if( BinString == "1111") return "f"; return ""; } int BinToInt(CString string)//2进制字符数据转换成10进制整型 { int len =0; int tempInt = 0; int strInt = 0; for(int i =0 ;i < string.GetLength() ;i ++) { tempInt = 1; strInt = (int)string.GetAt(i)-48; for(int k =0 ;k < 7-i ; k++) { tempInt = 2*tempInt; } len += tempInt*strInt; } return len; } #if 0 // 错误的实现 // UTF-8转换成GB2312先把UTF-8转换成Unicode.然后再把Unicode通过函数WideCharToMultiByte转换成GB2312 WCHAR* UTF_8ToUnicode(char *ustart) //把UTF-8转换成Unicode { char char_one; char char_two; char char_three; int Hchar; int Lchar; char uchar[2]; WCHAR *unicode; CString string_one; CString string_two; CString string_three; CString combiString; char_one = *ustart; char_two = *(ustart+1); char_three = *(ustart+2); string_one.Format("%x",char_one); string_two.Format("%x",char_two); string_three.Format("%x",char_three); string_three = string_three.Right(2); string_two = string_two.Right(2); string_one = string_one.Right(2); string_three = HexToBin(string_three.Left(1))+HexToBin(string_three.Right(1)); string_two = HexToBin(string_two.Left(1))+HexToBin(string_two.Right(1)); string_one = HexToBin(string_one.Left(1))+HexToBin(string_one.Right(1)); combiString = string_one +string_two +string_three; combiString = combiString.Right(20); combiString.Delete(4,2); combiString.Delete(10,2); Hchar = BinToInt(combiString.Left(8)); Lchar = BinToInt(combiString.Right(8)); uchar[1] = (char)Hchar; uchar[0] = (char)Lchar; unicode = (WCHAR *)uchar; return unicode; } char * UnicodeToGB2312(unsigned short uData) //把Unicode 转换成 GB2312 { char *buffer ; buffer = new char[sizeof(WCHAR)]; WideCharToMultiByte(CP_ACP,NULL,&uData,1,buffer,sizeof(WCHAR),NULL,NULL); return buffer; } char * TranslateUTF_8ToGB(char *xmlStream, int len) //len 是xmlStream的长度 { char * newCharBuffer = new char[len]; int index =0; int nCBIndex = 0; while(index < len) { if(xmlStream[index] > 0) // 如果是GB2312的字符 { newCharBuffer[nCBIndex] = xmlStream[index]; //直接复制 index += 1; //源字符串偏移量1 nCBIndex += 1; //目标字符串偏移量1 } else //如果是UTF-8的字符 { WCHAR * Wtemp = UTF_8ToUnicode(xmlStream + index); //先把UTF-8转成Unicode char * Ctemp = UnicodeToGB2312(*Wtemp);//再把Unicode 转成 GB2312 newCharBuffer[nCBIndex] = * Ctemp; // 复制 newCharBuffer[nCBIndex + 1] = *(Ctemp + 1); index += 3; //源字符串偏移量3 nCBIndex += 2; //目标字符串偏移量2 因为一个中文UTF-8占3个字节,GB2312占两个字节 } } newCharBuffer[nCBIndex] = 0; //结束符 return newCharBuffer; } #endif // if 0 BOOL getWindowText(HWND hWnd, CString& text) { int nLen = MAX_PATH;//::GetWindowTextLength(hWnd); int nRetLen = ::GetWindowText(hWnd, text.GetBufferSetLength(nLen), nLen + 1); text.ReleaseBuffer(); if(nRetLen < nLen) return FALSE; return TRUE; } /* HRESULT GetMetaCurrentScheme(ISkinScheme** pScheme) { if (!_hLibSkinLoad) return S_FALSE; typedef BOOL (WINAPI *GetCurrentScheme)(ISkinScheme** pScheme); GetCurrentScheme pf = (GetCurrentScheme)GetProcAddress(_hLibSkinLoad, "GetCurrentScheme"); ATLASSERT(pf); if(pf) { pf(pScheme); } return S_OK; } HINSTANCE getSkinHanld() { if (_hLibSkinLoad) return _hLibSkinLoad; _hLibSkinLoad = LoadLibrary("skin.dll"); return _hLibSkinLoad; } */ BOOL OpenUrl(LPCTSTR szUrl) { CComQIPtr<IWebBrowser2> m_pWebBrowser2; m_pWebBrowser2.CoCreateInstance(CLSID_InternetExplorer); HRESULT hr; hr = m_pWebBrowser2->put_StatusBar(VARIANT_TRUE); hr = m_pWebBrowser2->put_ToolBar(VARIANT_TRUE); hr = m_pWebBrowser2->put_MenuBar(VARIANT_TRUE); hr = m_pWebBrowser2->put_Visible(VARIANT_TRUE); CComVariant v; CComBSTR url(szUrl); hr = m_pWebBrowser2->Navigate ( url, &v, &v, &v, &v ); if (FAILED(hr)) { CString cmd = _T("IEXPLORE.EXE \""); cmd += szUrl; cmd += _T("\""); //createProcess(cmd.c_str()); ShellExecute(NULL, _T("open"), szUrl, NULL, NULL, 2); return TRUE; } return TRUE; } void minimizeMemory() { OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure. // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) { osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return; } if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) { SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1); } } CString getTempFilePath() { TCHAR szTmpPath[1024]; TCHAR szTempName[MAX_PATH]; // get temp path GetTempPath(1024, // length of the buffer szTmpPath); // buffer for path // Create a temporary file. GetTempFileName(szTmpPath, // directory for temp files _T("NEW"), // temp file name prefix 0, // create unique name szTempName); // buffer for name return szTempName; } std::string GetFileMd5Info(std::string sFile) { int i = 0; int nCnt = 0; std::string sRet ; MD5Sum md5sum ; CFileClass FileObj ; DWORD dwFileLen = 0; BYTE buf[64*1024] = ""; if(!(FileObj.Open(sFile,CFileClass::modeRead | CFileClass::modeWrite))) { return ""; } dwFileLen = FileObj.GetLength(); nCnt = dwFileLen/(64*1024); for(i=0;i<nCnt;i++) { FileObj.Read(buf,64*1024); md5sum.put((char *)buf,1024*64); } if(nCnt*1024*64!=dwFileLen) { dwFileLen-=(nCnt*1024*64); FileObj.Read(buf,dwFileLen); md5sum.put((char *)buf,dwFileLen); } sRet = md5sum.toString(); FileObj.Close(); return sRet ; } int str_split(std::vector<std::string>& dest, const char* str, const char* delimiter, bool includeEmpty) { const char *prev = str; const char *cur = str; const char *tmp; bool found; std::string txt; dest.clear(); for(; *cur; cur++) { tmp = delimiter; found = false; while (*tmp) { if (*tmp == *cur) { found = true; break; } tmp++; } if(found) { if(prev < cur) { txt.assign(prev, cur - prev); dest.push_back(txt); prev = cur + 1; } else if(prev == cur) { prev = cur + 1; if(includeEmpty) dest.push_back(""); } } } if(prev < cur) { txt.assign(prev, cur - prev); dest.push_back(txt); } else if(prev == cur && includeEmpty) { dest.push_back(""); } return dest.size(); } /* BOOL InitMail() { _hMail = LoadLibrary("MAPI32.DLL"); if (_hMail == NULL) //加载动态库失败 { return FALSE; } //获取发送邮件的函数地址 (FARPROC&)_lpfnSendMail = GetProcAddress(_hMail, "MAPISendMail"); if ( _lpfnSendMail ) return TRUE; else return FALSE; } BOOL SendMail(HWND hWndParent, CString strMailto, CString strTitle, CString strContext) { if ( !_lpfnSendMail ) return FALSE; if (!hWndParent || !::IsWindow(hWndParent)) return FALSE; //收件人结构信息 MapiRecipDesc recip; memset(&recip,0,sizeof(MapiRecipDesc)); recip.lpszAddress = strMailto.GetBuffer(0); recip.ulRecipClass = MAPI_TO; //邮件结构信息 MapiMessage message; memset(&message, 0, sizeof(message)); message.nFileCount = 0; //文件个数 message.lpFiles = NULL; //文件信息 message.nRecipCount = 1; //收件人个数 message.lpRecips = &recip; //收件人 message.lpszSubject = strTitle.GetBuffer(0); //主题 message.lpszNoteText= strContext.GetBuffer(0); //正文内容 //发送邮件 int nError = _lpfnSendMail(0, (ULONG_PTR)hWndParent, &message, MAPI_LOGON_UI|MAPI_DIALOG, 0); if (nError != SUCCESS_SUCCESS && nError != MAPI_USER_ABORT && nError != MAPI_E_LOGIN_FAILURE) { //AfxMessageBox(AFX_IDP_FAILED_MAPI_SEND); MessageBox(NULL, "发送邮件失败", MSGTITLE, MB_OK); return FALSE; } return TRUE; } void ReleaseMail() { if ( _hMail ) FreeLibrary( _hMail ); } */ bool isFileExist(const TCHAR *file) { WIN32_FIND_DATA data; HANDLE handle; if(!file) return false; handle = FindFirstFile(file, &data); if(handle == INVALID_HANDLE_VALUE) return false; FindClose(handle); return true; } bool isDirectoryExist(const TCHAR *dir) { WIN32_FIND_DATA data; HANDLE handle; TCHAR *name; int len; if(!dir) return false; len = lstrlen(dir); name = (TCHAR *)malloc((len + 5)*sizeof(TCHAR)); lstrcpy(name, dir); if(name[len - 1] == _T('\\')) lstrcpy(name + len, _T("*.*")); else lstrcpy(name + len, _T("\\*.*")); handle = FindFirstFile(name, &data); free(name); if(handle == INVALID_HANDLE_VALUE) { return false; } FindClose(handle); return true; } bool createDirectory(const TCHAR *dir) { if(isDirectoryExist(dir)) return true; if(CreateDirectory(dir, NULL)) return true; else { if(GetLastError() == ERROR_PATH_NOT_FOUND) { TCHAR path[MAX_PATH*2]; lstrcpy(path, dir); TCHAR *p = path; while (*p) { if(*p == _T('\\') && *(p+1) != _T('\\')) { *p = 0; if(!isDirectoryExist(path)) { if(!CreateDirectory(path, NULL)) return false; } *p = _T('\\'); } p = CharNext(p); } if(!isDirectoryExist(path)) { if(!CreateDirectory(path, NULL)) return false; } return true; } return false; } } bool createProcess(LPCTSTR cmd, BOOL bShow, BOOL bUtilEnd) { PROCESS_INFORMATION pi; STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; if(bShow) { si.wShowWindow = SW_SHOWDEFAULT; //si.lpDesktop = "WinSta0\\Default"; } else { si.wShowWindow = SW_HIDE; } if(CreateProcess(NULL, (LPTSTR)cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { if(bUtilEnd) WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return true; } return false; } #if 0 //判断是否可以创建文件 bool CanCreateFile(const std::string & sFile) { if(sFile->empty()) return FALSE; if(isDirectoryExist(sFile.c_str())) return FALSE; std::ifstream inFile(sFile.c_str()); if(!inFile) return TRUE; else return FALSE; } #endif #if 0 // Not used //得到一个唯一的不存在文件名称 //得到唯一的文件名称--组合规则xxxxx(n).xxx std::string GetUniqueFileName(const std::string &sFile) { int nCount = 0; std::string::size_type dwPos = std::string::npos; std::string::size_type dwLeft = std::string::npos; std::string::size_type dwRight = std::string::npos; std::string sTempFile ; std::string sFileName ; std::string sFileType ; std::string sFilePath ; std::string sFileCount ; sTempFile = sFile; //得到原来的路径和文件名称 dwPos = sTempFile.rfind(_T('\\')); if(dwPos!=std::string::npos) { sFilePath = sTempFile.substr(0,dwPos+1); sFileName = sTempFile.substr(dwPos+1); } else { sFileName = sTempFile; sFilePath = _T(""); } //得到文件名称和类型 sTempFile = sFileName; dwPos = sTempFile.find(_T('.')); if(dwPos!=std::string::npos) { sFileName = sTempFile.substr(0,dwPos); sFileType = sTempFile.substr(dwPos+1); } //得到文件的计数 sTempFile = sFileName; dwLeft = sTempFile.find(_T("(")); dwRight = sTempFile.rfind(_T(")")); if((dwLeft==0 && dwRight==sTempFile.size()-1) || (dwRight!=sTempFile.size()-1 && dwRight!=std::string::npos )) { dwLeft = std::string::npos; dwRight = std::string::npos; } if(dwLeft!=std::string::npos && dwRight!=std::string::npos) { sFileCount = sTempFile.substr(dwLeft+1,(dwRight-dwLeft)-1); if(dwLeft+1==dwRight) { sFileCount = _T(""); sFileName = sTempFile.substr(0,dwLeft); } else { //如果存在非数字之外的字符 if(sFileCount.find_first_not_of(_T(" 0123456789"))!=std::string::npos) { sFileCount = _T(""); sFileName = sTempFile; } else { sFileName = sTempFile.substr(0,dwLeft); } } } //重新组合文件名称 while(TRUE) { std::ostringstream sRetName ; sRetName << sFilePath; sRetName << sFileName; if(nCount!=0) { sRetName << _T("("); sRetName << nCount; sRetName << _T(")"); } if(!sFileType.empty()) { sRetName << _T("."); sRetName << sFileType; } //查询文件是否存在 if(CanCreateFile(sRetName.str())) return sRetName.str(); nCount++; } } #endif // if 0 bool GetFileVer(const TCHAR * filename, CString &ver) { CFileVersionInfo fvi; if( fvi.Open(filename) ) { TCHAR szVer[ 512 ] = { 0 }; ::wsprintf( szVer, _T( "%d.%d.%d.%d" ), fvi.GetFileVersionMajor(), // Major version fvi.GetFileVersionMinor(), // Minor version fvi.GetFileVersionBuild(), // Build number fvi.GetFileVersionQFE() // QFE ); ver = szVer; fvi.Close(); return true; } return false; } bool GetClientVer (std::string & ver) { TCHAR szFileName[1024]; GetModuleFileName(NULL, szFileName, 1024); CString s; bool f = GetFileVer(szFileName, s); ver = CT2A(s); return f; } BOOL ShellOpenFile(LPCTSTR Filename) { if(Filename == NULL || *Filename == 0) return FALSE; BOOL bSuccess; SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = _T("open"); ShExecInfo.lpFile = Filename; ShExecInfo.lpParameters = NULL; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOWDEFAULT; ShExecInfo.hInstApp = NULL; bSuccess = ShellExecuteEx(&ShExecInfo); if(!bSuccess) { ShExecInfo.fMask = NULL; ShExecInfo.lpVerb = NULL; return ShellExecuteEx(&ShExecInfo); } return TRUE; } CString getEmailAddress(CString strMail) { static const CString strCon = "abcdefghijklmnopqrstuvwxyz_-.1234567890"; int nLen = strMail.GetLength(); if ( nLen < 4 ) return ""; // 1 取得@ int nPos = strMail.Find(_T("@")); if ( nPos <= 0 ) return ""; CString strLeft = ""; CString strRight = ""; // 2 判断@前,后是否是abcdefghijklmnopqrstuvwxyz_-. 和数字 for ( int i = nPos + 1; i < nLen; i ++ ) { CString strTemp = strMail.Mid( i, 1); strTemp.MakeLower(); int nFind = strCon.Find( strTemp ); if ( nFind == -1 ) { //没有找到 break; } strRight += strTemp; } for ( i = nPos - 1; i >= 0 ; i -- ) { CString strTemp = strMail.Mid( i, 1); strTemp.MakeLower(); int nFind = strCon.Find( strTemp ); if ( nFind == -1 ) { //没有找到 break; } strLeft = strTemp + strLeft; } CString strTemp = strLeft + "@" + strRight; return strTemp; } //==================================================== // // ../表示向上一层 // /表示根目录下的 // XX.htm表示当前目录下的 //把URL转换成绝对地址 CString OnConversionURL(CString sURL,CString str_fafURL) { if ( str_fafURL.Find(_T("http://")) >= 0 ) return str_fafURL; if(sURL.Find(_T("/"),8)<0) { sURL +=_T("/"); } CString str_activeURL; int int_j = 0; int i=0; str_activeURL = str_fafURL; if(str_fafURL.Find(_T("../"),0)!=-1&&str_fafURL[0]!=_T('/')) { while( i<=str_fafURL.GetLength() ) { if( str_fafURL[i] == '.' && str_fafURL[i+1] == '.' && str_fafURL[i+2] == _T('/') ) { int_j++;} i++; } if(str_fafURL[0]==_T('/')) { str_fafURL.Delete(0,1); } str_fafURL.Replace(_T("../"),_T("")); i=0; int int_i=0; while( i <= sURL.GetLength() ) { if( sURL[i]==_T('/') ) { int_i++; } i++; } int_i -= int_j; if( int_i<3 ) { int_i = 3; } int int_cour=0; for( i=0; i<=sURL.GetLength(); i++) { if( sURL[i]==_T('/') ) { int_cour++; } if( int_cour==int_i ) { sURL= sURL.Left(i+1); break; } } //容错处理 if( sURL[sURL.GetLength()-1]!=_T('/') ) { sURL +=_T("/"); } sURL += str_fafURL; return sURL; } else { if( str_fafURL[0] ==_T('/') ) { int int_b = 0 ; for( int a=0; int_b<3 && a<sURL.GetLength(); a++) { if( sURL[a]==_T('/') ) { int_b++; } if( int_b==3 ) { sURL = sURL.Left(a); break; } } sURL += str_fafURL; } else { for( int i = sURL.GetLength() ; i > 0 ; i -- ) { if( sURL[i - 1] ==_T('/') ) { sURL = sURL.Left( i ); break; } } sURL += str_fafURL; } return sURL; } }
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 899 ] ] ]
5e41bce80248053e82bb3b95c2386a00eb2c50d3
c238f3867d4b352ed99f4c7b9c9bea6eca01f63d
/foliage/foliage/leaf_graphic/instancizator.cpp
031aa703406511b92d437fb600ca6dd4b4ff9b6c
[]
no_license
mguillemot/kamaku.sg15
f34197677e6ebf6105435d927929e4dd24d6005d
0eb6ce1068f8198e01e25483f0cbc14e522c54a4
refs/heads/master
2021-01-01T19:42:52.583481
2007-09-20T13:19:35
2007-09-20T13:19:35
2,226,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
cpp
#include <iostream> #include "graphic_types.hpp" #include "instancizator.hpp" #include "colors.hpp" #ifdef __PPC__ #include <ivga.h> #endif Sint32 Foliage::Instancizator::_next_free_instance = 0; Foliage::Surface* Foliage::Instancizator::_instances[INSTANCIZATOR_MAX]; void Foliage::Instancizator::instancize(Foliage::Surface *surf) { if (_next_free_instance < INSTANCIZATOR_MAX) { //TODO: YOKO mode support const Foliage::Size size = surf->getSize(); Color *pixels = surf->getPixels(); for (Sint32 i = 0; i < 16; i++) { for (Sint32 j = 15; j >= 0; j--) { if (i < size.w && (15 - j) < size.h) { ivga_write_sprite_data(_next_free_instance, 15 - j, i, *pixels); pixels++; } else { ivga_write_sprite_data(_next_free_instance, 15 - j, i, Foliage::Colors::Transparent); } } } _instances[_next_free_instance] = surf; surf->setInstancized(_next_free_instance); _next_free_instance++; } else { std::cout << "Impossible to instancize more surfaces." << std::endl; } }
[ "erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf" ]
[ [ [ 1, 43 ] ] ]
33e28115ca60fdab6f940f49e8cd70db9c9ea331
3d7d8969d540b99a1e53e00c8690e32e4d155749
/AppInc/TextureLoader.h
cd1ee34db6b666ca0c240fcb903ba986bc28a20d
[]
no_license
SymbianSource/oss.FCL.sf.incubator.photobrowser
50c4ea7142102068f33fc62e36baab9d14f348f9
818b5857895d2153c4cdd653eb0e10ba6477316f
refs/heads/master
2021-01-11T02:45:51.269916
2010-10-15T01:18:29
2010-10-15T01:18:29
70,931,013
0
0
null
null
null
null
UTF-8
C++
false
false
3,911
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: Juha Kauppinen, Mika Hokkanen * * Description: Photo Browser * */ #ifndef IMAGIC_TEXTURE_LOADER_H #define IMAGIC_TEXTURE_LOADER_H // INCLUDES #include "ImagicViewBrowser.h" #include "ImagicContainerBrowser.h" #include <BitmapTransforms.h> // FORWARD DECLARATIONS class CImagicViewBrowser; class CImagicAppUi; /*enum TTextureLoaderStatus { EIdle = 0, EScaling = 1, EDecoding = 2, ECreateSmileTex = 3, };*/ class CTextureLoader : public CActive { public: // Constructor and destructor void ConstructL(); CTextureLoader(CImagicAppUi* aImagicAppUi, CImagicContainerBrowser* aContainer, CImagicViewBrowser* aView, RCriticalSection* aDrawLock); ~CTextureLoader(); // Tells if loader is running at the moment inline const TBool IsRunning(void) const { return (iData!=NULL); } // Loads picture and stores the OpenGL index into specified variable void LoadL(CImageData* aData, TThumbSize aResolution); // Unloads picture from specified index void ReleaseSuperHResTexture(CImageData* aGridData); void ReleaseHQ512Textures(); void UnloadLQ512Tex(CImageData* aData) const; void UnloadLQ128Tex(CImageData* aData) const; void UnloadLQ32Tex(CImageData* aData) const; // Called when image is loaded void ImageLoadedL(TInt aError, CFbsBitmap* aBitmap, TInt aGLMaxRes); // Creates OpenGL texture of given bitmap static TInt CreateTexture(CFbsBitmap* aBitmap, TBool aHighQuality); void CreateIconTextures(/*RArray<CFbsBitmap*> aBitmapArray*/); void LoadIcons(); //void LoadAnimation(); TBool IsActiveAndRunning(); void GetPngL(TFileName& afilepath, CFbsBitmap* aBitmap); private: // Active object interface void RunL(); void DoCancel(); void RunError(); void CreateThumbnailTexture(CFbsBitmap* aBitmap); private: // Scales given value to power of two TInt ScaleDown(TInt aSize); TBool IsScalingNeeded(TSize aImageSize); private: CImagicViewBrowser* iView; // Pointer to view RCriticalSection* iDrawLock; // Drawing mutex CImagicContainerBrowser* iContainer; // Container class CFbsBitmap* iBitmap; // Bitmap for scaled picture CFbsBitmap* iSmileBitmap; // Bitmap for scaled picture CFbsBitmap* iZoomBitmap; // Bitmap for scaled picture RArray<CFbsBitmap*> iBitmapArray; // Bitmap for scaled picture CBitmapScaler* iBitmapScaler; // Bitmap scaler object CImageDecoder* iImageDecoder; CImageData* iData; // Pointer to one grid data TBool iHighQuality; // Is image supposed to be high quality TUint iNewIndex; // Texture index CImageData* iPreviousData; // Texture index TBool iCreateAnimation; GLuint iSmileTexIndex; RArray<GLuint> iIconTextureIndexes; TSize iImageSize; TBool iScalingNeeded; CImagicAppUi* iImagicAppUi; TInt iGLMaxRes; TThumbSize iResolution; TBool iClearCurrentLoading; TBool iRGB2BGRDone; }; #endif // IMAGIC_TEXTURE_LOADER_H
[ "none@none" ]
[ [ [ 1, 118 ] ] ]
2466140a1d196facaef870b56cd7acd708f628b3
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/UnexpectedEOFException.hpp
491677cbbd4f40839837340dd28d40a4d8558aa3
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,022
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * 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. */ /* * $Id: UnexpectedEOFException.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #if !defined(UNEXPECTEDEOFEXCEPTION_HPP) #define UNEXPECTEDEOFEXCEPTION_HPP #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLException.hpp> XERCES_CPP_NAMESPACE_BEGIN MakeXMLException(UnexpectedEOFException, XMLUTIL_EXPORT) XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 33 ] ] ]
06e23ce958d3d670f52c705afaf0897fea75c159
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/q3_ui/ui_team.cpp
94ec11c722b60ea8f8ed7ec9991407463fcfa392
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
6,234
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // // // ui_team.c // #include"ui_pch.h" #define TEAMMAIN_FRAME "menu/art/cut_frame" #define ID_JOINRED 100 #define ID_JOINBLUE 101 #define ID_JOINGAME 102 #define ID_SPECTATE 103 typedef struct { menuframework_s menu; menubitmap_s frame; menutext_s joinred; menutext_s joinblue; menutext_s joingame; menutext_s spectate; } teammain_t; static teammain_t s_teammain; // bk001204 - unused //static menuframework_s s_teammain_menu; //static menuaction_s s_teammain_orders; //static menuaction_s s_teammain_voice; //static menuaction_s s_teammain_joinred; //static menuaction_s s_teammain_joinblue; //static menuaction_s s_teammain_joingame; //static menuaction_s s_teammain_spectate; /* =============== TeamMain_MenuEvent =============== */ static void TeamMain_MenuEvent( void* ptr, int event ) { if( event != QM_ACTIVATED ) { return; } switch( ((menucommon_s*)ptr)->id ) { case ID_JOINRED: _UI_trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team red\n" ); UI_ForceMenuOff(); break; case ID_JOINBLUE: _UI_trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team blue\n" ); UI_ForceMenuOff(); break; case ID_JOINGAME: _UI_trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team free\n" ); UI_ForceMenuOff(); break; case ID_SPECTATE: _UI_trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team spectator\n" ); UI_ForceMenuOff(); break; } } /* =============== TeamMain_MenuInit =============== */ void TeamMain_MenuInit( void ) { int y; int gametype; char info[MAX_INFO_STRING]; memset( &s_teammain, 0, sizeof(s_teammain) ); TeamMain_Cache(); s_teammain.menu.wrapAround = qtrue; s_teammain.menu.fullscreen = qfalse; s_teammain.frame.generic.type = MTYPE_BITMAP; s_teammain.frame.generic.flags = QMF_INACTIVE; s_teammain.frame.generic.name = TEAMMAIN_FRAME; s_teammain.frame.generic.x = 142; s_teammain.frame.generic.y = 118; s_teammain.frame.width = 359; s_teammain.frame.height = 256; y = 194; s_teammain.joinred.generic.type = MTYPE_PTEXT; s_teammain.joinred.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_teammain.joinred.generic.id = ID_JOINRED; s_teammain.joinred.generic.callback = TeamMain_MenuEvent; s_teammain.joinred.generic.x = 320; s_teammain.joinred.generic.y = y; s_teammain.joinred.string = strdup("JOIN RED"); s_teammain.joinred.style = UI_CENTER|UI_SMALLFONT; s_teammain.joinred.color = colorRed; y += 20; s_teammain.joinblue.generic.type = MTYPE_PTEXT; s_teammain.joinblue.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_teammain.joinblue.generic.id = ID_JOINBLUE; s_teammain.joinblue.generic.callback = TeamMain_MenuEvent; s_teammain.joinblue.generic.x = 320; s_teammain.joinblue.generic.y = y; s_teammain.joinblue.string = strdup("JOIN BLUE"); s_teammain.joinblue.style = UI_CENTER|UI_SMALLFONT; s_teammain.joinblue.color = colorRed; y += 20; s_teammain.joingame.generic.type = MTYPE_PTEXT; s_teammain.joingame.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_teammain.joingame.generic.id = ID_JOINGAME; s_teammain.joingame.generic.callback = TeamMain_MenuEvent; s_teammain.joingame.generic.x = 320; s_teammain.joingame.generic.y = y; s_teammain.joingame.string = strdup("JOIN GAME"); s_teammain.joingame.style = UI_CENTER|UI_SMALLFONT; s_teammain.joingame.color = colorRed; y += 20; s_teammain.spectate.generic.type = MTYPE_PTEXT; s_teammain.spectate.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_teammain.spectate.generic.id = ID_SPECTATE; s_teammain.spectate.generic.callback = TeamMain_MenuEvent; s_teammain.spectate.generic.x = 320; s_teammain.spectate.generic.y = y; s_teammain.spectate.string = strdup("SPECTATE"); s_teammain.spectate.style = UI_CENTER|UI_SMALLFONT; s_teammain.spectate.color = colorRed; y += 20; _UI_trap_GetConfigString(CS_SERVERINFO, info, MAX_INFO_STRING); gametype = atoi( Info_ValueForKey( info,"g_gametype" ) ); // set initial states switch( gametype ) { case GT_SINGLE_PLAYER: case GT_FFA: case GT_TOURNAMENT: s_teammain.joinred.generic.flags |= QMF_GRAYED; s_teammain.joinblue.generic.flags |= QMF_GRAYED; break; default: case GT_TEAM: case GT_CTF: s_teammain.joingame.generic.flags |= QMF_GRAYED; break; } Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.frame ); Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joinred ); Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joinblue ); Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joingame ); Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.spectate ); } /* =============== TeamMain_Cache =============== */ void TeamMain_Cache( void ) { _UI_trap_R_RegisterShaderNoMip( TEAMMAIN_FRAME ); } /* =============== UI_TeamMainMenu =============== */ void UI_TeamMainMenu( void ) { TeamMain_MenuInit(); UI_PushMenu ( &s_teammain.menu ); }
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac", "crioux@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 126 ], [ 128, 137 ], [ 139, 148 ], [ 150, 159 ], [ 161, 210 ] ], [ [ 127, 127 ], [ 138, 138 ], [ 149, 149 ], [ 160, 160 ] ] ]
f5abb79820419741c670d3904c8bdfd55be46d70
55196303f36aa20da255031a8f115b6af83e7d11
/private/bikini/flash/header.hpp
a988e55d522f8d9d37c4fd90dca381706b40dd0d
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
875
hpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008-2010 Viktor Reutskyy [email protected] *//*---------------------------------------------------------------------------------------------*/ #pragma once #include <bikini/flash.hpp> // GameSWF #include <gameswf/gameswf.h> #include <base/tu_file.h> #include <gameswf/gameswf_player.h> #include <gameswf/gameswf_movie_def.h> // GameSWF requires these libs #pragma comment(lib, "gameswf ("_PLATFORM_"!"_CONFIGURATION_")") #pragma comment(lib, "zlib ("_PLATFORM_"!"_CONFIGURATION_")") #pragma comment(lib, "jpeg ("_PLATFORM_"!"_CONFIGURATION_")") #pragma comment(lib, "png ("_PLATFORM_"!"_CONFIGURATION_")") #pragma comment(lib, "ws2_32") #pragma comment(lib, "winmm")
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 25 ] ] ]
82eb840f2ce3d1d2965ff71a173d69df43ae79de
a31e04e907e1d6a8b24d84274d4dd753b40876d0
/MortScript/DlgBigMessage.cpp
fed36869ad01c3be80ef98b985038ecfa518a70e
[]
no_license
RushSolutions/jscripts
23c7d6a82046dafbba3c4e060ebe3663821b3722
869cc681f88e1b858942161d9d35f4fbfedcfd6d
refs/heads/master
2021-01-10T15:31:24.018830
2010-02-26T07:41:17
2010-02-26T07:41:17
47,889,373
0
0
null
null
null
null
UTF-8
C++
false
false
3,508
cpp
// DlgBigMessage.cpp : implementation file // #include "stdafx.h" #include "MortScriptApp.h" #include "DlgBigMessage.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern HFONT MsgFont; ///////////////////////////////////////////////////////////////////////////// // CDlgBigMessage dialog CDlgBigMessage::CDlgBigMessage(CWnd* pParent /*=NULL*/) : CDialog(CDlgBigMessage::IDD, pParent) { //{{AFX_DATA_INIT(CDlgBigMessage) m_Text = _T(""); //}}AFX_DATA_INIT } void CDlgBigMessage::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgBigMessage) //DDX_Text(pDX, IDC_LABEL_SCROLL, m_Text); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgBigMessage, CDialog) //{{AFX_MSG_MAP(CDlgBigMessage) ON_WM_SIZE() ON_WM_CTLCOLOR() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgBigMessage message handlers BOOL CDlgBigMessage::OnInitDialog() { CDialog::OnInitDialog(); SetWindowText( Title ); ((CEdit*)GetDlgItem(IDC_LABEL_SCROLL))->SetWindowText( m_Text ); ((CEdit*)GetDlgItem(IDC_LABEL_SCROLL))->SetSel(0,0,FALSE); #ifndef DESKTOP m_wndCommandBar.m_bShowSharedNewButton = FALSE; m_wndCommandBar.Create(this); CString ok = L"OK"; //GetTranslation( okLabel ); TCHAR texts[MAX_PATH]; wcscpy( texts, ok ); texts[ok.GetLength()] = '\0'; texts[ok.GetLength()+1] = '\0'; int idx = m_wndCommandBar.SendMessage(TB_ADDSTRING, 0, (LPARAM)texts ); TBBUTTON tbbi[1]; tbbi[0].idCommand = IDOK; tbbi[0].fsState = TBSTATE_ENABLED; tbbi[0].fsStyle = TBSTYLE_BUTTON|TBSTYLE_AUTOSIZE; tbbi[0].dwData = 0; tbbi[0].iBitmap = -2; tbbi[0].iString = idx; m_wndCommandBar.SendMessage(TB_ADDBUTTONS, 1, (LPARAM)&tbbi); #endif if ( MsgFont != NULL ) GetDlgItem(IDC_LABEL_SCROLL)->SetFont( CFont::FromHandle( MsgFont ) ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgBigMessage::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); int res = (cx>320)?2:1; RECT rect; if ( GetDlgItem( IDOK ) != NULL && IsWindow(GetDlgItem( IDOK )->m_hWnd) ) { GetDlgItem( IDOK )->GetWindowRect( &rect ); ScreenToClient( &rect ); int okheight = rect.bottom-rect.top; int okwidth = rect.right-rect.left; rect.bottom = cy-res*2; rect.top = cy-res*2-okheight; rect.left = (cx-okwidth)/2; rect.right = cx-rect.left; GetDlgItem( IDOK )->MoveWindow( &rect ); #ifndef DESKTOP GetDlgItem( IDC_LABEL_SCROLL )->SetWindowPos( &wndTop, res*2, res*2, cx-res*4, cy-res*4, SWP_SHOWWINDOW ); #else GetDlgItem( IDC_LABEL_SCROLL )->MoveWindow( res*2, res*2, cx-res*4, cy-res*8-okheight ); #endif ((CEdit*)GetDlgItem(IDC_LABEL_SCROLL))->SetSel(0,0,FALSE); } } HBRUSH CDlgBigMessage::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if( pWnd->GetDlgCtrlID() == IDC_LABEL_SCROLL ) { pDC->SetTextColor( 0x000000 ); pDC->SetBkMode(TRANSPARENT); #ifndef DESKTOP hbr=GetSysColorBrush(COLOR_STATIC); #else hbr=GetSysColorBrush(COLOR_BTNFACE); #endif } // TODO: Return a different brush if the default is not desired return hbr; }
[ "frezgo@c2805876-21d7-11df-8c35-9da929d3dec4" ]
[ [ [ 1, 131 ] ] ]
adb1766785d28657aa8cbfd0babd33c7b50621b6
2bdc85da8ec860be41ad14fceecedef1a8efc269
/TestCode/source/TestList.cpp
cd341b718dda2c50dbb433debc245eda4fd7d94d
[]
no_license
BackupTheBerlios/pythonwrapper-svn
5c41a03b23690c62693c7b29e81b240ee24f1a7f
42879461c7302755f3c803cd1314e8da5a202c68
refs/heads/master
2016-09-05T09:53:14.554795
2005-12-26T07:52:41
2005-12-26T07:52:41
40,751,088
0
0
null
null
null
null
UTF-8
C++
false
false
10,690
cpp
#include "TestList.h" #include "PWHandler.h" CPPUNIT_TEST_SUITE_REGISTRATION(TestList); void TestList::testCopyConstructor() { List l; int count = l.getRefCount(); int noneCount = Py_None->ob_refcnt; List l1(l); CPPUNIT_ASSERT_EQUAL(count+1, l.getRefCount()); CPPUNIT_ASSERT_EQUAL(count+1, l1.getRefCount()); CPPUNIT_ASSERT_EQUAL(noneCount, Py_None->ob_refcnt); } void TestList::setUp() { mObjList = new PyObject *[8]; mObjList[0] = PyInt_FromLong(1); mObjList[1] = PyInt_FromLong(2); mObjList[2] = PyInt_FromLong(3); mObjList[3] = PyInt_FromLong(4); mObjList[4] = PyInt_FromLong(5); mObjList[5] = PyString_FromString("six"); mObjList[6] = PyString_FromString("seven"); mObjList[7] = PyString_FromString("eight"); mList = new List(); mList->append(NewReference(mObjList[0])); mList->append(NewReference(mObjList[1])); mList->append(NewReference(mObjList[2])); mList->append(NewReference(mObjList[3])); mList->append(NewReference(mObjList[4])); mList->append(NewReference(mObjList[5])); mList->append(NewReference(mObjList[6])); mList->append(NewReference(mObjList[7])); } void TestList::tearDown() { delete [] mObjList; delete mList; CPPUNIT_ASSERT(! PyErr_Occurred()); } void TestList::testConstructorThrow() { BorrowedReference br(Py_None); List l(br); } void TestList::testAssignThrow() { *mList = Object(); } void TestList::testLength() { CPPUNIT_ASSERT_EQUAL(8, mList->length()); mList->delItem(0); CPPUNIT_ASSERT_EQUAL(7, mList->length()); } void TestList::testConstructorCleanup() { PyObject *str = PyString_FromString("test"); CPPUNIT_ASSERT_EQUAL(1, str->ob_refcnt); BorrowedReference n(str); CPPUNIT_ASSERT_EQUAL(2, str->ob_refcnt); try { List l(n); CPPUNIT_ASSERT_MESSAGE("Tuple constructor should have failed with str parameter", false); } catch (Exception &) { CPPUNIT_ASSERT_EQUAL(1, str->ob_refcnt); } CPPUNIT_ASSERT_EQUAL(1, str->ob_refcnt); Py_DECREF(str); } void TestList::testGetItem() { CPPUNIT_ASSERT(mObjList[0] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[1] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[2] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(5).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(6).borrowReference()); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(7).borrowReference()); } void TestList::testSetItem() { mList->setItem(0, BorrowedReference(mObjList[7])); mList->setItem(1, BorrowedReference(mObjList[6])); mList->setItem(2, BorrowedReference(mObjList[5])); mList->setItem(3, BorrowedReference(mObjList[4])); mList->setItem(4, BorrowedReference(mObjList[3])); mList->setItem(5, BorrowedReference(mObjList[2])); mList->setItem(6, BorrowedReference(mObjList[1])); mList->setItem(7, BorrowedReference(mObjList[0])); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[2] == mList->getItem(5).borrowReference()); CPPUNIT_ASSERT(mObjList[1] == mList->getItem(6).borrowReference()); CPPUNIT_ASSERT(mObjList[0] == mList->getItem(7).borrowReference()); } void TestList::testDelItem() { mList->delItem(0); CPPUNIT_ASSERT_EQUAL(7, mList->length()); mList->delItem(6); CPPUNIT_ASSERT_EQUAL(6, mList->length()); CPPUNIT_ASSERT(mObjList[1] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[2] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(5).borrowReference()); mList->delItem(3); CPPUNIT_ASSERT_EQUAL(5, mList->length()); CPPUNIT_ASSERT(mObjList[1] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[2] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(4).borrowReference()); } void TestList::testGetSlice() { mList->delSlice(1, 3); CPPUNIT_ASSERT(mObjList[0] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(5).borrowReference()); } void TestList::testSetSlice() { PyObject *o9 = PyInt_FromLong(9), *o10 = PyInt_FromLong(10), *o11 = PyInt_FromLong(11); List l; l.append(NewReference(o9)); l.append(NewReference(o10)); l.append(NewReference(o11)); mList->setSlice(1, 3, l); CPPUNIT_ASSERT(mObjList[0] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(o9 == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(o10 == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(o11 == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(5).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(6).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(7).borrowReference()); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(8).borrowReference()); } void TestList::testDelSlice() { mList->delSlice(1, 4); CPPUNIT_ASSERT(mObjList[0] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(4).borrowReference()); } void TestList::testAppend() { PyObject *o8 = PyInt_FromLong(9), *o9 = PyInt_FromLong(10), *o10 = PyInt_FromLong(11); mList->append(NewReference(o8)); mList->append(NewReference(o9)); mList->append(NewReference(o10)); CPPUNIT_ASSERT(mObjList[0] == mList->getItem(0).borrowReference()); CPPUNIT_ASSERT(mObjList[1] == mList->getItem(1).borrowReference()); CPPUNIT_ASSERT(mObjList[2] == mList->getItem(2).borrowReference()); CPPUNIT_ASSERT(mObjList[3] == mList->getItem(3).borrowReference()); CPPUNIT_ASSERT(mObjList[4] == mList->getItem(4).borrowReference()); CPPUNIT_ASSERT(mObjList[5] == mList->getItem(5).borrowReference()); CPPUNIT_ASSERT(mObjList[6] == mList->getItem(6).borrowReference()); CPPUNIT_ASSERT(mObjList[7] == mList->getItem(7).borrowReference()); CPPUNIT_ASSERT(o8 == mList->getItem(8).borrowReference()); CPPUNIT_ASSERT(o9 == mList->getItem(9).borrowReference()); CPPUNIT_ASSERT(o10 == mList->getItem(10).borrowReference()); } void TestList::testOperatorGet() { CPPUNIT_ASSERT((*mList)[0].borrowReference() == mObjList[0]); CPPUNIT_ASSERT((*mList)[1].borrowReference() == mObjList[1]); CPPUNIT_ASSERT((*mList)[2].borrowReference() == mObjList[2]); CPPUNIT_ASSERT((*mList)[3].borrowReference() == mObjList[3]); CPPUNIT_ASSERT((*mList)[4].borrowReference() == mObjList[4]); CPPUNIT_ASSERT((*mList)[5].borrowReference() == mObjList[5]); CPPUNIT_ASSERT((*mList)[6].borrowReference() == mObjList[6]); CPPUNIT_ASSERT((*mList)[7].borrowReference() == mObjList[7]); } void TestList::testOperatorSet() { (*mList)[0] = BorrowedReference(mObjList[7]); (*mList)[1] = BorrowedReference(mObjList[6]); (*mList)[2] = BorrowedReference(mObjList[5]); (*mList)[3] = BorrowedReference(mObjList[4]); (*mList)[4] = BorrowedReference(mObjList[3]); (*mList)[5] = BorrowedReference(mObjList[2]); (*mList)[6] = BorrowedReference(mObjList[1]); (*mList)[7] = BorrowedReference(mObjList[0]); CPPUNIT_ASSERT((*mList)[0].borrowReference() == mObjList[7]); CPPUNIT_ASSERT((*mList)[1].borrowReference() == mObjList[6]); CPPUNIT_ASSERT((*mList)[2].borrowReference() == mObjList[5]); CPPUNIT_ASSERT((*mList)[3].borrowReference() == mObjList[4]); CPPUNIT_ASSERT((*mList)[4].borrowReference() == mObjList[3]); CPPUNIT_ASSERT((*mList)[5].borrowReference() == mObjList[2]); CPPUNIT_ASSERT((*mList)[6].borrowReference() == mObjList[1]); CPPUNIT_ASSERT((*mList)[7].borrowReference() == mObjList[0]); } void TestList::testReverse() { mList->reverse(); CPPUNIT_ASSERT((*mList)[0].borrowReference() == mObjList[7]); CPPUNIT_ASSERT((*mList)[1].borrowReference() == mObjList[6]); CPPUNIT_ASSERT((*mList)[2].borrowReference() == mObjList[5]); CPPUNIT_ASSERT((*mList)[3].borrowReference() == mObjList[4]); CPPUNIT_ASSERT((*mList)[4].borrowReference() == mObjList[3]); CPPUNIT_ASSERT((*mList)[5].borrowReference() == mObjList[2]); CPPUNIT_ASSERT((*mList)[6].borrowReference() == mObjList[1]); CPPUNIT_ASSERT((*mList)[7].borrowReference() == mObjList[0]); } void TestList::testSort() { mList->sort(); CPPUNIT_ASSERT((*mList)[0].borrowReference() == mObjList[0]); CPPUNIT_ASSERT((*mList)[1].borrowReference() == mObjList[1]); CPPUNIT_ASSERT((*mList)[2].borrowReference() == mObjList[2]); CPPUNIT_ASSERT((*mList)[3].borrowReference() == mObjList[3]); CPPUNIT_ASSERT((*mList)[4].borrowReference() == mObjList[4]); CPPUNIT_ASSERT((*mList)[7].borrowReference() == mObjList[5]); CPPUNIT_ASSERT((*mList)[6].borrowReference() == mObjList[6]); CPPUNIT_ASSERT((*mList)[5].borrowReference() == mObjList[7]); }
[ "cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e" ]
[ [ [ 1, 290 ] ] ]
bf38703760315f530d8b41e042195c1fe5266ea4
6db50bfe9697eaff64ffafeb1507b353d3d25ccc
/pttTestMAPI/MAPIEx/MAPIMessage.cpp
05d410a8b408b34b9f3f57bf91c1fc8841228b06
[]
no_license
PiRSquared17/jkfiledownload
181947c230a3aa8e1f2161a200a2d5b606c8606e
29eacfdacd5e3dca4a7d8d3651e34478a2206612
refs/heads/master
2021-01-22T05:50:44.680259
2011-06-10T14:54:48
2011-06-10T14:54:48
32,191,348
0
0
null
null
null
null
UTF-8
C++
false
false
15,118
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////// // // File: MAPIMessage.cpp // Description: MAPI Message class wrapper // // Copyright (C) 2005-2010, Noel Dillabough // // This source code is free to use and modify provided this notice remains intact and that any enhancements // or bug fixes are posted to the CodeProject page hosting this class for the community to benefit. // // Usage: see the CodeProject article at http://www.codeproject.com/internet/CMapiEx.asp // //////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "MAPIExPCH.h" #include "MAPIEx.h" ///////////////////////////////////////////////////////////// // CMAPIMessage CMAPIMessage::CMAPIMessage() { m_pRecipients=NULL; } CMAPIMessage::~CMAPIMessage() { Close(); } BOOL CMAPIMessage::Open(CMAPIEx* pMAPI, SBinary entryID) { if(!CMAPIObject::Open(pMAPI,entryID)) return FALSE; GetPropertyString(PR_SENDER_NAME, m_strSenderName); FillSenderEmail(); GetPropertyString(PR_SUBJECT, m_strSubject); return TRUE; } void CMAPIMessage::Close() { RELEASE(m_pRecipients); CMAPIObject::Close(); } BOOL CMAPIMessage::GetHeader(CString& strHeader) { return GetPropertyString(PR_TRANSPORT_MESSAGE_HEADERS, strHeader); } void CMAPIMessage::FillSenderEmail() { CString strAddrType; GetPropertyString(PR_SENDER_ADDRTYPE, strAddrType); GetPropertyString(PR_SENDER_EMAIL_ADDRESS, m_strSenderEmail); // for Microsoft Exchange server internal mails we want to try to resolve the SMTP email address if(strAddrType==_T("EX")) { LPSPropValue pProp; if(GetProperty(PR_SENDER_ENTRYID, pProp)==S_OK) { if(m_pMAPI) m_pMAPI->GetExEmail(pProp->Value.bin, m_strSenderEmail); MAPIFreeBuffer(pProp); } } } BOOL CMAPIMessage::GetReceivedTime(SYSTEMTIME& tmReceived) { LPSPropValue pProp; if(GetProperty(PR_MESSAGE_DELIVERY_TIME, pProp)==S_OK) { FILETIME tmLocal; FileTimeToLocalFileTime(&pProp->Value.ft, &tmLocal); FileTimeToSystemTime(&tmLocal, &tmReceived); MAPIFreeBuffer(pProp); return TRUE; } return FALSE; } BOOL CMAPIMessage::GetReceivedTime(CString& strReceivedTime, LPCTSTR szFormat) { SYSTEMTIME tm; if(GetReceivedTime(tm)) { TCHAR szTime[256]; if(!szFormat) szFormat=_T("MM/dd/yyyy hh:mm:ss tt"); GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, &tm, szFormat, szTime, 256); GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, &tm, szTime, szTime, 256); strReceivedTime=szTime; return TRUE; } return FALSE; } BOOL CMAPIMessage::GetSubmitTime(SYSTEMTIME& tmSubmit) { LPSPropValue pProp; if(GetProperty(PR_CLIENT_SUBMIT_TIME, pProp)==S_OK) { FILETIME tmLocal; FileTimeToLocalFileTime(&pProp->Value.ft, &tmLocal); FileTimeToSystemTime(&tmLocal, &tmSubmit); MAPIFreeBuffer(pProp); return TRUE; } return FALSE; } BOOL CMAPIMessage::GetSubmitTime(CString& strSubmitTime, LPCTSTR szFormat) { SYSTEMTIME tm; if(GetSubmitTime(tm)) { TCHAR szTime[256]; if(!szFormat) szFormat=_T("MM/dd/yyyy hh:mm:ss tt"); GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, &tm, szFormat, szTime,256); GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, &tm, szTime, szTime,256); strSubmitTime=szTime; return TRUE; } return FALSE; } BOOL CMAPIMessage::GetTo(CString& strTo) { return GetPropertyString(PR_DISPLAY_TO, strTo); } BOOL CMAPIMessage::GetCC(CString& strCC) { return GetPropertyString(PR_DISPLAY_CC, strCC); } BOOL CMAPIMessage::GetBCC(CString& strBCC) { return GetPropertyString(PR_DISPLAY_BCC, strBCC); } int CMAPIMessage::GetSensitivity() { return GetPropertyValue(PR_SENSITIVITY, -1); } int CMAPIMessage::GetMessageStatus() { return GetPropertyValue(PR_MSG_STATUS, 0); } int CMAPIMessage::GetPriority() { return GetPropertyValue(PR_PRIORITY, PRIO_NONURGENT); } int CMAPIMessage::GetImportance() { return GetPropertyValue(PR_IMPORTANCE, IMPORTANCE_NORMAL); } DWORD CMAPIMessage::GetSize() { return GetPropertyValue(PR_MESSAGE_SIZE, 0); } BOOL CMAPIMessage::GetRecipients() { if(!Message()) return FALSE; RELEASE(m_pRecipients); if(Message()->GetRecipientTable(CMAPIEx::cm_nMAPICode, &m_pRecipients)!=S_OK) return FALSE; const int nProperties=RECIPIENT_COLS; SizedSPropTagArray(nProperties, Columns)={nProperties,{PR_RECIPIENT_TYPE, PR_DISPLAY_NAME, PR_EMAIL_ADDRESS, PR_ADDRTYPE, PR_ENTRYID }}; return (m_pRecipients->SetColumns((LPSPropTagArray)&Columns, 0)==S_OK); } BOOL CMAPIMessage::GetNextRecipient(CString& strName, CString& strEmail, int& nType) { if(!m_pRecipients) return FALSE; LPSRowSet pRows=NULL; BOOL bResult=FALSE; if(m_pRecipients->QueryRows(1, 0, &pRows)==S_OK) { if(pRows->cRows) { nType=pRows->aRow[0].lpProps[PROP_RECIPIENT_TYPE].Value.ul; strName=CMAPIEx::GetValidString(pRows->aRow[0].lpProps[PROP_RECIPIENT_NAME]); // for Microsoft Exchange server internal mails we want to try to resolve the SMTP email address CString strAddrType=CMAPIEx::GetValidString(pRows->aRow[0].lpProps[PROP_ADDR_TYPE]); if(strAddrType==_T("EX")) { if(m_pMAPI) m_pMAPI->GetExEmail(pRows->aRow[0].lpProps[PROP_ENTRYID].Value.bin, strEmail); } else { strEmail=CMAPIEx::GetValidString(pRows->aRow[0].lpProps[PROP_RECIPIENT_EMAIL]); } bResult=TRUE; } FreeProws(pRows); MAPIFreeBuffer(pRows); } return bResult; } BOOL CMAPIMessage::GetReplyTo(CString& strEmail) { BOOL bResult=FALSE; LPSPropValue prop; if(GetProperty(PR_REPLY_RECIPIENT_ENTRIES, prop) == S_OK) { LPFLATENTRYLIST pReplyEntryList=(LPFLATENTRYLIST)prop->Value.bin.lpb; if(pReplyEntryList->cEntries>0) { LPFLATENTRY pReplyEntry=(LPFLATENTRY)pReplyEntryList->abEntries; SBinary entryID; entryID.cb=pReplyEntry->cb; entryID.lpb=pReplyEntry->abEntry; bResult=m_pMAPI->GetExEmail(entryID, strEmail); } MAPIFreeBuffer(prop); } return bResult; } // nPriority defaults to IMPORTANCE_NORMAL, IMPORTANCE_HIGH or IMPORTANCE_LOW also valid BOOL CMAPIMessage::Create(CMAPIEx* pMAPI, int nPriority, BOOL bSaveToSentFolder, CMAPIFolder* pFolder) { if(!pMAPI) return FALSE; if(!pFolder) pFolder=pMAPI->GetFolder(); if(!pFolder) pFolder=pMAPI->OpenOutbox(); if(!CMAPIObject::Create(pMAPI, pFolder)) return FALSE; SPropValue prop; SetMessageFlags(MSGFLAG_UNSENT | MSGFLAG_FROMME); LPSPropValue pProp=NULL; ULONG cValues=0; ULONG rgTags[]={ 1, PR_IPM_SENTMAIL_ENTRYID }; if(m_pMAPI->GetMessageStore()->GetProps((LPSPropTagArray) rgTags, CMAPIEx::cm_nMAPICode, &cValues, &pProp)==S_OK) { if(bSaveToSentFolder) { prop.ulPropTag=PR_SENTMAIL_ENTRYID; prop.Value.bin=pProp[0].Value.bin; } else { prop.ulPropTag=PR_DELETE_AFTER_SUBMIT; prop.Value.b=TRUE; } Message()->SetProps(1, &prop, NULL); SetEntryID(&(pProp[0].Value.bin)); MAPIFreeBuffer(pProp); } if(nPriority!=IMPORTANCE_NORMAL) { prop.ulPropTag=PR_IMPORTANCE; prop.Value.l=nPriority; Message()->SetProps(1, &prop, NULL); } #ifdef _WIN32_WCE prop.ulPropTag=PR_MESSAGE_CLASS; prop.Value.lpszW=_T("IPM.Note"); Message()->SetProps(1, &prop, NULL); prop.ulPropTag=PR_MSG_STATUS; prop.Value.ul=MSGSTATUS_RECTYPE_SMTP; Message()->SetProps(1, &prop, NULL); #endif return TRUE; } BOOL CMAPIMessage::IsUnread() { return (!(GetMessageFlags()&MSGFLAG_READ)); } BOOL CMAPIMessage::MarkAsRead(BOOL bRead) { #ifdef _WIN32_WCE int ulMessageFlags=GetMessageFlags(); if(bRead) ulMessageFlags|=MSGFLAG_READ; else ulMessageFlags&=~MSGFLAG_READ; return SetMessageFlags(ulMessageFlags); #else return (Message()->SetReadFlag(bRead ? MSGFLAG_READ : CLEAR_READ_FLAG)==S_OK); #endif } BOOL CMAPIMessage::AddRecipients(LPADRLIST pAddressList) { HRESULT hr=E_INVALIDARG; #ifdef _WIN32_WCE hr=Message()->ModifyRecipients(MODRECIP_ADD, pAddressList); #else LPADRBOOK pAddressBook; if(m_pMAPI->GetSession()->OpenAddressBook(0, NULL, AB_NO_DIALOG, &pAddressBook)!=S_OK) return FALSE; if(pAddressBook->ResolveName(0, CMAPIEx::cm_nMAPICode, NULL, pAddressList)==S_OK) hr=Message()->ModifyRecipients(MODRECIP_ADD, pAddressList); RELEASE(pAddressBook); #endif return (hr==S_OK); } // AddrType only needed by Windows CE, use SMTP, or SMS etc, default NULL will not set PR_ADDRTYPE BOOL CMAPIMessage::AddRecipient(LPCTSTR szEmail, int nType, LPCTSTR szAddrType) { if(!Message() || !m_pMAPI) return FALSE; int nBufSize=CbNewADRLIST(1); LPADRLIST pAddressList=NULL; MAPIAllocateBuffer(nBufSize, (LPVOID FAR*)&pAddressList); memset(pAddressList, 0, nBufSize); int nProperties=3; if(szAddrType==NULL) nProperties--; pAddressList->cEntries=1; pAddressList->aEntries[0].ulReserved1=0; pAddressList->aEntries[0].cValues=nProperties; MAPIAllocateBuffer(sizeof(SPropValue)*nProperties, (LPVOID FAR*)&pAddressList->aEntries[0].rgPropVals); memset(pAddressList->aEntries[0].rgPropVals, 0, sizeof(SPropValue)*nProperties); pAddressList->aEntries[0].rgPropVals[0].ulPropTag=PR_RECIPIENT_TYPE; pAddressList->aEntries[0].rgPropVals[0].Value.ul=nType; #ifdef _WIN32_WCE pAddressList->aEntries[0].rgPropVals[1].ulPropTag=PR_EMAIL_ADDRESS; pAddressList->aEntries[0].rgPropVals[1].Value.LPSZ=(TCHAR*)szEmail; #else pAddressList->aEntries[0].rgPropVals[1].ulPropTag=PR_DISPLAY_NAME; pAddressList->aEntries[0].rgPropVals[1].Value.LPSZ=(TCHAR*)szEmail; #endif if(szAddrType!=NULL) { pAddressList->aEntries[0].rgPropVals[2].ulPropTag=PR_ADDRTYPE; pAddressList->aEntries[0].rgPropVals[2].Value.LPSZ=(TCHAR*)szAddrType; } BOOL bResult=AddRecipients(pAddressList); CMAPIEx::ReleaseAddressList(pAddressList); return bResult; } void CMAPIMessage::SetSubject(LPCTSTR szSubject) { m_strSubject=szSubject; SetPropertyString(PR_SUBJECT, szSubject); } void CMAPIMessage::SetSender(LPCTSTR szSenderName, LPCTSTR szSenderEmail) { m_strSenderName=szSenderName; m_strSenderEmail=szSenderEmail; LPTSTR szAddrType=_T("SMTP"); if(m_strSenderName.GetLength() && m_strSenderEmail.GetLength()) { SetPropertyString(PR_SENDER_NAME, szSenderName); SetPropertyString(PR_SENDER_EMAIL_ADDRESS, szSenderEmail); #ifndef _WIN32_WCE LPADRBOOK pAddressBook; if(m_pMAPI->GetSession()->OpenAddressBook(0, NULL, AB_NO_DIALOG, &pAddressBook)==S_OK) { SPropValue prop; if(pAddressBook->CreateOneOff((LPTSTR)szSenderName, szAddrType, (LPTSTR)szSenderEmail, 0, &prop.Value.bin.cb, (LPENTRYID*)&prop.Value.bin.lpb)==S_OK) { prop.ulPropTag=PR_SENT_REPRESENTING_ENTRYID; Message()->SetProps(1, &prop, NULL); SetPropertyString(PR_SENT_REPRESENTING_NAME, szSenderName); SetPropertyString(PR_SENT_REPRESENTING_EMAIL_ADDRESS, szSenderEmail); SetPropertyString(PR_SENT_REPRESENTING_ADDRTYPE, szAddrType); } } RELEASE(pAddressBook); #endif } } BOOL CMAPIMessage::SetReceivedTime(SYSTEMTIME tmReceived, BOOL bLocalTime) { SPropValue prop; prop.ulPropTag=PR_MESSAGE_DELIVERY_TIME; #ifndef _WIN32_WCE if(bLocalTime) TzSpecificLocalTimeToSystemTime(NULL, &tmReceived, &tmReceived); #endif SystemTimeToFileTime(&tmReceived, &prop.Value.ft); return (Message() && Message()->SetProps(1, &prop, NULL)==S_OK); } BOOL CMAPIMessage::SetSubmitTime(SYSTEMTIME tmSubmit, BOOL bLocalTime) { SPropValue prop; prop.ulPropTag=PR_CLIENT_SUBMIT_TIME; #ifndef _WIN32_WCE if(bLocalTime) TzSpecificLocalTimeToSystemTime(NULL, &tmSubmit, &tmSubmit); #endif SystemTimeToFileTime(&tmSubmit, &prop.Value.ft); return (Message() && Message()->SetProps(1, &prop, NULL)==S_OK); } // request a Read Receipt sent to szReceiverEmail BOOL CMAPIMessage::SetReadReceipt(BOOL bSet, LPCTSTR szReceiverEmail) { if(!Message()) return FALSE; SPropValue prop; prop.ulPropTag=PR_READ_RECEIPT_REQUESTED; prop.Value.b=(unsigned short)bSet; if(Message()->SetProps(1, &prop, NULL)!=S_OK) return FALSE; if(bSet && szReceiverEmail && _tcslen(szReceiverEmail)>0) SetPropertyString(PR_READ_RECEIPT_REQUESTED, szReceiverEmail); return TRUE; } BOOL CMAPIMessage::SetDeliveryReceipt(BOOL bSet) { if(!Message()) return FALSE; SPropValue prop; prop.ulPropTag=PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED; prop.Value.b=(unsigned short)bSet; return (Message()->SetProps(1, &prop, NULL)!=S_OK); } // limited compare, compares entry IDs and subject to determine if two emails are equal BOOL CMAPIMessage::operator==(CMAPIMessage& message) { if(!m_entryID.cb || !message.m_entryID.cb || m_entryID.cb!=message.m_entryID.cb) return FALSE; if(memcmp(m_entryID.lpb,message.m_entryID.lpb, m_entryID.cb)) return FALSE; return (!m_strSubject.Compare(message.m_strSubject)); } // Novell GroupWise customization by jcadmin #ifndef GROUPWISE BOOL CMAPIMessage::MarkAsPrivate() { return FALSE; } #else #include GWMAPI.h //(from Novell Developer Kit) #define SEND_OPTIONS_MARK_PRIVATE 0x00080000L void CMAPIMessage::MarkAsPrivate() { SPropValue prop; prop.ulPropTag=PR_NGW_SEND_OPTIONS; prop.Value.l=NGW_SEND_OPTIONS_MARK_PRIVATE; return (Message()->SetProps(1, &prop, NULL)==S_OK); } #endif BOOL CMAPIMessage::SetSensitivity(int nSensitivity) { SPropValue prop; prop.ulPropTag=PR_SENSITIVITY; prop.Value.l=nSensitivity; return (Message()->SetProps(1, &prop, NULL)==S_OK); } // In WinCE, use MSGSTATUS_RECTYPE_SMS for an SMS, MSGSTATUS_RECTYPE_SMTP for an email BOOL CMAPIMessage::SetMessageStatus(int nMessageStatus) { SPropValue prop; prop.ulPropTag=PR_MSG_STATUS; prop.Value.ul=nMessageStatus; return (Message()->SetProps(1, &prop, NULL)==S_OK); } // Shows the default MAPI form for IMessage, returns FALSE on failure, IDOK on success or close existing messages // and IDCANCEL on close new messages int CMAPIMessage::ShowForm(CMAPIEx* pMAPI) { CMAPIFolder* pFolder=pMAPI->GetFolder(); IMAPISession* pSession=pMAPI->GetSession(); ULONG ulMessageToken; if(pFolder && pSession && pSession->PrepareForm(NULL,Message(), &ulMessageToken)==S_OK) { ULONG ulMessageStatus=GetPropertyValue(PR_MSG_STATUS, 0); ULONG ulMessageFlags=GetMessageFlags(); ULONG ulAccess=GetPropertyValue(PR_ACCESS, 0); LPSPropValue pProp; if(GetProperty(PR_MESSAGE_CLASS, pProp)==S_OK) { #ifdef UNICODE char szMessageClass[256]; WideCharToMultiByte(CP_ACP, 0, pProp->Value.LPSZ,-1, szMessageClass,255, NULL, NULL); #else char* szMessageClass=pProp->Value.LPSZ; #endif HRESULT hr=pSession->ShowForm(NULL, pMAPI->GetMessageStore(), pFolder->Folder(), NULL,ulMessageToken, NULL, 0,ulMessageStatus,ulMessageFlags,ulAccess, szMessageClass); MAPIFreeBuffer(pProp); if(hr==S_OK) return IDOK; if(hr==MAPI_E_USER_CANCEL) return IDCANCEL; } } return FALSE; } BOOL CMAPIMessage::Send() { if(Message() && Message()->SubmitMessage(0)==S_OK) { Close(); return TRUE; } return FALSE; }
[ "jkinhsnu@409c1fd0-e2f3-11dd-9059-71fac19e68c6" ]
[ [ [ 1, 523 ] ] ]
eea43beec42f686b0acc51296a2e8fb7c6872b0f
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/extensions/sdktools/vcaller.cpp
6ea1f131f1c17eccd3ae28d84dec217fee0f01a2
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,932
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod SDKTools Extension * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include "extension.h" #include "vcallbuilder.h" #include "vglobals.h" enum SDKLibrary { SDKLibrary_Server, /**< server.dll/server_i486.so */ SDKLibrary_Engine, /**< engine.dll/engine_*.so */ }; enum SDKPassMethod { SDKPass_Pointer, /**< Pass as a pointer */ SDKPass_Plain, /**< Pass as plain data */ SDKPass_ByValue, /**< Pass an object by value */ SDKPass_ByRef, /**< Pass an object by reference */ }; int s_vtbl_index = -1; void *s_call_addr = NULL; ValveCallType s_vcalltype = ValveCall_Static; bool s_has_return = false; ValvePassInfo s_return; unsigned int s_numparams = 0; ValvePassInfo s_params[SP_MAX_EXEC_PARAMS]; inline void DecodePassMethod(ValveType vtype, SDKPassMethod method, PassType &type, unsigned int &flags) { if (method == SDKPass_Pointer || method == SDKPass_ByRef) { type = PassType_Basic; if (vtype == Valve_POD || vtype == Valve_Float || vtype == Valve_Bool) { flags = PASSFLAG_BYVAL | PASSFLAG_ASPOINTER; } else { flags = PASSFLAG_BYVAL; } } else if (method == SDKPass_Plain) { type = PassType_Basic; flags = PASSFLAG_BYVAL; } else if (method == SDKPass_ByValue) { if (vtype == Valve_Vector || vtype == Valve_QAngle) { type = PassType_Object; } else { type = PassType_Basic; } flags = PASSFLAG_BYVAL; } } static cell_t StartPrepSDKCall(IPluginContext *pContext, const cell_t *params) { s_numparams = 0; s_vtbl_index = -1; s_call_addr = NULL; s_has_return = false; s_vcalltype = (ValveCallType)params[1]; return 1; } static cell_t PrepSDKCall_SetVirtual(IPluginContext *pContext, const cell_t *params) { s_vtbl_index = params[1]; return 1; } static cell_t PrepSDKCall_SetSignature(IPluginContext *pContext, const cell_t *params) { void *addrInBase = NULL; if (params[1] == SDKLibrary_Server) { addrInBase = (void *)g_SMAPI->GetServerFactory(false); } else if (params[1] == SDKLibrary_Engine) { addrInBase = (void *)g_SMAPI->GetEngineFactory(false); } if (addrInBase == NULL) { return 0; } char *sig; pContext->LocalToString(params[2], &sig); #if defined PLATFORM_LINUX if (sig[0] == '@') { Dl_info info; if (dladdr(addrInBase, &info) == 0) { return 0; } void *handle = dlopen(info.dli_fname, RTLD_NOW); if (!handle) { return 0; } s_call_addr = dlsym(handle, &sig[1]); dlclose(handle); return (s_call_addr != NULL) ? 1 : 0; } #endif s_call_addr = memutils->FindPattern(addrInBase, sig, params[3]); return (s_call_addr != NULL) ? 1 : 0; } static cell_t PrepSDKCall_SetFromConf(IPluginContext *pContext, const cell_t *params) { IGameConfig *conf; if (params[1] == BAD_HANDLE) { conf = g_pGameConf; } else { HandleError err; if ((conf = gameconfs->ReadHandle(params[1], pContext->GetIdentity(), &err)) == NULL) { return pContext->ThrowNativeError("Invalid Handle %x (error %d)", params[1], err); } } char *key; pContext->LocalToString(params[3], &key); if (params[2] == 0) { return conf->GetOffset(key, &s_vtbl_index) ? 1 : 0; } else if (params[2] == 1) { bool result = conf->GetMemSig(key, &s_call_addr) ? 1 : 0; return (result && s_call_addr != NULL) ? 1 : 0; } return 0; } static cell_t PrepSDKCall_SetReturnInfo(IPluginContext *pContext, const cell_t *params) { s_has_return = true; s_return.vtype = (ValveType)params[1]; DecodePassMethod(s_return.vtype, (SDKPassMethod)params[2], s_return.type, s_return.flags); s_return.decflags = params[3]; s_return.encflags = params[4]; return 1; } static cell_t PrepSDKCall_AddParameter(IPluginContext *pContext, const cell_t *params) { if (s_numparams >= SP_MAX_EXEC_PARAMS) { return pContext->ThrowNativeError("Parameter limit for SDK calls reached"); } ValvePassInfo *info = &s_params[s_numparams++]; info->vtype = (ValveType)params[1]; SDKPassMethod method = (SDKPassMethod)params[2]; DecodePassMethod(info->vtype, method, info->type, info->flags); info->decflags = params[3] | VDECODE_FLAG_BYREF; info->encflags = params[4]; /* Since SDKPass_ByRef acts like SDKPass_Pointer we can't allow NULL, just in case */ if (method == SDKPass_ByRef) { info->decflags &= ~VDECODE_FLAG_ALLOWNULL; } return 1; } static cell_t EndPrepSDKCall(IPluginContext *pContext, const cell_t *params) { ValveCall *vc = NULL; if (s_vtbl_index > -1) { vc = CreateValveVCall(s_vtbl_index, s_vcalltype, s_has_return ? &s_return : NULL, s_params, s_numparams); } else if (s_call_addr) { vc = CreateValveCall(s_call_addr, s_vcalltype, s_has_return ? &s_return : NULL, s_params, s_numparams); } if (!vc) { return BAD_HANDLE; } if (vc->thisinfo) { vc->thisinfo->decflags |= VDECODE_FLAG_BYREF; } Handle_t hndl = handlesys->CreateHandle(g_CallHandle, vc, pContext->GetIdentity(), myself->GetIdentity(), NULL); if (!hndl) { delete vc; } return hndl; } static cell_t SDKCall(IPluginContext *pContext, const cell_t *params) { ValveCall *vc; HandleError err; HandleSecurity sec(pContext->GetIdentity(), myself->GetIdentity()); if ((err = handlesys->ReadHandle(params[1], g_CallHandle, &sec, (void **)&vc)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error %d)", params[1], err); } unsigned char *ptr = vc->stk_get(); unsigned int numparams = (unsigned)params[0]; unsigned int startparam = 2; /* Do we need to write a thispointer? */ if (vc->thisinfo) { switch (vc->type) { case ValveCall_Entity: case ValveCall_Player: { if (startparam > numparams) { vc->stk_put(ptr); return pContext->ThrowNativeError("Expected 1 parameter for entity pointer; found none"); } if (DecodeValveParam(pContext, params[startparam], vc, vc->thisinfo, ptr) == Data_Fail) { vc->stk_put(ptr); return 0; } startparam++; } break; case ValveCall_GameRules: { if (g_pGameRules == NULL) { vc->stk_put(ptr); return pContext->ThrowNativeError("GameRules unsupported or not available; file a bug report"); } void *gamerules = *g_pGameRules; if (gamerules == NULL) { vc->stk_put(ptr); return pContext->ThrowNativeError("GameRules not available before map is loaded"); } *(void **)ptr = gamerules; } break; case ValveCall_EntityList: { if (g_EntList == NULL) { vc->stk_put(ptr); return pContext->ThrowNativeError("EntityList unsupported or not available; file a bug report"); } *(void **)ptr = g_EntList; } break; } } /* See if we need to skip any more parameters */ unsigned int retparam = startparam; if (vc->retinfo) { if (vc->retinfo->vtype == Valve_String) { startparam += 2; } else if (vc->retinfo->vtype == Valve_Vector || vc->retinfo->vtype == Valve_QAngle) { startparam += 1; } } unsigned int callparams = vc->call->GetParamCount(); bool will_copyback = false; for (unsigned int i=0; i<callparams; i++) { unsigned int p = startparam + i; if (p > numparams) { vc->stk_put(ptr); return pContext->ThrowNativeError("Expected %dth parameter, found none", p); } if (DecodeValveParam(pContext, params[p], vc, &(vc->vparams[i]), ptr) == Data_Fail) { vc->stk_put(ptr); return 0; } if (vc->vparams[i].encflags & VENCODE_FLAG_COPYBACK) { will_copyback = true; } } /* Make the actual call */ vc->call->Execute(ptr, vc->retbuf); /* Do we need to copy anything back? */ if (will_copyback) { for (unsigned int i=0; i<callparams; i++) { if (vc->vparams[i].encflags & VENCODE_FLAG_COPYBACK) { if (EncodeValveParam(pContext, params[startparam + i], vc, &vc->vparams[i], ptr) == Data_Fail) { vc->stk_put(ptr); return 0; } } } } /* Save stack once and for all */ vc->stk_put(ptr); /* Figure out how to decode the return information */ if (vc->retinfo) { if (vc->retinfo->vtype == Valve_String) { if (numparams < 3) { return pContext->ThrowNativeError("Expected arguments (2,3) for string storage"); } cell_t *addr; size_t written; pContext->LocalToPhysAddr(params[retparam+1], &addr); pContext->StringToLocalUTF8(params[retparam], *addr, *(char **)vc->retbuf, &written); return (cell_t)written; } else if (vc->retinfo->vtype == Valve_Vector || vc->retinfo->vtype == Valve_QAngle) { if (numparams < 2) { return pContext->ThrowNativeError("Expected argument (2) for Float[3] storage"); } if (EncodeValveParam(pContext, params[retparam], vc, vc->retinfo, vc->retbuf) == Data_Fail) { return 0; } } else if (vc->retinfo->vtype == Valve_CBaseEntity || vc->retinfo->vtype == Valve_CBasePlayer) { CBaseEntity *pEntity = *(CBaseEntity **)(vc->retbuf); if (!pEntity) { return -1; } edict_t *pEdict = gameents->BaseEntityToEdict(pEntity); if (!pEdict || pEdict->IsFree()) { return -1; } return engine->IndexOfEdict(pEdict); } else if (vc->retinfo->vtype == Valve_Edict) { edict_t *pEdict = *(edict_t **)(vc->retbuf); if (!pEdict || pEdict->IsFree()) { return -1; } return engine->IndexOfEdict(pEdict); } else if (vc->retinfo->vtype == Valve_Bool) { bool *addr = (bool *)vc->retbuf; if (vc->retinfo->flags & PASSFLAG_ASPOINTER) { addr = *(bool **)addr; } return *addr ? 1 : 0; } else { cell_t *addr = (cell_t *)vc->retbuf; if (vc->retinfo->flags & PASSFLAG_ASPOINTER) { addr = *(cell_t **)addr; } return *addr; } } return 0; } sp_nativeinfo_t g_CallNatives[] = { {"StartPrepSDKCall", StartPrepSDKCall}, {"PrepSDKCall_SetVirtual", PrepSDKCall_SetVirtual}, {"PrepSDKCall_SetSignature", PrepSDKCall_SetSignature}, {"PrepSDKCall_SetFromConf", PrepSDKCall_SetFromConf}, {"PrepSDKCall_SetReturnInfo", PrepSDKCall_SetReturnInfo}, {"PrepSDKCall_AddParameter", PrepSDKCall_AddParameter}, {"EndPrepSDKCall", EndPrepSDKCall}, {"SDKCall", SDKCall}, {NULL, NULL}, };
[ [ [ 1, 2 ], [ 7, 7 ], [ 28, 31 ], [ 109, 109 ], [ 111, 111 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ], [ 34, 34 ], [ 50, 50 ], [ 60, 60 ], [ 67, 67 ], [ 89, 89 ], [ 195, 196 ], [ 200, 205 ], [ 212, 212 ], [ 255, 255 ], [ 257, 257 ], [ 259, 308 ], [ 362, 362 ], [ 426, 426 ], [ 433, 433 ] ], [ [ 4, 5 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 32, 33 ], [ 35, 49 ], [ 51, 59 ], [ 61, 66 ], [ 68, 88 ], [ 90, 108 ], [ 110, 110 ], [ 112, 194 ], [ 197, 199 ], [ 206, 211 ], [ 213, 254 ], [ 256, 256 ], [ 258, 258 ], [ 309, 361 ], [ 363, 425 ], [ 427, 432 ], [ 434, 455 ] ] ]
e4c90104b1f06b3656a1842779f0383d9504bbac
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/timesignature.cpp
a1624c2f9289cb4dfccfdc553e388f6debde7c47
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
14,773
cpp
///////////////////////////////////////////////////////////////////////////// // Name: timesignature.cpp // Purpose: Stores and renders time signatures // Author: Brad Larsen // Modified by: // Created: Dec 12, 2004 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #include "stdwx.h" #include "timesignature.h" #include <math.h> // Needed for pow() #ifdef _DEBUG #define new DEBUG_NEW #endif // Note: The MIDI_xxx duration constants found in this class are defined in generalmidi.h const wxUint32 TimeSignature::DEFAULT_DATA = 0x1a018000; const wxByte TimeSignature::DEFAULT_PULSES = 4; const wxByte TimeSignature::MIN_BEATSPERMEASURE = 1; const wxByte TimeSignature::MAX_BEATSPERMEASURE = 32; const wxByte TimeSignature::MIN_BEATAMOUNT = 2; const wxByte TimeSignature::MAX_BEATAMOUNT = 32; const wxByte TimeSignature::MIN_PULSES = 0; const wxByte TimeSignature::MAX_PULSES = 32; // Constructor/Destructor /// Default Constructor TimeSignature::TimeSignature() : m_data(DEFAULT_DATA), m_pulses(DEFAULT_PULSES) { //------Last Checked------// // - Dec 12, 2004 } /// Primary Constructor /// @param beatsPerMeasure The number of beats in a measure (numerator) /// @param beatAmount The amount given to each beat (denominator) TimeSignature::TimeSignature(wxByte beatsPerMeasure, wxByte beatAmount) : m_data(DEFAULT_DATA), m_pulses(DEFAULT_PULSES) { //------Last Checked------// // - Dec 13, 2004 SetMeter(beatsPerMeasure, beatAmount); } /// Copy Constructor TimeSignature::TimeSignature(const TimeSignature& timeSignature) { //------Last Checked------// // - Dec 12, 2004 *this = timeSignature; } /// Destructor TimeSignature::~TimeSignature() { //------Last Checked------// // - Dec 12, 2004 } // Operators /// Assignment Operator const TimeSignature& TimeSignature::operator=(const TimeSignature& timeSignature) { //------Last Checked------// // - Dec 12, 2004 // Check for assignment to self if (this != &timeSignature) { m_data = timeSignature.m_data; m_pulses = timeSignature.m_pulses; } return (*this); } /// Equality Operator bool TimeSignature::operator==(const TimeSignature& timeSignature) const { //------Last Checked------// // - Dec 10, 2004 return ( (m_data == timeSignature.m_data) && (m_pulses == timeSignature.m_pulses) ); } /// Inequality Operator bool TimeSignature::operator!=(const TimeSignature& timeSignature) const { //------Last Checked------// // - Dec 10, 2004 return (!operator==(timeSignature)); } // Serialize Functions /// Performs serialization for the class /// @param stream Power Tab output stream to serialize to /// @return True if the object was serialized, false if not bool TimeSignature::DoSerialize(PowerTabOutputStream& stream) { //------Last Checked------// // - Dec 12, 2004 stream << m_data << m_pulses; wxCHECK(stream.CheckState(), false); return (stream.CheckState()); } /// Performs deserialization for the class /// @param stream Power Tab input stream to load from /// @param version File version /// @return True if the object was deserialized, false if not bool TimeSignature::DoDeserialize(PowerTabInputStream& stream, wxWord version) { //------Last Checked------// // - Dec 12, 2004 stream >> m_data >> m_pulses; wxCHECK(stream.CheckState(), false); return (stream.CheckState()); } // Meter Functions /// Sets the meter (i.e. 2/4) /// @param beatsPerMeasure The number of beats in a measure (numerator) /// @param beatAmount The amount given to each beat (denominator) /// @return True if the meter was set, false if not bool TimeSignature::SetMeter(wxByte beatsPerMeasure, wxByte beatAmount) { //------Last Checked------// // - Dec 13, 2004 if (!SetBeatsPerMeasure(beatsPerMeasure)) return (false); if (!SetBeatAmount(beatAmount)) return (false); // Set the default beaming pattern, based on the meter's beat amount and basic beat beatAmount = GetBeatAmount(); wxUint32 basicBeat = GetBasicBeat(); // Calculate the number of 8th notes in basic beat if (beatAmount <= 8) { // 4/4 Time, group in 4s if ((beatAmount == 4) && (GetBeatsPerMeasure() == 4)) SetBeamingPattern(4); else SetBeamingPattern((wxByte)(basicBeat / (MIDI_PPQN / 2))); } // Calculate the number of 16th notes in basic beat else if (beatAmount == 16) SetBeamingPattern((wxByte)(basicBeat / (MIDI_PPQN / 4))); // Calculate the number of 32nd notes in basic beat else if (beatAmount == 32) SetBeamingPattern((wxByte)(basicBeat / (MIDI_PPQN / 8))); // Set the default pulses SetPulses((wxByte)(GetMeasureTotal() / basicBeat)); return (true); } /// Gets the meter (i.e. 2/4) /// @param beatsPerMeasure The number of beats in a measure (numerator) /// @param beatAmount The amount given to each beat (denominator) void TimeSignature::GetMeter(wxByte& beatsPerMeasure, wxByte& beatAmount) const { //------Last Checked------// // - Dec 12, 2004 beatsPerMeasure = GetBeatsPerMeasure(); beatAmount = GetBeatAmount(); } /// Determines if the meter is compound time /// @return True if the meter is compound time, false if not bool TimeSignature::IsCompoundTime() const { //------Last Checked------// // - Dec 12, 2004 wxByte beatsPerMeasure, beatAmount; GetMeter(beatsPerMeasure, beatAmount); return (((beatsPerMeasure % 3) == 0) && (beatsPerMeasure != 3)); } /// Determines if the meter is quadruple time /// @return True if the meter is quadruple time, false if not bool TimeSignature::IsQuadrupleTime() const { //------Last Checked------// // - Dec 12, 2004 wxByte beatsPerMeasure, beatAmount; GetMeter(beatsPerMeasure, beatAmount); return ((beatsPerMeasure == 4) || (beatsPerMeasure == 12)); } /// Gets the total time for a measure that uses the time signature, in MIDI units /// @returns The total time for a measure that uses the time signature, in MIDI units wxUint32 TimeSignature::GetMeasureTotal() const { //------Last Checked------// // - Dec 12, 2004 return (((MIDI_PPQN * 4) / GetBeatAmount()) * GetBeatsPerMeasure()); } /// Gets the basic beat value for the time signature /// @return The basic beat value for the time signature, in MIDI units wxUint32 TimeSignature::GetBasicBeat() const { //------Last Checked------// // - Dec 12, 2004 // Compound time = dotted beat if (IsCompoundTime()) return ((MIDI_PPQN * 4) * 3 / GetBeatAmount()); return ((MIDI_PPQN * 4) / GetBeatAmount()); } // Beats Per Measure Functions /// Sets the beats per measure (numerator) /// @param beatsPerMeasure The beats per measure to set /// @return True if the beats per measure was set, false if not bool TimeSignature::SetBeatsPerMeasure(wxByte beatsPerMeasure) { //------Last Checked------// // - Dec 13, 2004 wxCHECK(IsValidBeatsPerMeasure(beatsPerMeasure), false); // Automatically clear the common and cut time flags ClearFlag(commonTime | cutTime); // Beats per measure are zero-based in storage beatsPerMeasure--; m_data &= ~beatsPerMeasureMask; m_data |= (beatsPerMeasure << 27); return (true); } /// Gets the time signature's beats per measure value (numerator) /// @return The time signature's beats per measure value wxByte TimeSignature::GetBeatsPerMeasure() const { //------Last Checked------// // - Dec 12, 2004 // Common Time if (IsCommonTime()) return (4); // Cut Time else if (IsCutTime()) return (2); // beatsPerMeasure is stored in zero-based format, so add one wxByte beatsPerMeasure = (wxByte)((m_data & beatsPerMeasureMask) >> 27); beatsPerMeasure++; return (beatsPerMeasure); } // Beat Amount Functions /// Sets the beat amount /// @param beatAmount Beat amount to set /// @return True if the beat amount was set, false if not bool TimeSignature::SetBeatAmount(wxByte beatAmount) { //------Last Checked------// // - Dec 13, 2004 wxCHECK(IsValidBeatAmount(beatAmount), false); // Automatically clear the common and cut time flags ClearFlag(commonTime | cutTime); // The beat amount is stored in power of 2 form if (beatAmount == 2) beatAmount = 1; else if (beatAmount == 4) beatAmount = 2; else if (beatAmount == 8) beatAmount = 3; else if (beatAmount == 16) beatAmount = 4; else if (beatAmount == 32) beatAmount = 5; m_data &= ~beatAmountMask; m_data |= (beatAmount << 24); return (true); } /// Gets the time signature's beat amount (denominator) /// @return The time signature's beat amount wxByte TimeSignature::GetBeatAmount() const { //------Last Checked------// // - Dec 13, 2004 // Common Time if (IsCommonTime()) return (4); // Cut Time else if (IsCutTime()) return (2); // The beat amount is stored in power of 2 form wxByte beatAmount = (wxByte)((m_data & beatAmountMask) >> 24); beatAmount = (wxByte)(pow(2, beatAmount)); return (beatAmount); } // Beaming Pattern Functions // Sets the beaming pattern /// @param beat1 Number of items to beam in the first beat /// @param beat2 Number of items to beam in the second beat /// @param beat3 Number of items to beam in the third beat /// @param beat4 Number of items to beam in the fourth beat /// @return True if the beaming pattern was set, false if not bool TimeSignature::SetBeamingPattern(wxByte beat1, wxByte beat2, wxByte beat3, wxByte beat4) { //------Last Checked------// // - Dec 13, 2004 wxCHECK(IsValidBeamingPatternBeat(beat1, true), false); wxCHECK(IsValidBeamingPatternBeat(beat2, false), false); wxCHECK(IsValidBeamingPatternBeat(beat3, false), false); wxCHECK(IsValidBeamingPatternBeat(beat4, false), false); // Clear the old beam data m_data &= ~beamingPatternMask; // Data is stored in zero-based format if (beat1 > 0) beat1--; if (beat2 > 0) beat2--; if (beat3 > 0) beat3--; if (beat4 > 0) beat4--; // Construct the beaming data wxUint32 beaming = 0; beaming = beat1; beaming <<= 5; beaming |= beat2; beaming <<= 5; beaming |= beat3; beaming <<= 5; beaming |= beat4; // Update the beaming pattern m_data |= beaming; return (true); } /// Gets the beaming pattern used by the time signature /// @param beat1 - Beaming pattern for the first beat in the time signature /// @param beat2 - Beaming pattern for the second beat in the time signature /// @param beat3 - Beaming pattern for the third beat in the time signature /// @param beat4 - Beaming pattern for the fourth beat in the time signature void TimeSignature::GetBeamingPattern(wxByte & beat1, wxByte & beat2, wxByte & beat3, wxByte & beat4) const { //------Last Checked------// // - Dec 13, 2004 // All the beam data is stored in zero-based format beat1 = (wxByte)((m_data & beamingPatternBeat1Mask) >> 15); beat1++; beat2 = (wxByte)((m_data & beamingPatternBeat2Mask) >> 10); if (beat2 > 0) beat2++; beat3 = (wxByte)((m_data & beamingPatternBeat3Mask) >> 5); if (beat3 > 0) beat3++; beat4 = (wxByte)(m_data & beamingPatternBeat4Mask); if (beat4 > 0) beat4++; } /// Sets the beaming pattern using a wxUint32 format value (wxUint32 format = beat1 - LOBYTE of LOWORD, beat2 - HIBYTE of LOWORD, beat3 - LOBYTE of HIWORD, beat4 - HIBYTE of HIWORD) /// @param beamingPattern Beaming pattern to set, in wxUint32 format /// @return True if the beaming pattern was set, false if not bool TimeSignature::SetBeamingPatternFromwxUint32(wxUint32 beamingPattern) { //------Last Checked------// // - Dec 13, 2004 return (SetBeamingPattern( LOBYTE(LOWORD(beamingPattern)), HIBYTE(LOWORD(beamingPattern)), LOBYTE(HIWORD(beamingPattern)), HIBYTE(HIWORD(beamingPattern)) ) ); } /// Gets the beaming pattern used by the time signature, in wxUint32 format (wxUint32 format = beat1 - LOBYTE of LOWORD, beat2 - HIBYTE of LOWORD, beat3 - LOBYTE of HIWORD, beat4 - HIBYTE of HIWORD) /// @return The beaming pattern for the time signature, in wxUint32 format wxUint32 TimeSignature::GetBeamingPatternAswxUint32() const { //------Last Checked------// // - Dec 12, 2004 wxByte beat1, beat2, beat3, beat4; GetBeamingPattern(beat1, beat2, beat3, beat4); return (MAKELONG(MAKEWORD(beat1, beat2), MAKEWORD(beat3, beat4))); } // Flag Functions /// Sets a flag used by the TimeSignature object /// @param flag The flag to set bool TimeSignature::SetFlag(wxUint32 flag) { //------Last Checked------// // - Dec 13, 2004 wxCHECK(IsValidFlag(flag), false); // Perform any mutual exclusive flag clearing if ((flag & commonTime) == commonTime) ClearFlag(cutTime); if ((flag & cutTime) == cutTime) ClearFlag(commonTime); m_data |= flag; return (true); } // Text Functions /// Gets a text representation of the meter /// @param type Type of text to get (see textTypes enum in .h for values) /// @return Text representation of the meter wxString TimeSignature::GetText(wxUint32 type) const { //------Last Checked------// // - Dec 13, 2004 int beatsPerMeasure = GetBeatsPerMeasure(); int beatAmount = GetBeatAmount(); wxString returnValue; // Beats per measure only if (type == textBeatsPerMeasure) returnValue = wxString::Format(wxT("%d"), beatsPerMeasure); // Beat amount only else if (type == textBeatAmount) returnValue = wxString::Format(wxT("%d"), beatAmount); // Full meter else returnValue = wxString::Format(wxT("%d/%d"), beatsPerMeasure, beatAmount); return (returnValue); }
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 461 ] ] ]
7edff9239c49329b2115deb8327d63088fd637b5
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaInstructions/ArraySetElementInstruction.cpp
93a43233356d1c54429df14c83f6620369ad481b
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include "TessaInstructionHeader.h" namespace TessaInstructions { ArraySetElementInstruction::ArraySetElementInstruction(TessaInstruction *receiverObject, TessaInstruction* index, TessaInstruction *valueToSet) : ArrayAccessInstruction(receiverObject, index) { this->valueToSet = valueToSet; } }
[ [ [ 1, 9 ] ] ]
a48edaa596e445ca8ac15ecce0c32f287eaea48c
009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd
/S60/inc/Engine.h
16f9342746dc765f308a8a083762ee2377ffe617
[]
no_license
AnthonyNystrom/MobiVU
c849857784c09c73b9ee11a49f554b70523e8739
b6b8dab96ae8005e132092dde4792cb363e732a2
refs/heads/master
2021-01-10T19:36:50.695911
2010-10-25T03:39:25
2010-10-25T03:39:25
1,015,426
3
3
null
null
null
null
UTF-8
C++
false
false
1,965
h
/* ============================================================================ Name : Engine.h Author : 7TouchGroup Version : 1.0 Copyright : 7TouchGroup Description : CEngine declaration ============================================================================ */ #ifndef ENGINE_H #define ENGINE_H #include <e32base.h> // For CActive, link against: euser.lib #include <e32std.h> // For RTimer, link against: euser.lib #include "DemoVideoCallAppUi.h" class CDemoVideoCallAppUi; class CEngine : public CActive { public: // Cancel and destroy ~CEngine(); // Two-phased constructor. static CEngine* NewL(); // Two-phased constructor. static CEngine* NewLC(); public: // New functions // Function for making the initial request void StartL(TTimeIntervalMicroSeconds32 aDelay); void ShowUsersLogged(){iState=EShowUsersOnline;} void MakeCall(){_iCntRing=0;iState=EMakeCall;} void StopCall(){iState = ELogin; _iCnt=0;} void StopLogin(){iState = ENoneState;} void InComingCall(){iState = EIncoming0;} void ResetRings(){_iCntRing=0;} TInt CanStartConversation(); private: // C++ constructor CEngine(); // Second-phase constructor void ConstructL(); CDemoVideoCallAppUi* iAppUi; private: // From CActive // Handle completion void RunL(); // How to cancel me void DoCancel(); // Override to handle leaves from RunL(). Default implementation causes // the active scheduler to panic. TInt RunError(TInt aError); private: enum TEngineState { EUninitialized, // Uninitialized EInitialized, // Initalized EError, // Error condition EShowUsersOnline, ENoneState, EMakeCall, ELogin, EIncoming0, EIncoming1, EConversation }; private: TInt iState; // State of the active object RTimer iTimer; // Provides async timing service TInt _iCntRing; TInt _iCnt; TInt _iCntForCloseConv; }; #endif // ENGINE_H
[ [ [ 1, 87 ] ] ]
62825eb1334da745e12ac52f27004ae07cf5c245
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/browse_record.h
9103096acb1034378f9ddcf680ee29802a1f7e50
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
605
h
#ifndef BROWSE_HISTORY_H #define BROWSE_HISTORY_H #include "wx/string.h" #ifndef WXDLLIMPEXP_LE #ifdef WXMAKINGDLL # define WXDLLIMPEXP_LE WXEXPORT #elif defined(WXUSINGDLL) # define WXDLLIMPEXP_LE WXIMPORT #else # define WXDLLIMPEXP_LE #endif // WXDLLIMPEXP_LE #endif class WXDLLIMPEXP_LE BrowseRecord { public: wxString filename; wxString project; int lineno; int position; public: BrowseRecord() : filename(wxEmptyString), project(wxEmptyString), lineno(wxNOT_FOUND), position(wxNOT_FOUND) {} ~BrowseRecord() {} }; #endif //BROWSE_HISTORY_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 31 ] ] ]
12fb59f97a7a51f9d5340206da9f8d65287c269f
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/gameswf/gameswf_morph2.cpp
3859b819c6fec548df0a7a095dfe2c7b3f689639
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
12,096
cpp
// gameswf_morph2.cpp // -- Thatcher Ulrich <[email protected]>, Mike Shaver <[email protected]> 2003, Vitalij Alexeev <[email protected]> 2004. // This source code has been donated to the Public Domain. Do // whatever you want with it. // Loading and rendering of morphing shapes using gameswf_shape. #include "gameswf/gameswf_morph2.h" #include "gameswf/gameswf_stream.h" #include "gameswf/gameswf_movie_def.h" namespace gameswf { morph2_character_def::morph2_character_def(player* player) : shape_character_def(player), m_last_ratio(-1.0f), m_mesh(0) { m_shape1 = new shape_character_def(player); m_shape2 = new shape_character_def(player); } morph2_character_def::~morph2_character_def() { delete m_shape2; delete m_shape1; } void morph2_character_def::display(character* inst) { int i; float ratio = inst->m_ratio; // bounds rect new_bound; new_bound.set_lerp(m_shape1->get_bound_local(), m_shape2->get_bound_local(), ratio); set_bound(new_bound); // fill styles for (i=0; i < m_fill_styles.size(); i++) { fill_style* fs = &m_fill_styles[i]; const fill_style& fs1 = m_shape1->get_fill_styles()[i]; const fill_style& fs2 = m_shape2->get_fill_styles()[i]; fs->set_lerp(fs1, fs2, ratio); } // line styles for (i=0; i < m_line_styles.size(); i++) { line_style& ls = m_line_styles[i]; const line_style& ls1 = m_shape1->get_line_styles()[i]; const line_style& ls2 = m_shape2->get_line_styles()[i]; ls.m_width = (Uint16)frnd(flerp(ls1.get_width(), ls2.get_width(), ratio)); ls.m_color.set_lerp(ls1.get_color(), ls2.get_color(), ratio); } // shape int k = 0, n = 0; for (i = 0; i < m_paths.size(); i++) { path& p = m_paths[i]; const path& p1 = m_shape1->get_paths()[i]; // Swap fill styles -- for some reason, morph // shapes seem to be defined with their fill // styles backwards! p.m_fill0 = p1.m_fill1; p.m_fill1 = p1.m_fill0; p.m_line = p1.m_line; p.m_ax = flerp(p1.m_ax, m_shape2->get_paths()[n].m_ax, ratio); p.m_ay = flerp(p1.m_ay, m_shape2->get_paths()[n].m_ay, ratio); // edges; int len = p1.m_edges.size(); p.m_edges.resize(len); for (int j=0; j < p.m_edges.size(); j++) { p.m_edges[j].m_cx = flerp(p1.m_edges[j].m_cx, m_shape2->get_paths()[n].m_edges[k].m_cx, ratio); p.m_edges[j].m_cy = flerp(p1.m_edges[j].m_cy, m_shape2->get_paths()[n].m_edges[k].m_cy, ratio); p.m_edges[j].m_ax = flerp(p1.m_edges[j].m_ax, m_shape2->get_paths()[n].m_edges[k].m_ax, ratio); p.m_edges[j].m_ay = flerp(p1.m_edges[j].m_ay, m_shape2->get_paths()[n].m_edges[k].m_ay, ratio); k++; if (m_shape2->get_paths()[n].m_edges.size() <= k) { k = 0; n++; } } } // display matrix mat = inst->get_world_matrix(); cxform cx = inst->get_world_cxform(); float max_error = 20.0f / mat.get_max_scale() / inst->get_parent()->get_pixel_scale(); if (ratio != m_last_ratio) { delete m_mesh; m_last_ratio = ratio; m_mesh = new mesh_set(this, max_error * 0.75f); } m_mesh->display(mat, cx, m_fill_styles, m_line_styles); } void morph2_character_def::read(stream* in, int tag_type, bool with_style, movie_definition_sub* md) { UNUSED(with_style); rect bound1, bound2; bound1.read(in); bound2.read(in); m_shape1->set_bound(bound1); m_shape2->set_bound(bound2); if(tag_type == 84) { rect edge_bound1, edge_bound2; edge_bound1.read(in); edge_bound2.read(in); int reserved = in->read_uint(6); assert(reserved == 0); m_uses_nonscaling_strokes = in->read_uint(1) == 1; m_uses_scaling_strokes = in->read_uint(1) == 1; } m_offset = in->read_u32(); m_fill_style_count = in->read_variable_count(); int i; for (i = 0; i < m_fill_style_count; i++) { fill_style fs1, fs2; fs1.m_type = in->read_u8(); fs2.m_type = fs1.m_type; IF_VERBOSE_PARSE(log_msg("morph fill style type = 0x%X\n", fs1.m_type)); if (fs1.m_type == 0x00) { fs1.m_color.read_rgba(in); fs2.m_color.read_rgba(in); IF_VERBOSE_PARSE(log_msg("morph fill style begin color: "); fs1.m_color.print()); IF_VERBOSE_PARSE(log_msg("morph fill style end color: "); fs2.m_color.print()); } else if (fs1.m_type == 0x10 || fs1.m_type == 0x12) { matrix input_matrix1, input_matrix2; input_matrix1.read(in); input_matrix2.read(in); fs1.m_gradient_matrix.set_identity(); fs2.m_gradient_matrix.set_identity(); if (fs1.m_type == 0x10) { fs1.m_gradient_matrix.concatenate_translation(128.f, 0.f); fs1.m_gradient_matrix.concatenate_scale(1.0f / 128.0f); fs2.m_gradient_matrix.concatenate_translation(128.f, 0.f); fs2.m_gradient_matrix.concatenate_scale(1.0f / 128.0f); } else { fs1.m_gradient_matrix.concatenate_translation(32.f, 32.f); fs1.m_gradient_matrix.concatenate_scale(1.0f / 512.0f); fs2.m_gradient_matrix.concatenate_translation(32.f, 32.f); fs2.m_gradient_matrix.concatenate_scale(1.0f / 512.0f); } matrix m1, m2; m1.set_inverse(input_matrix1); fs1.m_gradient_matrix.concatenate(m1); m2.set_inverse(input_matrix2); fs2.m_gradient_matrix.concatenate(m2); // GRADIENT int num_gradients = in->read_u8(); assert(num_gradients >= 1 && num_gradients <= 8); fs1.m_gradients.resize(num_gradients); fs2.m_gradients.resize(num_gradients); for (int j = 0; j < num_gradients; j++) { fs1.m_gradients[j].read(in, tag_type); fs2.m_gradients[j].read(in, tag_type); } IF_VERBOSE_PARSE(log_msg("morph fsr: num_gradients = %d\n", num_gradients)); // @@ hack. if (num_gradients > 0) { fs1.m_color = fs1.m_gradients[0].m_color; fs2.m_color = fs2.m_gradients[0].m_color; } } else if (fs1.m_type == 0x40 || fs1.m_type == 0x41) { int bitmap_char_id = in->read_u16(); IF_VERBOSE_PARSE(log_msg("morph fsr bitmap_char = %d\n", bitmap_char_id)); // Look up the bitmap character. fs1.m_bitmap_character = md->get_bitmap_character(bitmap_char_id); fs2.m_bitmap_character = fs1.m_bitmap_character; matrix m1, m2; m1.read(in); m2.read(in); // For some reason, it looks like they store the inverse of the // TWIPS-to-texcoords matrix. fs1.m_bitmap_matrix.set_inverse(m1); fs2.m_bitmap_matrix.set_inverse(m2); } m_shape1->m_fill_styles.push_back(fs1); m_shape2->m_fill_styles.push_back(fs2); } m_line_style_count = in->read_variable_count(); if(tag_type == 46) { for (i = 0; i < m_line_style_count; i++) { line_style ls1, ls2; ls1.m_width = in->read_u16(); ls2.m_width = in->read_u16(); ls1.m_color.read(in, tag_type); ls2.m_color.read(in, tag_type); m_shape1->m_line_styles.push_back(ls1); m_shape2->m_line_styles.push_back(ls2); } } else { assert(tag_type == 84); for (i = 0; i < m_line_style_count; i++) { line_style ls1, ls2; ls1.m_width = in->read_u16(); ls2.m_width = in->read_u16(); int start_cap_style = in->read_uint(2); int join_style = in->read_uint(2); int has_fill_flag = in->read_uint(1); int no_h_scale_flag = in->read_uint(1); int no_v_scale_flag = in->read_uint(1); int pixel_hinting_flag = in->read_uint(1); int reserved = in->read_uint(1); assert( reserved == 0 ); int no_close = in->read_uint(1); int end_cap_style = in->read_uint(2); if( join_style == 2 ) { int miter_limit_factor_fixed = in->read_u16(); // 8.8 fixed point format float miter_limit_factor = (float) miter_limit_factor_fixed / 256.0f; } if( has_fill_flag == 0 ) { rgba start_color; start_color.read_rgba( in ); rgba end_color; end_color.read_rgba( in ); } else { // todo factorize fill_style read fill_style fs1, fs2; fs1.m_type = in->read_u8(); fs2.m_type = fs1.m_type; IF_VERBOSE_PARSE(log_msg("morph fill style type = 0x%X\n", fs1.m_type)); if (fs1.m_type == 0x00) { fs1.m_color.read_rgba(in); fs2.m_color.read_rgba(in); IF_VERBOSE_PARSE(log_msg("morph fill style begin color: "); fs1.m_color.print()); IF_VERBOSE_PARSE(log_msg("morph fill style end color: "); fs2.m_color.print()); } else if (fs1.m_type == 0x10 || fs1.m_type == 0x12) { matrix input_matrix1, input_matrix2; input_matrix1.read(in); input_matrix2.read(in); fs1.m_gradient_matrix.set_identity(); fs2.m_gradient_matrix.set_identity(); if (fs1.m_type == 0x10) { fs1.m_gradient_matrix.concatenate_translation(128.f, 0.f); fs1.m_gradient_matrix.concatenate_scale(1.0f / 128.0f); fs2.m_gradient_matrix.concatenate_translation(128.f, 0.f); fs2.m_gradient_matrix.concatenate_scale(1.0f / 128.0f); } else { fs1.m_gradient_matrix.concatenate_translation(32.f, 32.f); fs1.m_gradient_matrix.concatenate_scale(1.0f / 512.0f); fs2.m_gradient_matrix.concatenate_translation(32.f, 32.f); fs2.m_gradient_matrix.concatenate_scale(1.0f / 512.0f); } matrix m1, m2; m1.set_inverse(input_matrix1); fs1.m_gradient_matrix.concatenate(m1); m2.set_inverse(input_matrix2); fs2.m_gradient_matrix.concatenate(m2); // GRADIENT int num_gradients = in->read_u8(); assert(num_gradients >= 1 && num_gradients <= 8); fs1.m_gradients.resize(num_gradients); fs2.m_gradients.resize(num_gradients); for (int j = 0; j < num_gradients; j++) { fs1.m_gradients[j].read(in, tag_type); fs2.m_gradients[j].read(in, tag_type); } IF_VERBOSE_PARSE(log_msg("morph fsr: num_gradients = %d\n", num_gradients)); // @@ hack. if (num_gradients > 0) { fs1.m_color = fs1.m_gradients[0].m_color; fs2.m_color = fs2.m_gradients[0].m_color; } } else if (fs1.m_type == 0x40 || fs1.m_type == 0x41) { int bitmap_char_id = in->read_u16(); IF_VERBOSE_PARSE(log_msg("morph fsr bitmap_char = %d\n", bitmap_char_id)); // Look up the bitmap character. fs1.m_bitmap_character = md->get_bitmap_character(bitmap_char_id); fs2.m_bitmap_character = fs1.m_bitmap_character; matrix m1, m2; m1.read(in); m2.read(in); } } /* ls1.m_color.read(in, tag_type); ls2.m_color.read(in, tag_type); m_shape1->m_line_styles.push_back(ls1); m_shape2->m_line_styles.push_back(ls2); */ } } m_shape1->read(in, tag_type, false, md); in->align(); m_shape2->read(in, tag_type, false, md); assert(m_shape1->m_fill_styles.size() == m_shape2->m_fill_styles.size()); assert(m_shape1->m_line_styles.size() == m_shape2->m_line_styles.size()); // setup array size m_fill_styles.resize(m_shape1->m_fill_styles.size()); for (i = 0; i < m_fill_styles.size(); i++) { fill_style& fs = m_fill_styles[i]; fill_style& fs1 = m_shape1->m_fill_styles[i]; fs.m_gradients.resize(fs1.m_gradients.size()); } m_line_styles.resize(m_shape1->m_line_styles.size()); m_paths.resize(m_shape1->m_paths.size()); int edges_count1 = 0; for (i = 0; i < m_paths.size(); i++) { path& p = m_paths[i]; path& p1 = m_shape1->m_paths[i]; int len = p1.m_edges.size(); edges_count1 += len; p.m_edges.resize(len); } int edges_count2 = 0; for (i = 0; i < m_shape2->m_paths.size(); i++) { path& p2 = m_shape2->m_paths[i]; int len = p2.m_edges.size(); edges_count2 += len; } assert(edges_count1 == edges_count2); } } // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 416 ] ] ]
54598c7997216e29bcc4342e2c5b25d2d7888040
b411e4861bc1478147bfc289c868b961a6136ead
/tags/DownhillRacing/Level.h
c47e1503b8d9f26e54d86b630cba74b1919134b6
[]
no_license
mvm9289/downhill-racing
d05df2e12384d8012d5216bc0b976bc7df9ff345
038ec4875db17a7898282d6ced057d813a0243dc
refs/heads/master
2021-01-20T12:20:31.383595
2010-12-19T23:29:02
2010-12-19T23:29:02
32,334,476
0
0
null
null
null
null
UTF-8
C++
false
false
472
h
#pragma once #include "Terrain.h" #include "Box.h" #include "Sphere.h" #include <string> class Level { private: Terrain *terrain; Sphere *skydome; bool hellmode; public: Level(string level); Level(void); virtual ~Level(void); Point startupPoint(); Point endPoint(); bool loadLevel(string level); void boundingSphere(Point& center, float& radius); Box boundingBox(); void render(); Terrain* getTerrain(); bool isHellMode(); };
[ "mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1" ]
[ [ [ 1, 28 ] ] ]
558f708fe16da46e6e1eda0fb9bcf824991ce8e0
96ae76a21d65bb48d04f74a2ae8d705b47d1d969
/pongar/src/Paddle.cpp
a6bafb8a1e6dfd07bf1107e4431303351859034e
[]
no_license
tedwp/pongar
d48b9112bb2bfe27428a8df5e9b3bad31c03347e
de96ae581684874e96d562122008b4acd313ebbd
refs/heads/master
2021-01-10T02:58:43.849201
2011-02-07T01:11:46
2011-02-07T01:11:46
48,293,673
0
0
null
null
null
null
UTF-8
C++
false
false
4,328
cpp
#include "Paddle.h" Paddle::Paddle(void) { m_color.red = 255; m_color.green = 0; m_color.blue = 255; m_color.alpha = 255; m_marker = NULL; m_isLeft = true; m_playingField = NULL; m_score = 0; m_size = PADDLE_LENGTH; m_zoomFactor = 1.5f; m_zoomOffset = 0.0f; } Paddle::~Paddle(void) { } void Paddle::render(void) { glTranslatef( 0.0f, 0.0f, -0.01f ); float paddle1YStart = m_size/2 - m_yPosition; float paddle1YEnd = -m_size/2 - m_yPosition; if (paddle1YStart > PLAYINGFIELD_HEIGHT/2) { paddle1YEnd = PLAYINGFIELD_HEIGHT/2; paddle1YStart = paddle1YEnd - m_size; } if (paddle1YEnd < -PLAYINGFIELD_HEIGHT/2) { paddle1YStart = -PLAYINGFIELD_HEIGHT/2; paddle1YEnd = paddle1YStart + m_size; } // draw paddle glColor4f( m_color.red, m_color.green, m_color.blue, m_color.alpha ); if(isLeft()) glRectf(paddle1YEnd, -(PLAYINGFIELD_WIDTH / 2) - PADDLE_WIDTH/2 , paddle1YStart, -(PLAYINGFIELD_WIDTH / 2) + PADDLE_WIDTH/2); else glRectf(paddle1YEnd, PLAYINGFIELD_WIDTH / 2 - PADDLE_WIDTH/2, paddle1YStart, PLAYINGFIELD_WIDTH / 2 + PADDLE_WIDTH/2); } void Paddle::updatePositionFromMarker(void) { float* playingFieldTf = m_playingField->getCorrespondingMarker()->getPosition(); float* paddle1Tf = m_marker->getPosition(); float vec1[3]; vec1[0] = paddle1Tf[3]-playingFieldTf[3]; vec1[1] = paddle1Tf[7]-playingFieldTf[7]; vec1[2] = 0.0; //get point on inner axis and paddle axis float xaxisVectorInp[4] = {0,1,0,0}; float xaxisVector[4] = {0,0,0,0}; //mult vector by matrix for(int i=0; i<4; i++){ xaxisVector[i] = 0; for(int j=0; j<4; j++){ xaxisVector[i] += playingFieldTf[4*i + j] * xaxisVectorInp[j]; } } float vec2[3]; vec2[0] = xaxisVector[0]-playingFieldTf[3]; vec2[1] = xaxisVector[1]-playingFieldTf[7]; vec2[2] = 0.0; //calculate angle between these vectors //first normalize vectors float help = sqrt( vec1[0]*vec1[0] + vec1[1]*vec1[1] + vec1[2]*vec1[2] ); vec1[0] /= help; vec1[1] /= help; vec1[2] /= help; help = sqrt( vec2[0]*vec2[0] + vec2[1]*vec2[1] + vec2[2]*vec2[2] ); vec2[0] /= help; vec2[1] /= help; vec2[2] /= help; //then calculate the angle float angle = (180 / 3.14159f) * acos( vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2] ); if((vec1[0] * vec2[1] - vec1[1] * vec2[0]) < 0 ) angle *= -1; m_yPosition = m_zoomOffset + m_zoomFactor * (float) PLAYINGFIELD_WIDTH/2 * sin(angle*3.14159f/180); /*float paddle1offset = (float) PLAYINGFIELD_WIDTH/2 * sin(angle*3.14159f/180); m_yPosition = paddle1offset; m_yRenderPosition = paddle1offset;*/ } void Paddle::arrayToCvMat(float* transform, CvMat* mat) { cvZero( mat ); for (unsigned i = 0; i < 16; i++) { cvmSet( mat, i/4, i%4, transform[i] ); } } float Paddle::getYPosition(void) { return m_yPosition; } /*float Paddle::getYRenderPosition(void) { return m_yRenderPosition; }*/ void Paddle::setMarker(Marker* marker) { m_marker = marker; } bool Paddle::isLeft(void) { return m_isLeft; } void Paddle::setLeft(bool isLeft) { m_isLeft = isLeft; } void Paddle::setPlayingField(PlayingField* playingField) { m_playingField = playingField; } void Paddle::increaseScore(void) { m_score++; } int Paddle::getScore(void) { return m_score; } void Paddle::reset(void) { m_yPosition = 0; //m_yRenderPosition = 0; m_score = 0; } float Paddle::getSize(void) { return m_size; } void Paddle::disableAllActions(void) { disableActionSizeDecrease(); disableActionSizeIncrease(); } void Paddle::enableActionSizeIncrease(void) { if(!m_actionSizeIncreaseEnabled) { m_size *= ACTION_INCREASESIZE_PADDLE_FACTOR; m_actionSizeIncreaseEnabled = true; } } void Paddle::disableActionSizeIncrease(void) { if(m_actionSizeIncreaseEnabled) { m_size /= ACTION_INCREASESIZE_PADDLE_FACTOR; m_actionSizeIncreaseEnabled = false; } } void Paddle::enableActionSizeDecrease(void) { if(!m_actionSizeDecreaseEnabled) { m_size *= ACTION_DECREASESIZE_PADDLE_FACTOR; m_actionSizeDecreaseEnabled = true; } } void Paddle::disableActionSizeDecrease(void) { if(m_actionSizeDecreaseEnabled) { m_size /= ACTION_DECREASESIZE_PADDLE_FACTOR; m_actionSizeDecreaseEnabled = false; } }
[ "salatgurke00@cd860a2f-db29-0b79-333e-049c8ca359aa", "[email protected]", "[email protected]" ]
[ [ [ 1, 5 ], [ 10, 11 ], [ 17, 22 ], [ 24, 24 ], [ 41, 41 ], [ 48, 51 ], [ 107, 112 ], [ 117, 127 ] ], [ [ 6, 9 ], [ 12, 16 ], [ 23, 23 ], [ 25, 39 ], [ 44, 47 ], [ 52, 54 ], [ 59, 59 ], [ 75, 75 ], [ 82, 82 ], [ 87, 87 ], [ 91, 93 ], [ 96, 106 ], [ 113, 113 ], [ 116, 116 ], [ 128, 188 ] ], [ [ 40, 40 ], [ 42, 43 ], [ 55, 58 ], [ 60, 74 ], [ 76, 81 ], [ 83, 86 ], [ 88, 90 ], [ 94, 95 ], [ 114, 115 ] ] ]
42770271abe7dfe87778ab0f6dcebed9b1c0af66
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/PathwayLoader.h
b2dfe7ec4f765da4850edcb7e171b266e73e3a8e
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
256
h
#pragma once namespace Kylin { class PathwayLoader { public: PathwayLoader(); ~PathwayLoader(); virtual KBOOL Load(KCCHAR* pScene); Pathway* GetPathway(KUINT uID); protected: KMAP<KUINT,Pathway*> m_kPathwayMap; }; }
[ [ [ 1, 20 ] ] ]
18e9b32122af7bf7e335cbba7e848578bb36eca7
3fe4cb1c37ed16389f90818b7d07aa5d05bf59e3
/ImageProcessing/ImageProcessing/PanView.cpp
edabd6b35112fd37b8d8649bcc69b654923b4e7a
[]
no_license
zinking/advancedimageprocessing
e0fbc1c69810202b89b2510ddaf60561ce0fe806
0c68e11109c0d6299881aecefaf3a85efa8d4471
refs/heads/master
2021-01-21T11:46:53.348948
2008-12-08T06:15:06
2008-12-08T06:15:06
32,132,965
0
0
null
null
null
null
GB18030
C++
false
false
685
cpp
// PanView.cpp : 实现文件 // #include "stdafx.h" #include "ImageProcessing.h" #include "PanView.h" // CPanView IMPLEMENT_DYNCREATE(CPanView, CFormView) CPanView::CPanView() : CFormView(CPanView::IDD) { } CPanView::~CPanView() { } void CPanView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CPanView, CFormView) END_MESSAGE_MAP() // CPanView 诊断 #ifdef _DEBUG void CPanView::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CPanView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG // CPanView 消息处理程序
[ "zinking3@f9886646-c4e6-11dd-8bad-cde060d8fd3c" ]
[ [ [ 1, 49 ] ] ]
b3b933358b4c1f9b8b2043073ac8e6d9fd3a46a8
b22c254d7670522ec2caa61c998f8741b1da9388
/shared/PlayerCallbackBase.h
017ee04fe4a5ee59d66578bdad6b89385fc480bb
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
2,156
h
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #ifndef _LBA_NET_PLAYER_CALLBACK_BASE_H_ #define _LBA_NET_PLAYER_CALLBACK_BASE_H_ #include <boost/shared_ptr.hpp> struct Input; class PhysicalObjectHandlerBase; /*********************************************************************** * Module: PlayerCallbackBase.h * Author: vivien * Modified: mardi 14 juillet 2009 17:41:03 * Purpose: base class to handle player inputs ***********************************************************************/ class PlayerCallbackBase { public: // constructor PlayerCallbackBase(){} // destructor virtual ~PlayerCallbackBase(){} // called when we get new friend in list virtual void inputUpdated(unsigned int time, const Input & newinput) = 0; // apply stored input for a specific time period virtual void applyInput(unsigned int timeleftborder, unsigned int timerightborder) = 0; // apply last character move virtual void applyLastMove() = 0; // reset input iterator at each cycle virtual void resetIterator() = 0; // set physcial character virtual void SetPhysicalCharacter(boost::shared_ptr<PhysicalObjectHandlerBase> charac, bool AsGhost=false) = 0; }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 72 ] ] ]
b4554b784d6344e3d005073fe227579f9cbfa538
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qstylepainter.h
944a0e00e64490b15b2728a811d65b3118053612
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,354
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QSTYLEPAINTER_H #define QSTYLEPAINTER_H #include <QtGui/qpainter.h> #include <QtGui/qstyle.h> #include <QtGui/qwidget.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QStylePainter : public QPainter { public: inline QStylePainter() : QPainter(), widget(0), wstyle(0) {} inline explicit QStylePainter(QWidget *w) { begin(w, w); } inline QStylePainter(QPaintDevice *pd, QWidget *w) { begin(pd, w); } inline bool begin(QWidget *w) { return begin(w, w); } inline bool begin(QPaintDevice *pd, QWidget *w) { Q_ASSERT_X(w, "QStylePainter::QStylePainter", "Widget must be non-zero"); widget = w; wstyle = w->style(); return QPainter::begin(pd); }; inline void drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt); inline void drawControl(QStyle::ControlElement ce, const QStyleOption &opt); inline void drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt); inline void drawItemText(const QRect &r, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole = QPalette::NoRole); inline void drawItemPixmap(const QRect &r, int flags, const QPixmap &pixmap); inline QStyle *style() const { return wstyle; } private: QWidget *widget; QStyle *wstyle; Q_DISABLE_COPY(QStylePainter) }; void QStylePainter::drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt) { wstyle->drawPrimitive(pe, &opt, this, widget); } void QStylePainter::drawControl(QStyle::ControlElement ce, const QStyleOption &opt) { wstyle->drawControl(ce, &opt, this, widget); } void QStylePainter::drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt) { wstyle->drawComplexControl(cc, &opt, this, widget); } void QStylePainter::drawItemText(const QRect &r, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole) { wstyle->drawItemText(this, r, flags, pal, enabled, text, textRole); } void QStylePainter::drawItemPixmap(const QRect &r, int flags, const QPixmap &pixmap) { wstyle->drawItemPixmap(this, r, flags, pixmap); } QT_END_NAMESPACE QT_END_HEADER #endif // QSTYLEPAINTER_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 112 ] ] ]
9a2d0ebf65e8889f69cb570b02d8c11697d8b480
305d82f4e4a75f9366316ef1c1574982342cb342
/form_test/form_test/FORM.cpp
39e8297bdde8afd3db805c9938f212f6498b075b
[]
no_license
jabbilabbi/cmpt212-spring10
a260e8eba3a8899ae47220e6e59be5e355781d30
64a7490a7602a32892f23e89f5e8ca270a83fe3b
refs/heads/master
2021-01-01T19:06:28.560193
2010-04-16T11:49:46
2010-04-16T11:49:46
32,115,006
0
0
null
null
null
null
UTF-8
C++
false
false
437
cpp
// FORM.cpp : implementation file // #include "stdafx.h" #include "form_test.h" #include "FORM.h" // FORM dialog IMPLEMENT_DYNAMIC(FORM, CDialog) FORM::FORM(CWnd* pParent /*=NULL*/) : CDialog(FORM::IDD, pParent) { } FORM::~FORM() { } void FORM::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(FORM, CDialog) END_MESSAGE_MAP() // FORM message handlers
[ "alexantonio@accf1826-6565-04f0-df9b-893c0ca74f04" ]
[ [ [ 1, 33 ] ] ]
5c4af3e6a09a1aba8d09a7c52af71db852a991fa
e98d99816ad42028e5988ade802ffdf9846da166
/Mediotic/mediObjSurfaceCreationStrategy.h
a5fb368a5b206c793d0767cd3402c9efee7d7b20
[]
no_license
OpenEngineDK/extensions-MediPhysics
5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64
94fdd25f90608ad3db6b3c6a30db1c1e4c490987
refs/heads/master
2016-09-14T04:26:29.607457
2008-10-14T12:14:53
2008-10-14T12:14:53
58,073,189
0
0
null
null
null
null
UTF-8
C++
false
false
520
h
#pragma once #include "mediSurfaceCreationStrategy.h" #include "OBJLoader/ObjLoader.h" #include <string> class mediObjSurfaceCreationStrategy : public mediSurfaceCreationStrategy { private: ObjLoader obj; public: mediObjSurfaceCreationStrategy(void); ~mediObjSurfaceCreationStrategy(void); mediObjSurfaceCreationStrategy(std::string filename); void process(std::vector<mediParticle> & particles, mediSurface & surface); ObjLoader* GetObjModel(); void CopyObjModel(ObjLoader obj); };
[ [ [ 1, 20 ] ] ]
93cb06e9f7226f108dca70b2ae0d9ecbcd458416
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/qlocalemap.h
69fba788b84f496e70a94542611ff676feeeb9da
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
#ifndef QLOCALEMAP_H #define QLOCALEMAP_H #include <QObject> #include <QString> #include <QMap> class QLocaleMap : public QObject { public: QLocaleMap(); QMap<QString,QString> localeMap; const QMap<QString,QString>& getLocale(){return localeMap;} }; #endif // QLOCALEMAP_H
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 16 ] ] ]
c30afc613b6a70232c225590ca1dbb05a33f43c7
368c34f3901c02da13d4a03730d4a859e3f3dc91
/key-net/Socket.cpp
1db1579048ac3810e33b83aae5989122f6f7c87b
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
Nercury/epics
2c0f1f521894b5478fb993c96aad80f89502e593
37c3e4b47510085245bc4dc7795e777b5541a2df
refs/heads/master
2020-12-24T16:58:32.814871
2011-12-19T21:24:46
2011-12-19T21:24:46
2,839,261
0
0
null
null
null
null
UTF-8
C++
false
false
8,313
cpp
#include "Socket.h" using namespace key; using namespace key::internal; void Socket::Init(KEY_SOCKET socket_handle) { #ifdef WIN32 WSADATA wsaData; if (WSAStartup( MAKEWORD(2,2), &wsaData ) != NO_ERROR) { is_failed = true; return; } #endif this->af = AF_INET; this->type = SOCK_STREAM; this->protocol = IPPROTO_TCP; if (socket_handle == NULL) { this->socket_handle = socket(this->af, this->type, this->protocol); if ( this->socket_handle == INVALID_SOCKET ) { is_failed = true; } else { u_long iMode = 1; ioctlsocket(this->socket_handle, FIONBIO, &iMode); } } else { this->socket_handle = socket_handle; if (this->socket_handle != INVALID_SOCKET && this->socket_handle != SOCKET_ERROR) was_connected = true; } #ifdef WIN32 if (this->socket_handle != NULL) this->ex_functions.set_socket(this->socket_handle); #endif } Socket::Socket() : is_bound(false), is_failed(false), is_listening(false), was_connected(false), is_accepting(false), is_accepting_and_receiving(false) { this->Init(NULL); } Socket::Socket(KEY_SOCKET socket_handle) : is_bound(false), is_failed(false), is_listening(false), was_connected(false), is_accepting(false), is_accepting_and_receiving(false) { this->Init(socket_handle); } Socket::~Socket() { this->Close(); #ifdef WIN32 // only the last call to this cleans up wsa, so we are good. WSACleanup(); #endif } fun_res Socket::Bind(uint16_t port) { this->service.sin_family = AF_INET; this->service.sin_addr.s_addr = ADDR_ANY;//inet_addr("0.0.0.0"); this->service.sin_port = htons(port); int yes = 1; if (setsockopt(this->socket_handle, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes)) < 0) { std::string error = (boost::format("Error setting socket parameters: %1%") % socket_error_message(socket_last_error(), SocketErrorScope::Bind)).str(); closesocket(this->socket_handle); this->socket_handle = SOCKET_ERROR; this->is_bound = false; return fun_error(error); } // Bind the socket. auto res = bind( this->socket_handle, (SOCKADDR*)&(this->service), sizeof(this->service)); if (res == SOCKET_ERROR) { std::string error = (boost::format("Error binding socket: %1%") % socket_error_message(socket_last_error(), SocketErrorScope::Bind)).str(); closesocket(this->socket_handle); this->socket_handle = SOCKET_ERROR; this->is_bound = false; return fun_error(error); } this->is_bound = true; return fun_ok(); } #ifdef WIN32 static void begin_accept_win_completion(DWORD bytes_transfered, key::internal::OVERLAPPEDACCEPT * ac) { ac->callback(std::make_shared<Socket>(ac->accept_socket)); } #endif fun_res Socket::BeginAccept(std::function<void (std::shared_ptr<Socket>)> callback) { if (is_failed) return fun_error("Cannot accept on failed socket"); if (!is_bound) return fun_error("Bind() must be called before BeginAccept()"); if (!this->is_listening) { this->is_listening = true; if (listen( this->socket_handle, 1 ) == SOCKET_ERROR) { this->is_listening = false; return fun_error((boost::format("Error listening on socket: %1%") % socket_error_message(socket_last_error(), SocketErrorScope::Listen)).str()); } } #ifdef WIN32 if (!is_accepting) { accept_completion.Open(boost::thread::hardware_concurrency(), begin_accept_win_completion); is_accepting = true; } KEY_SOCKET acc_socket = socket(this->af, this->type, this->protocol); if ( acc_socket == INVALID_SOCKET ) { return fun_error(boost::format("Error creating accept socket: %1%") % socket_last_error_message()); } else { u_long iMode = 1; ioctlsocket(acc_socket, FIONBIO, &iMode); accept_completion.AssignSocket(this->socket_handle); auto data = accept_completion.NewData(); memset(&(data->ol), 0, sizeof(data->ol)); data->accept_socket = acc_socket; data->callback = callback; ex_functions.get_accept_ex()(this->socket_handle, acc_socket, &(*data).buf, 0, sizeof(sockaddr_in) + 16, sizeof(sockaddr_in) + 16, &(data->bytesReceived), &(data->ol)); // uh... } #endif return fun_ok(); } #ifdef WIN32 static void begin_accept_and_receive_win_completion(DWORD bytes_transferred, key::internal::OVERLAPPEDACCEPTANDRECEIVE * ac) { ac->callback((uint32_t)bytes_transferred, ac->buf.get(), std::make_shared<Socket>(ac->accept_socket)); } #endif fun_res Socket::BeginAcceptAndReceive(int32_t no_data_timeout_ms, int32_t buf_size, std::function<void (uint32_t bytes_transferred, char * bytes, std::shared_ptr<Socket>)> callback) { if (is_failed) return fun_error("Cannot accept on failed socket"); if (!is_bound) return fun_error("Bind() must be called before BeginAccept()"); if (!this->is_listening) { this->is_listening = true; if (listen( this->socket_handle, 1 ) == SOCKET_ERROR) { this->is_listening = false; return fun_error((boost::format("Error listening on socket: %1%") % socket_error_message(socket_last_error(), SocketErrorScope::Listen)).str()); } } #ifdef WIN32 if (!is_accepting_and_receiving) { accept_and_receive_completion.Open(boost::thread::hardware_concurrency(), begin_accept_and_receive_win_completion); is_accepting_and_receiving = true; } KEY_SOCKET acc_socket = socket(this->af, this->type, this->protocol); if ( acc_socket == INVALID_SOCKET ) { return fun_error(boost::format("Error creating accept socket: %1%") % socket_last_error_message()); } else { u_long iMode = 1; ioctlsocket(acc_socket, FIONBIO, &iMode); accept_and_receive_completion.AssignSocket(this->socket_handle); auto data = accept_and_receive_completion.NewData(); memset(&(data->ol), 0, sizeof(data->ol)); data->accept_socket = acc_socket; data->buf.reset(new char[buf_size + (sizeof(sockaddr_in) + 16) * 2]); data->buf_size = buf_size; data->callback = callback; ex_functions.get_accept_ex()(this->socket_handle, acc_socket, &(*data).buf[0], buf_size, sizeof(sockaddr_in) + 16, sizeof(sockaddr_in) + 16, &(data->bytesReceived), &(data->ol)); // uh... } #endif return fun_ok(); } fun_res Socket::BeginConnect(std::string address, uint16_t port, std::function<void (std::shared_ptr<Socket>)> callback) { if (is_failed) return fun_error("Cannot connect on failed socket"); if (was_connected) return fun_error("Can not connect on already connected socket"); #ifdef WIN32 auto connect_ex = this->ex_functions.get_connect_ex(); return cndc->BeginConnect(connect_ex, this->shared_from_this(), address, port, callback); #else return fun_error("connect is not implemented"); #endif } fun_res Socket::BeginSend(char * buffer, int buffer_size, std::function<void (std::shared_ptr<Socket>)> callback) { if (is_failed) return fun_error("Cannot send on failed socket"); if (!was_connected) return fun_error("Cannot send on non-connected socket"); #ifdef WIN32 return this->io->BeginSend(this->shared_from_this(), buffer, buffer_size, callback); #else return fun_error("send is not implemented"); #endif } fun_res Socket::BeginReceive(char * buffer, int buffer_size, std::function<void (char * buffer, int buffer_size, uint64_t bytes_transferred, std::shared_ptr<Socket>)> callback) { if (is_failed) return fun_error("Cannot receive on failed socket"); if (!was_connected) return fun_error("Cannot receive on non-connected socket"); #ifdef WIN32 return this->io->BeginReceive(this->shared_from_this(), buffer, buffer_size, callback); #else return fun_error("receive is not implemented"); #endif } fun_res Socket::Close() { this->was_connected = false; if (this->socket_handle != INVALID_SOCKET) { if (closesocket(this->socket_handle) == SOCKET_ERROR) { this->socket_handle = INVALID_SOCKET; return fun_error(boost::format("Socket close failure: %1%") % socket_last_error_message()); } this->socket_handle = INVALID_SOCKET; #ifdef WIN32 this->accept_completion.Close(); this->accept_and_receive_completion.Close(); #endif this->is_accepting = false; this->is_accepting_and_receiving = false; } return fun_ok(); }
[ [ [ 1, 292 ] ] ]
d50bce0a28d740af5c892c5311546fd3997ad9af
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/CERTIFIER/user.h
e09b078d9aaee52bde903eae12f735001cebdcfe
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
847
h
#ifndef __USER_H__ #define __USER_H__ #include <dplay.h> #include <map> #include <string> #include "dpmng.h" using namespace std; class CUser { public: DPID m_dpid; DWORD m_dwTick; BOOL m_bValid; public: CUser( DPID dpid ); virtual ~CUser() {} void SetAccount( const char* szAccount ) { strncpy( m_pszAccount, szAccount, MAX_ACCOUNT ); m_pszAccount[MAX_ACCOUNT-1] = '\0'; } const char* GetAccount( void ) { return m_pszAccount; } private: char m_pszAccount[MAX_ACCOUNT]; }; class CUserMng : public map<DPID, CUser*> { public: CMclCritSec m_AddRemoveLock; public: CUserMng(); virtual ~CUserMng(); BOOL AddUser( DPID dpid ); BOOL RemoveUser( DPID dpid ); CUser* GetUser( DPID dpid ); void ClearDum( CDPMng* pdp ); static CUserMng* GetInstance( void ); }; #endif // __USER_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 45 ] ] ]
cda68cd513c7312cad3362fd243327d999fe920d
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Complex Mesh/Vertex.cpp
2ac7265a181cda1de9d2efee957eaceae2658190
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
5,362
cpp
/* Vertex.cpp Written by Matthew Fisher ComplexMesh is a complex (edge-based) mesh structure. Vertex represents a vertex in a ComplexMesh. */ #include "..\\..\\Main.h" #include "Vertex.h" void Vertex::LoadVertices() { _Vertices.FreeMemory(); for(UINT i = 0; i < _Triangles.Length(); i++) { for(UINT i2 = 0; i2 < 3; i2++) { Vertex &VertexToConsider = _Triangles[i]->GetVertex(i2); if(VertexToConsider != *this) { bool Add = true; for(UINT i3 = 0; i3 < _Vertices.Length(); i3++) { if(*(_Vertices[i3]) == VertexToConsider) { Add = false; } } if(Add) { _Vertices.PushEnd(&VertexToConsider); } } } } } FullEdge& Vertex::GetSharedEdge(const Vertex &OtherVertex) const { for(UINT i = 0; i < _Triangles.Length(); i++) { if(_Triangles[i]->ContainsVertex(OtherVertex)) { return _Triangles[i]->GetSharedEdge(*this, OtherVertex); } } SignalError("GetSharedEdge failed"); return FullEdge::Invalid; } double Vertex::GaussianCurvature() const { double AngleSum = 0.0f; for(UINT TriangleIndex = 0; TriangleIndex < Triangles().Length(); TriangleIndex++) { Triangle &CurTriangle = *(_Triangles[TriangleIndex]); AngleSum += CurTriangle.GetAngle(*this); } return 2.0 * Math::PI - AngleSum; } double Vertex::ComputeTriangleArea() { double TriangleArea = 0.0f; for(UINT TriangleIndex = 0; TriangleIndex < Triangles().Length(); TriangleIndex++) { TriangleArea += _Triangles[TriangleIndex]->Area(); } return TriangleArea; } Vec3f Vertex::MeanCurvatureNormal() { Vec3f MeanCurvature = Vec3f::Origin; float ConstantTerm = 0.0f; for(UINT EdgeIndex = 0; EdgeIndex < Vertices().Length(); EdgeIndex++) { Vertex &OtherVertex = *(_Vertices[EdgeIndex]); FullEdge &CurEdge = GetSharedEdge(OtherVertex); float ConstantFactor = float(CurEdge.GetCotanTerm()); Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid"); MeanCurvature += ConstantFactor * (_Pos - OtherVertex.Pos()); ConstantTerm += ConstantFactor; } return MeanCurvature / ConstantTerm; } Vec3f Vertex::AreaWeightedNormal() const { Vec3f Normal = Vec3f::Origin; for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = *(_Triangles[TriangleIndex]); Normal += CurTriangle.Area() * CurTriangle.Normal(); } return Vec3f::Normalize(Normal); } Vec3f Vertex::EvaluateVField(const Vector<double> &OneForm) const { Vec3f Result = Vec3f::Origin; float Magnitude = 0.0f; float AreaSum = 0.0f; for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = *(_Triangles[TriangleIndex]); float CurArea = float(CurTriangle.Area()); AreaSum += CurArea; float Ratio1 = 0.0f; float Ratio2 = 0.0f; UINT Index = CurTriangle.GetVertexLocalIndex(*this); if(Index == 1) { Ratio1 = 1.0f; } else if(Index == 2) { Ratio2 = 1.0f; } Vec3f VField = CurTriangle.EvaluateVField(OneForm, Ratio1, Ratio2); Magnitude += CurArea * VField.Length(); Result += CurArea * Vec3f::Normalize(VField); } return Vec3f::Normalize(Result) * Magnitude / AreaSum; } bool Vertex::LocallyManifold() { if(!_Boundary) { return true; } UINT BoundaryEdgeCount = 0; for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex *CurVertex = _Vertices[VertexIndex]; if(GetSharedEdge(*CurVertex).Boundary()) { BoundaryEdgeCount++; if(BoundaryEdgeCount > 2) { return false; } } } return true; } Vec3f Vertex::ComputeLoopSubdivisionPos() { Vec3f Result; UINT n = _Vertices.Length(); if(Boundary()) { Result = 0.75f * _Pos; for(UINT i = 0; i < _Triangles.Length(); i++) { Triangle &CurTriangle = *(_Triangles[i]); for(UINT i2 = 0; i2 < 3; i2++) { FullEdge &CurFullEdge = CurTriangle.GetFullEdge(i2); if(CurFullEdge.Boundary() && CurFullEdge.ContainsVertex(*this)) { Vertex &CurVertex = CurFullEdge.GetOtherVertex(*this); Result += CurVertex.Pos() / 8.0f; } } } } else { float Beta; if(n == 3) { Beta = 3.0f / 16.0f; } else { Beta = 3.0f / (8.0f * n); } Result = (1.0f - n * Beta) * _Pos; for(UINT i = 0; i < n; i++) { Result += _Vertices[i]->Pos() * Beta; } } return Result; }
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 190 ] ] ]
e04cccc15fdcc96a18eff7c803de1bfdeaefffab
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/TeComPrinter/stdafx.cpp
6612505e9d7f7f15e8cfc4a7c07d410c460725df
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
// stdafx.cpp : source file that includes just the standard includes // TeComPrinter.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 5 ] ] ]
2a416bcfee05525bbb8b60060f18b0815a33c2cb
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/app/organizer/notepad_library_api/src/TestNpdApiBlocks.cpp
e6016cd0080af19353f356e32364278274b645dd
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
8,571
cpp
/* * Copyright (c) 2002 - 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ?Description * */ // [INCLUDE FILES] - do not remove #include <e32svr.h> #include <e32cmn.h> #include <f32file.h> #include <StifParser.h> #include <Stiftestinterface.h> #include "TestNpdApi.h" // CONSTANTS //const ?type ?constant_var = ?constant; // LOCAL CONSTANTS AND MACROS //const ?type ?constant_var = ?constant; //#define ?macro_name ?macro_def // ============================= LOCAL FUNCTIONS =============================== // ----------------------------------------------------------------------------- // ?function_name ?description. // ?description // Returns: ?value_1: ?description // ?value_n: ?description_line1 // ?description_line2 // ----------------------------------------------------------------------------- // /* ?type ?function_name( ?arg_type arg, // ?description ?arg_type arg) // ?description { ?code // ?comment // ?comment ?code } */ // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CTestNpdApi::Delete // Delete here all resources allocated and opened from test methods. // Called from destructor. // ----------------------------------------------------------------------------- // void CTestNpdApi::Delete() { } // ----------------------------------------------------------------------------- // CTestNpdApi::RunMethodL // Run specified method. Contains also table of test mothods and their names. // ----------------------------------------------------------------------------- // TInt CTestNpdApi::RunMethodL( CStifItemParser& aItem ) { static TStifFunctionInfo const KFunctions[] = { // Copy this line for every implemented function. // First string is the function name used in TestScripter script file. // Second is the actual implementation member function. ENTRY( "TestFetchTemplate", CTestNpdApi::FetchTemplate ), ENTRY( "TestFetchMemo", CTestNpdApi::FetchMemo ), ENTRY( "TestNoOfTemplates", CTestNpdApi::NoOfTemplates ), ENTRY( "SaveFileAsMemoUsingFileName", CTestNpdApi::SaveFileAsMemoUsingFileName ), ENTRY( "SaveFileAsMemoUsingHandle", CTestNpdApi::SaveFileAsMemoUsingHandle ), ENTRY( "TestAddContent", CTestNpdApi::AddContent ), ENTRY( "Model", CTestNpdApi::Model ), //ADD NEW ENTRY HERE // [test cases entries] - Do not remove }; const TInt count = sizeof( KFunctions ) / sizeof( TStifFunctionInfo ); return RunInternalL( KFunctions, count, aItem ); } //Funcs Defns // ----------------------------------------------------------------------------- // CTestNpdApi::FetchTemplate // ----------------------------------------------------------------------------- TInt CTestNpdApi::FetchTemplate( CStifItemParser& aItem ) { HBufC* retData = CNotepadApi::FetchTemplateL(); if( retData ) { delete retData; return KErrNone; } return KErrGeneral; } // ----------------------------------------------------------------------------- // CTestNpdApi::FetchMemo // ----------------------------------------------------------------------------- TInt CTestNpdApi::FetchMemo( CStifItemParser& aItem ) { HBufC* retData = CNotepadApi::FetchMemoL(); if( retData ) { delete retData; return KErrNone; } return KErrGeneral; } // ----------------------------------------------------------------------------- // CTestNpdApi::NoOfTemplates // ----------------------------------------------------------------------------- TInt CTestNpdApi::NoOfTemplates( CStifItemParser& aItem ) { TInt noOfTmplts = CNotepadApi::NumberOfTemplates(); //By default there will be a 10 templates, so verifying for more than 0 if ( noOfTmplts >= 0 ) { return KErrNone; } return KErrGeneral; } // ----------------------------------------------------------------------------- // CTestNpdApi::SaveFileAsMemoUsingFileName // ----------------------------------------------------------------------------- TInt CTestNpdApi::SaveFileAsMemoUsingFileName( CStifItemParser& aItem ) { TInt err = 0; TInt encoding; aItem.GetNextInt(encoding); //Verifying parameter for correct value if ( (encoding != 0) && (encoding != 1) ) { iLog->Log( _L("Wrong parameter, please give either 0 or 1(encoding)") ); return KErrGeneral; } TFileName fileName; fileName.Append(KExampleFilePath); //If 0, no encoding if(encoding == 0) { TRAP(err, CNotepadApi::SaveFileAsMemoL(fileName)); } else { TRAP(err, CNotepadApi::SaveFileAsMemoL(fileName, KCharacterSetIdentifierIso88591)); } if(err == KErrNone) { return KErrNone; } return err; } // ----------------------------------------------------------------------------- // CTestNpdApi::SaveFileAsMemoUsingHandle // ----------------------------------------------------------------------------- TInt CTestNpdApi::SaveFileAsMemoUsingHandle( CStifItemParser& aItem ) { TInt err = 0; TInt encoding; aItem.GetNextInt(encoding); //Verifying parameter for correct value if ( (encoding != 0) && (encoding != 1) ) { iLog->Log( _L("Wrong parameter, please give either 0 or 1(encoding)") ); return KErrGeneral; } TFileName fileName; fileName.Append( KExampleFilePath ); RFile data; RFs session; User::LeaveIfError( session.Connect() ); CleanupClosePushL( session ); User::LeaveIfError( data.Open( session, fileName, EFileRead ) ); CleanupClosePushL( data ); //If 0, no encoding if(encoding == 0) { TRAP(err, CNotepadApi::SaveFileAsMemoL(data)); } else { TRAP(err, CNotepadApi::SaveFileAsMemoL(data, KCharacterSetIdentifierIso88591)); } CleanupStack::PopAndDestroy( &data ); //data, CleanupStack::PopAndDestroy( &session ); //session if(err == KErrNone) { return KErrNone; } return err; } // ----------------------------------------------------------------------------- // CTestNpdApi::AddContent // ----------------------------------------------------------------------------- TInt CTestNpdApi::AddContent( CStifItemParser& aItem ) { _LIT( KNote, "Saving this text as Notes/Memo"); TRAPD(err, CNotepadApi::AddContentL( KNote )); //Just verifying the error code if(err == KErrNone) { return KErrNone; } return err; } // ----------------------------------------------------------------------------- // CTestNpdApi::Model // ----------------------------------------------------------------------------- TInt CTestNpdApi::Model( CStifItemParser& aItem ) { CNotepadApi* ptrToNpd = CNotepadApi::NewL(); //Not testing the ProbeMemoL() function, but just using to test Model() function. TInt key = 327; ptrToNpd->ProbeMemoL(key); CNotepadModel* retData = ptrToNpd->Model(); //deleting the pointer as it is not used anymore. delete ptrToNpd; //Verifying the pointer, is exist means model() is created properly if( retData ) { return KErrNone; } return KErrGeneral; } // ----------------------------------------------------------------------------- // CTestNpdApi::?member_function // ?implementation_description // (other items were commented in a header). // ----------------------------------------------------------------------------- // /* TInt CTestNpdApi::?member_function( CItemParser& aItem ) { ?code } */ // ========================== OTHER EXPORTED FUNCTIONS ========================= // None // [End of File] - Do not remove
[ "none@none" ]
[ [ [ 1, 284 ] ] ]
13526bc10c736ac2d03f1935fc999a9c57931220
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CCgi.h
13b6a4a0f2ab6700b852293f8f5fd8a98f13cd9f
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
3,200
h
/* CCgi.h Classe base per interfaccia CGI (deriva da CHtml per poter unificare in un unica classe quanto necessario). Luca Piergentili, 29/11/99 [email protected] */ #ifndef _CCGI_H #define _CCGI_H #include "CHtml.h" /* CGI_RESPONSE_TYPE tipo della risposta (Content, Location, header HTTP) */ enum CGI_RESPONSE_TYPE { CONTENT_RESPONSE, LOCATION_RESPONSE, HTTP_RESPONSE }; /* CGI_SUBMISSION_TYPE tipo per modalita' invio dati */ enum CGI_SUBMISSION_TYPE { GET, POST, UNKNOWTYPE }; /* CGI_ENV struttura per le variabili d'ambiente */ struct CGI_ENV { char* variable; char* value; }; /* CGI_FORM struttura per i dati presenti nel form */ #define CGI_MAX_FORM_FIELD 32 #define CGI_MAX_FORM_VALUE 256 struct CGI_FORM { char field[CGI_MAX_FORM_FIELD + 1]; char value[CGI_MAX_FORM_VALUE + 1]; }; // dimensioni buffers #define CGI_MAX_ENVVAR_NAME 64 // nome della variabile #define CGI_MAX_ENVVAR_VALUE 512 // contenuto della variabile #define CGI_MAX_NPH_CODE 32 // codice HTTP per l'header NPH #define CGI_MAX_NPH_EXTRA 1024 // codice extra #define CGI_MAX_COOKIE_SIZE 1024 // cookie #define CGI_MAX_COOKIE_NAME 128 // nome del cookie #define CGI_MAX_COOKIE_VALUE 256 // valore del cookie class CCgi : public CHtml { public: // costruttore/distruttore CCgi(CGI_RESPONSE_TYPE = CONTENT_RESPONSE,const char* = NULL); // tipo risposta, nome file html output ~CCgi(); void SendFile(const char* html_file); // header HTTP virtual void Header (const char* = NULL); void SetNphHeader (const int = 200,const char* = "OK",const char* = NULL); // dati ambiente const char* GetEnvData (char*,int); const char* GetEnvValue (const char*); // dati form const char* GetFormData (char*,int); const char* GetFormField (const char*); // dati const char* GetData (void) {return(cgi_data);} const char* GetDecodedData (void) {return(cgi_decoded_data);} int GetDataLength (void) {return(submission_length);} int GetDataPairs (void) {return(data_pairs);} // cookies const char* SetCookie (const char*,const char*,const char* = NULL,const char* = NULL,const char* = NULL,int = 0); const char* GetCookie (const char*); const char* DeleteCookie (const char*); // tipo richiesta CGI_RESPONSE_TYPE GetResponseType (void) {return(response_type);} CGI_SUBMISSION_TYPE GetSubmissionType (void) {return(submission_type);} private: // conversioni char ConvertHex (char*); void ConvertSpace (char*); void UnescapeUrl (char*); void DecodeData (char*); // form int CountDataPairs (char*); void LoadForm (const char*); int nph_code; char nph_desc[CGI_MAX_NPH_CODE + 1]; char nph_extra[CGI_MAX_NPH_EXTRA + 1]; CGI_RESPONSE_TYPE response_type; int env_size; CGI_ENV* cgi_env; CGI_SUBMISSION_TYPE submission_type; int submission_length; char* cgi_data; char* cgi_decoded_data; int data_pairs; CGI_FORM* cgi_form; char m_szFileName[_MAX_PATH+1]; }; #endif /* _CCGI_H */
[ [ [ 1, 123 ] ] ]
7d87999249a0d1e99263469e398c77b3bd4e9bd3
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Core/flx_octree.cpp
4f7c614018189ffdc652fd0a89f361aa0d068a5d
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
6,961
cpp
/*--------------------------------------------------------------------------- This source file is part of the FluxEngine. Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin) This program is free software. ---------------------------------------------------------------------------*/ //OLD! Not used actually... #include "flx_octree.h" #include "flx_node_transform.h" #include "flx_scene.h" Box boxes; char test2[70]; struct remove_element { bool operator() (Object*& elem) { if(elem->remove) { //delete elem; return true; } return false; } }; Octree::Octree() : _objCount(0), _objects(NULL), _radius(0.0f) { memset(_child, 0, sizeof(_child)); box_offset_tbl[0] = Vector3(-0.5f, -0.5f, -0.5f); box_offset_tbl[1] = Vector3(0.5f, -0.5f, -0.5f); box_offset_tbl[2] = Vector3(-0.5f, 0.5f, -0.5f); box_offset_tbl[3] = Vector3(0.5f, 0.5f, -0.5f); box_offset_tbl[4] = Vector3(-0.5f, -0.5f, 0.5f); box_offset_tbl[5] = Vector3(0.5f, -0.5f, 0.5f); box_offset_tbl[6] = Vector3(-0.5f, 0.5f, 0.5f); box_offset_tbl[7] = Vector3(0.5f, 0.5f, 0.5f); m_bIsInFrustum = true; } Octree::~Octree() { //delete[] _objects; } const bool Octree::build(std::vector<Object*> objects, unsigned int count, unsigned int threshold, unsigned int max_depth, const Box &boxes, unsigned int current_depth) { if(count < threshold || current_depth > max_depth) { _objCount = count; return true; } m_box = boxes; for(unsigned int i = 0; i < 8; i++) { child_obj_counts[i] = 0; } for(unsigned int i = 0; i < count; i++) { if(!(objects[i])) return true; Object &obj = *objects[i]; const Vector3 &c = boxes.center; obj.code = 0; if(obj.m_vPosition.x > c.x) obj.code |= 1; if(obj.m_vPosition.y > c.y) obj.code |= 2; if(obj.m_vPosition.z > c.z) obj.code |= 4; child_obj_counts[obj.code]++; } for(unsigned int i = 0; i < 8; i++) { std::vector<Object*> newList_tmp; if(child_obj_counts[i] <= 0) continue; _child[i] = new Octree; for(unsigned int j = 0; j < count; j++) { if(objects[j]->code == i) { newList_tmp.push_back(objects[j]); } } /*//todo remove duplicate Ns int new_count = 0; for (unsigned int j = 0; j < child_obj_counts[i]; j++) { if(!newList_tmp[j] || !objects[j]) continue; if(objects[j] == newList_tmp[j]) { //newList_tmp[j]->remove = true; } else { //newList.push_back(newList_tmp[j]); } } //newList_tmp.erase(remove_if(newList_tmp.begin(), newList_tmp.end(), remove_element()), newList_tmp.end()); */ Vector3 offset = box_offset_tbl[i] * boxes.radius; Box new_boxes; new_boxes.radius = boxes.radius * 0.5f; new_boxes.center = boxes.center + offset; //recursive call _objCount = newList_tmp.size(); _child[i]->build(newList_tmp, newList_tmp.size(), threshold, max_depth, new_boxes, current_depth+1); newList_tmp.clear(); } return true; } const Box Octree::calc_boxes(std::vector<Object*> objects, unsigned int count) { Box b; Object _min = *objects[0]; Object _max = *objects[0]; for(unsigned int i = 1; i < count; i++) { const Object &o = *objects[i]; if(o.m_vPosition.x < _min.m_vPosition.x) _min.m_vPosition.x = o.m_vPosition.x; if(o.m_vPosition.y < _min.m_vPosition.y) _min.m_vPosition.y = o.m_vPosition.y; if(o.m_vPosition.z < _min.m_vPosition.z) _min.m_vPosition.z = o.m_vPosition.z; if(o.m_vPosition.x > _max.m_vPosition.x) _max.m_vPosition.x = o.m_vPosition.x; if(o.m_vPosition.y > _max.m_vPosition.y) _max.m_vPosition.y = o.m_vPosition.y; if(o.m_vPosition.z > _max.m_vPosition.z) _max.m_vPosition.z = o.m_vPosition.z; } Vector3 radius = _max.m_vPosition - _min.m_vPosition; radius.x *= 0.5f; radius.y *= 0.5f; radius.z *= 0.5f; b.center = _min.m_vPosition + radius ; b.radius = radius.x; if(b.radius < radius.y) b.radius = radius.y; if(b.radius < radius.z) b.radius = radius.z; return b; } const bool Octree::traverse(callback proc, void *data) const { if(!proc(*this, data)) return false; if(!_objCount) { for(unsigned int i = 0; i < 8; i++) { if(!_child[i]) continue; if(!_child[i]->traverse(proc, data)) return false; } } return false; } void Octree::update(double fDeltaTime, std::vector<Object*> objects) { boxes = calc_boxes(objects, maxobjects); build(objects, maxobjects, 32, 32, boxes, 0); } void Octree::draw_cube() { float m_fDepth = this->m_box.radius; float m_fHeight = this->m_box.radius; float m_fWidth = this->m_box.radius; /*dynamic_cast<NodeTransform*>(octree_box_t)->m_v3Translate = Vector3(this->m_box.center.x,this->m_box.center.y,this->m_box.center.z); dynamic_cast<NodeTransform*>(octree_box_t)->RenderOGL(false); */ if(this->m_box.center.x == 0.0f && this->m_box.center.y == 0.0f) return; glDisable(GL_TEXTURE_2D); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glTranslatef(this->m_box.center.x, this->m_box.center.y,this->m_box.center.z); glBegin(GL_QUADS); //front glNormal3f(0, 0, 1.0f); glVertex3f(-m_fWidth , -m_fHeight, m_fDepth); glVertex3f(m_fWidth, -m_fHeight, m_fDepth); glVertex3f(m_fWidth, m_fHeight, m_fDepth); glVertex3f(-m_fWidth, m_fHeight, m_fDepth); //right glNormal3f(1.0f, 0, 0.0f); glVertex3f(m_fWidth , -m_fHeight, m_fDepth); glVertex3f(m_fWidth, -m_fHeight, -m_fDepth); glVertex3f(m_fWidth, m_fHeight, -m_fDepth); glVertex3f(m_fWidth, m_fHeight, m_fDepth); //back glNormal3f(0.0f, 0, -1.0f); glVertex3f(m_fWidth , -m_fHeight, -m_fDepth); glVertex3f(-m_fWidth, -m_fHeight, -m_fDepth); glVertex3f(-m_fWidth, m_fHeight, -m_fDepth); glVertex3f(m_fWidth, m_fHeight, -m_fDepth); //left glNormal3f(-1.0f, 0, 0.0f); glVertex3f(-m_fWidth , -m_fHeight, -m_fDepth); glVertex3f(-m_fWidth, -m_fHeight, m_fDepth); glVertex3f(-m_fWidth, m_fHeight, m_fDepth); glVertex3f(-m_fWidth, m_fHeight, -m_fDepth); //top glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(-m_fWidth , m_fHeight, m_fDepth); glVertex3f(m_fWidth, m_fHeight, m_fDepth); glVertex3f(m_fWidth, m_fHeight, -m_fDepth); glVertex3f(-m_fWidth, m_fHeight, -m_fDepth); //bottom glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(-m_fWidth , m_fHeight, -m_fDepth); glVertex3f(m_fWidth, m_fHeight, -m_fDepth); glVertex3f(m_fWidth, m_fHeight, m_fDepth); glVertex3f(-m_fWidth, m_fHeight, m_fDepth); glEnd(); glTranslatef(-this->m_box.center.x, -this->m_box.center.y,-this->m_box.center.z); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_TEXTURE_2D); for(int i = 0; i < 8; i++) { if(this->_child[i]) this->_child[i]->draw_cube(); } } void Octree::cleanup(unsigned int count) { for(int j = 0; j < 8; j++) { if(!child_obj_counts[j]) continue; if(_child[j]) { _child[j]->cleanup(count); delete _child[j]; } } }
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 270 ] ] ]
968b71f25160a54a853a708d29b307c2b35068f1
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/detail/constructor.hpp
88a0432db6b5a0e758c7f13f82bad795fa88573a
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
3,281
hpp
// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !BOOST_PP_IS_ITERATING # ifndef LUABIND_DETAIL_CONSTRUCTOR_081018_HPP # define LUABIND_DETAIL_CONSTRUCTOR_081018_HPP # include <luabind/object.hpp> # include <luabind/wrapper_base.hpp> # include <boost/preprocessor/iteration/iterate.hpp> # include <boost/preprocessor/iteration/local.hpp> # include <boost/preprocessor/repetition/enum_params.hpp> # include <boost/preprocessor/repetition/enum_binary_params.hpp> namespace luabind { namespace detail { inline void inject_backref( lua_State* L, void*, void* ) {} template <class T> void inject_backref( lua_State* L, T* p, wrap_base* ) { weak_ref( L, 1 ).swap( wrap_access::ref( *p ) ); } template <std::size_t Arity, class T, class Signature> struct construct_aux; template <class T, class Signature> struct construct : construct_aux < mpl::size<Signature>::value - 2, T, Signature > {}; template <class T, class Signature> struct construct_aux<0, T, Signature> { void operator()( argument const& self_ ) const { object_rep* self = touserdata<object_rep>( self_ ); class_rep* cls = self->crep(); std::auto_ptr<T> instance( new T ); inject_backref( self_.interpreter(), instance.get(), instance.get() ); if ( cls->has_holder() ) { cls->construct_holder()( self->ptr(), instance.get() ); } else { self->set_object( instance.get() ); } self->set_destructor( cls->destructor() ); instance.release(); } }; # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (1, LUABIND_MAX_ARITY, <luabind/detail/constructor.hpp>)) # include BOOST_PP_ITERATE() } } // namespace luabind::detail # endif // LUABIND_DETAIL_CONSTRUCTOR_081018_HPP #else // !BOOST_PP_IS_ITERATING # define N BOOST_PP_ITERATION() template <class T, class Signature> struct construct_aux<N, T, Signature> { typedef typename mpl::begin<Signature>::type first; typedef typename mpl::next<first>::type iter0; # define BOOST_PP_LOCAL_MACRO(n) \ typedef typename mpl::next< \ BOOST_PP_CAT(iter,BOOST_PP_DEC(n))>::type BOOST_PP_CAT(iter,n); \ typedef typename BOOST_PP_CAT(iter,n)::type BOOST_PP_CAT(a,BOOST_PP_DEC(n)); # define BOOST_PP_LOCAL_LIMITS (1,N) # include BOOST_PP_LOCAL_ITERATE() void operator()( argument const& self_, BOOST_PP_ENUM_BINARY_PARAMS( N, a, _ ) ) const { object_rep* self = touserdata<object_rep>( self_ ); class_rep* cls = self->crep(); std::auto_ptr<T> instance( new T( BOOST_PP_ENUM_PARAMS( N, _ ) ) ); inject_backref( self_.interpreter(), instance.get(), instance.get() ); if ( cls->has_holder() ) { cls->construct_holder()( self->ptr(), instance.get() ); } else { self->set_object( instance.get() ); } self->set_destructor( cls->destructor() ); instance.release(); } }; #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 115 ] ] ]
86f5813b3ce37a0985e8ea38e78f03ef2ade306b
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/BaseScaleFX.cpp
a9b1b8da3c34686005f8dec8126fe89cce96dd18
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
11,340
cpp
// ----------------------------------------------------------------------- // // // MODULE : BaseScaleFX.cpp // // PURPOSE : BaseScale special FX - Implementation // // CREATED : 5/27/98 // // (c) 1998-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "BaseScaleFX.h" #include "iltclient.h" #include "GameClientShell.h" #include "VarTrack.h" #ifndef __PSX2 #include "winutil.h" #endif extern CGameClientShell* g_pGameClientShell; static VarTrack g_vtRotate; static VarTrack g_vtRotateVel; static VarTrack g_vtRotateLeft; static VarTrack g_vtFaceCamera; // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::Init // // PURPOSE: Init the fx // // ----------------------------------------------------------------------- // LTBOOL CBaseScaleFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!psfxCreateStruct) return LTFALSE; CSpecialFX::Init(psfxCreateStruct); BSCREATESTRUCT* pBaseScale = (BSCREATESTRUCT*)psfxCreateStruct; m_rRot = pBaseScale->rRot; m_vPos = pBaseScale->vPos; m_vVel = pBaseScale->vVel; m_vInitialScale = pBaseScale->vInitialScale; m_vFinalScale = pBaseScale->vFinalScale; m_vInitialColor = pBaseScale->vInitialColor; m_vFinalColor = pBaseScale->vFinalColor; m_bUseUserColors = pBaseScale->bUseUserColors; m_dwFlags = pBaseScale->dwFlags; m_fLifeTime = pBaseScale->fLifeTime; m_fDelayTime = pBaseScale->fDelayTime; m_fInitialAlpha = pBaseScale->fInitialAlpha; m_fFinalAlpha = pBaseScale->fFinalAlpha; m_pFilename = pBaseScale->pFilename; m_pSkinReader = pBaseScale->pSkinReader; m_pRenderStyleReader = pBaseScale->pRenderStyleReader; m_bLoop = pBaseScale->bLoop; m_bAdditive = pBaseScale->bAdditive; m_bMultiply = pBaseScale->bMultiply; m_nType = pBaseScale->nType; m_bRotate = pBaseScale->bRotate; m_bFaceCamera = pBaseScale->bFaceCamera; m_bPausable = pBaseScale->bPausable; m_fRotateVel = GetRandom(pBaseScale->fMinRotateVel, pBaseScale->fMaxRotateVel); m_nRotationAxis = pBaseScale->nRotationAxis; m_nMenuLayer = pBaseScale->nMenuLayer; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::CreateObject // // PURPOSE: Create object associated with the BaseScale // // ----------------------------------------------------------------------- // LTBOOL CBaseScaleFX::CreateObject(ILTClient *pClientDE) { if (!CSpecialFX::CreateObject(pClientDE) || !m_pFilename) return LTFALSE; // Setup the BaseScale... ObjectCreateStruct createStruct; INIT_OBJECTCREATESTRUCT(createStruct); SAFE_STRCPY(createStruct.m_Filename, m_pFilename); if(m_pSkinReader) { m_pSkinReader->CopyList(0, createStruct.m_SkinNames[0], MAX_CS_FILENAME_LEN+1); } if(m_pRenderStyleReader) { m_pRenderStyleReader->CopyList(0, createStruct.m_RenderStyleNames[0], MAX_CS_FILENAME_LEN+1); } // Allow create object to be called to re-init object... if (m_hObject) { // See if we are changing object types... if (GetObjectType(m_hObject) != m_nType) { // Shit, need to re-create object... pClientDE->RemoveObject(m_hObject); m_hObject = LTNULL; } else // Cool, can re-use object... { g_pCommonLT->SetObjectFilenames(m_hObject, &createStruct); g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, m_dwFlags, FLAGMASK_ALL); g_pLTClient->SetObjectPosAndRotation(m_hObject, &m_vPos, &m_rRot); } } // See if we need to create the object... if (!m_hObject) { createStruct.m_ObjectType = m_nType; createStruct.m_Flags = m_dwFlags; createStruct.m_Pos = m_vPos; createStruct.m_Rotation = m_rRot; m_hObject = pClientDE->CreateObject(&createStruct); if (!m_hObject) return LTFALSE; } // Set blend modes if applicable... uint32 dwFlags = 0; // Set up the flags LTBOOL bFog = LTTRUE; if (m_bAdditive) { dwFlags |= FLAG2_ADDITIVE; bFog = LTFALSE; } else if (m_bMultiply) { dwFlags |= FLAG2_MULTIPLY; bFog = LTFALSE; } g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags2, dwFlags, FLAG2_ADDITIVE | FLAG2_MULTIPLY); // Enable/Disable fog as appropriate... g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, (bFog) ? 0 : FLAG_FOGDISABLE, FLAG_FOGDISABLE); return Reset(); } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::Reset // // PURPOSE: Reset the object // // ----------------------------------------------------------------------- // LTBOOL CBaseScaleFX::Reset() { if (!m_hObject) return LTFALSE; LTFLOAT r, g, b, a; if (m_bUseUserColors) { r = m_vInitialColor.x; g = m_vInitialColor.y; b = m_vInitialColor.z; } else { m_pClientDE->GetObjectColor(m_hObject, &r, &g, &b, &a); } m_pClientDE->SetObjectScale(m_hObject, &m_vInitialScale); m_pClientDE->SetObjectColor(m_hObject, r, g, b, m_fInitialAlpha); m_fStartTime = m_fDelayTime; m_fEndTime = m_fStartTime + m_fLifeTime; m_fElapsedTime = 0.0f; if (m_vVel.x != 0.0f || m_vVel.y != 0.0 || m_vVel.z != 0.0) { InitMovingObject(&m_movingObj, m_vPos, m_vVel); m_movingObj.m_dwPhysicsFlags |= MO_NOGRAVITY; } if (m_nType == OT_MODEL) { m_pClientDE->SetModelLooping(m_hObject, m_bLoop != LTFALSE); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::Update // // PURPOSE: Update the BaseScale // // ----------------------------------------------------------------------- // LTBOOL CBaseScaleFX::Update() { if(!m_hObject || !m_pClientDE) return LTFALSE; //handle updating the elapsed time float fFrameTime = m_pClientDE->GetFrameTime(); //see if we are paused though if(m_bPausable && g_pGameClientShell->IsServerPaused()) fFrameTime = 0.0f; m_fElapsedTime += fFrameTime; if (m_fElapsedTime > m_fEndTime) { return LTFALSE; } else if (m_fElapsedTime < m_fStartTime) { g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, 0, FLAG_VISIBLE); return LTTRUE; // not yet... } else { g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, FLAG_VISIBLE, FLAG_VISIBLE); } float fElapsedFromStart = m_fElapsedTime - m_fStartTime; if (m_fFinalAlpha != m_fInitialAlpha || m_vInitialColor.x != m_vFinalColor.x || m_vInitialColor.y != m_vFinalColor.y || m_vInitialColor.z != m_vFinalColor.z) { UpdateAlpha(fElapsedFromStart); } if (m_vInitialScale.x != m_vFinalScale.x || m_vInitialScale.y != m_vFinalScale.y || m_vInitialScale.z != m_vFinalScale.z) { UpdateScale(fElapsedFromStart); } if (m_vVel.x != 0.0f || m_vVel.y != 0.0 || m_vVel.z != 0.0) { UpdatePos(fElapsedFromStart); } UpdateRot(fElapsedFromStart); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::UpdateAlpha // // PURPOSE: Update the BaseScale alpha // // ----------------------------------------------------------------------- // void CBaseScaleFX::UpdateAlpha(LTFLOAT fTimeDelta) { if(!m_hObject || !m_pClientDE) return; LTFLOAT fAlpha = m_fInitialAlpha + (fTimeDelta * (m_fFinalAlpha - m_fInitialAlpha) / m_fLifeTime); LTVector vColor; if (m_bUseUserColors) { vColor.x = m_vInitialColor.x + (fTimeDelta * (m_vFinalColor.x - m_vInitialColor.x) / m_fLifeTime); vColor.y = m_vInitialColor.y + (fTimeDelta * (m_vFinalColor.y - m_vInitialColor.y) / m_fLifeTime); vColor.z = m_vInitialColor.z + (fTimeDelta * (m_vFinalColor.z - m_vInitialColor.z) / m_fLifeTime); //m_pClientDE->CPrint("Color = (%.2f, %.2f, %.2f), Alpha = %.2f", vColor.x, vColor.y, vColor.z, fAlpha); } else { LTFLOAT a; m_pClientDE->GetObjectColor(m_hObject, &(vColor.x), &(vColor.y), &(vColor.z), &a); } m_pClientDE->SetObjectColor(m_hObject, vColor.x, vColor.y, vColor.z, fAlpha); } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::UpdateScale // // PURPOSE: Update the BaseScale alpha // // ----------------------------------------------------------------------- // void CBaseScaleFX::UpdateScale(LTFLOAT fTimeDelta) { if(!m_hObject || !m_pClientDE) return; LTVector vScale; vScale.Init(); vScale.x = m_vInitialScale.x + (fTimeDelta * (m_vFinalScale.x - m_vInitialScale.x) / m_fLifeTime); vScale.y = m_vInitialScale.y + (fTimeDelta * (m_vFinalScale.y - m_vInitialScale.y) / m_fLifeTime); vScale.z = m_vInitialScale.z + (fTimeDelta * (m_vFinalScale.z - m_vInitialScale.z) / m_fLifeTime); m_pClientDE->SetObjectScale(m_hObject, &vScale); } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::UpdatePos // // PURPOSE: Update the BaseScale's pos // // ----------------------------------------------------------------------- // void CBaseScaleFX::UpdatePos(LTFLOAT fTimeDelta) { if(!m_hObject || !m_pClientDE) return; if (m_movingObj.m_dwPhysicsFlags & MO_RESTING) return; LTVector vNewPos; if (UpdateMovingObject(LTNULL, &m_movingObj, vNewPos)) { m_movingObj.m_vLastPos = m_movingObj.m_vPos; m_movingObj.m_vPos = vNewPos; g_pLTClient->SetObjectPos(m_hObject, &vNewPos); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBaseScaleFX::UpdateRot // // PURPOSE: Update the BaseScale's rotation // // ----------------------------------------------------------------------- // void CBaseScaleFX::UpdateRot(LTFLOAT fTimeDelta) { if (!m_bRotate || !m_hObject) return; LTVector vU, vR, vF, vAxis; LTRotation rRot; g_pLTClient->GetObjectRotation(m_hObject, &rRot); vU = rRot.Up(); vR = rRot.Right(); vF = rRot.Forward(); // See if this is a rotatable sprite and we want it to face the // camera... if (m_bFaceCamera) { uint32 dwFlags; g_pCommonLT->GetObjectFlags(m_hObject, OFT_Flags, dwFlags); if (dwFlags & FLAG_ROTATEABLESPRITE) { // Okay, make sure we're facing the camera... HOBJECT hCamera = g_pPlayerMgr->GetCamera(); if (hCamera) { LTVector vCamPos, vPos; g_pLTClient->GetObjectPos(hCamera, &vCamPos); g_pLTClient->GetObjectPos(m_hObject, &vPos); vF = vCamPos - vPos; rRot = LTRotation(vF, vU); } } } if (m_nType == OT_MODEL && m_nRotationAxis == 1) { vAxis = vU; } else if (m_nType == OT_MODEL && m_nRotationAxis == 2) { vAxis = vR; } else vAxis = vF; rRot.Rotate(vAxis, m_fRotateVel * (fTimeDelta - (m_fElapsedTime - m_fStartTime))); g_pLTClient->SetObjectRotation(m_hObject, &rRot); } void CBaseScaleFX::AdjustScale(LTFLOAT fScaleMultiplier) { VEC_MULSCALAR(m_vInitialScale, m_vInitialScale, fScaleMultiplier); VEC_MULSCALAR(m_vFinalScale, m_vFinalScale, fScaleMultiplier); m_pClientDE->SetObjectScale(m_hObject, &m_vInitialScale); }
[ [ [ 1, 417 ] ] ]
e07f962d6480a75b7501aadec2a8ec33ddf28cb2
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/neteasebook/main.cpp
b9b5d3889bbc8a1d96f9f2fed5a1c0d7829221aa
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
#include <QtCore> #include "qneteasebookdownload.h" int main(int argc, char *argv[]) { if(argc<2){ qDebug()<<"Input Book Index URL."; return 0; } QCoreApplication app(argc, argv); QNeteaseBookDownload downloader(QString(argv[1]),"."); //downloader.setProxy("172.28.9.151",8080); downloader.download(); app.connect(&downloader, SIGNAL(finished()), &app, SLOT(quit())); return app.exec(); }
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 17 ] ] ]
36773029d1e172cba42080f2e60a54ed22df33fb
b6a6fa4324540b94fb84ee68de3021a66f5efe43
/Duplo/include/PackedMessage.h
452b34086e946d8978cd8e4fb1368b6aa0a53a34
[]
no_license
southor/duplo-scs
dbb54061704f8a2ec0514ad7d204178bfb5a290e
403cc209039484b469d602b6752f66b9e7c811de
refs/heads/master
2021-01-20T10:41:22.702098
2010-02-25T16:44:39
2010-02-25T16:44:39
34,623,992
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef _PACKED_MESSAGE_ #define _PACKED_MESSAGE_ #include "BaseMessage.h" #include "Dup_Declares.h" namespace Dup { class PackedMessage : public BaseMessage { private: dup_moduleid moduleId; dup_pos sendMoment; public: PackedMessage(dup_pos sendMoment, dup_moduleid moduleID, dup_uint16 size, dup_message *msg, dup_uint8 format = 0x00); dup_moduleid getModuleId(); dup_pos getSendMoment(); }; }; #endif #ifndef _PACKED_MESSAGE_DEC_ #define _PACKED_MESSAGE_DEC_ namespace Dup { PackedMessage::PackedMessage(dup_pos sendMoment, dup_moduleid moduleId, dup_uint16 size, dup_message *msg, dup_uint8 format) : BaseMessage(msg, size, format) { this->moduleId = moduleId; this->sendMoment = sendMoment; } dup_moduleid PackedMessage::getModuleId() { return moduleId; } dup_pos PackedMessage::getSendMoment() { return sendMoment; } }; #endif
[ "t.soderberg8@2b3d9118-3c8b-11de-9b50-8bb2048eb44c" ]
[ [ [ 1, 65 ] ] ]
50f0c7ff45145e900d92054eb8f9c41843cd9256
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/__ffl_dump/source/ffl_file.cpp
b8c8cb8cd13c54833c640fd59634bcbdfcb63713
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,997
cpp
#include "../include/ffl_file.h" ffl_file::ffl_file() { handle_ = INVALID_HANDLE_VALUE; } ffl_file::~ffl_file() { close(); } bool ffl_file::create( const ffl_tchar_t * name, unsigned int access_mode /* = GENERIC_READ | GENERIC_WRITE */, unsigned int share_mode /* = FILE_SHARE_READ */ ) { FFL_ASSERT( opened() == false ); handle_ = ::CreateFile( name, access_mode, share_mode, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if( handle_ == INVALID_HANDLE_VALUE ) { return false; } return true; } bool ffl_file::open( const ffl_tchar_t * name, unsigned int access_mode /* = GENERIC_READ | GENERIC_WRITE */, unsigned int share_mode /* = FILE_SHARE_READ */ ) { FFL_ASSERT( opened() == false ); handle_ = ::CreateFile( name, access_mode, share_mode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if( handle_ == INVALID_HANDLE_VALUE ) { return false; } return true; } void ffl_file::close() { if( handle_ != INVALID_HANDLE_VALUE ) { FFL_VERIFY( ::CloseHandle( handle_ ) != FALSE ); handle_ = INVALID_HANDLE_VALUE; } return; } bool ffl_file::opened() { return ( handle_ != INVALID_HANDLE_VALUE ); } size_t ffl_file::read( void * buffer, size_t buffer_size ) { FFL_ASSERT( opened() == true ); FFL_ASSERT( buffer_size != NULL ); DWORD read_size = 0; if( opened() == true && buffer != NULL ) { if( ::ReadFile( handle_, buffer, static_cast< DWORD >( buffer_size ), &read_size, NULL ) == FALSE ) { read_size = 0; } } return ( read_size ); } size_t ffl_file::write( const void * buffer, size_t write_size ) { FFL_ASSERT( opened() == true ); FFL_ASSERT( buffer != NULL ); DWORD written_size = 0; if( opened() == true ) { if( ::WriteFile( handle_, buffer, static_cast< DWORD >( write_size ), &written_size, NULL ) == FALSE ) { written_size = 0; } } return ( written_size ); } ffl_int64_t ffl_file::seek( ffl_int64_t offset, int origin ) { FFL_ASSERT( opened() == true ); LARGE_INTEGER large; large.QuadPart = 0; if( opened() == true ) { large.QuadPart = offset; large.LowPart = ::SetFilePointer( handle_, large.LowPart, &large.HighPart, origin ); if( large.LowPart == INVALID_SET_FILE_POINTER && ::GetLastError() != NO_ERROR ) { large.QuadPart = INVALID_SET_FILE_POINTER; } } return ( large.QuadPart ); } bool ffl_file::flush() { FFL_ASSERT( opened() == true ); if( opened() == true ) { if( ::FlushFileBuffers( handle_ ) == FALSE ) { return false; } return true; } return false; } ffl_uint64_t ffl_file::size() { FFL_ASSERT( opened() == true ); ULARGE_INTEGER large; large.QuadPart = 0; if( opened() == true ) { large.LowPart = ::GetFileSize( handle_, &large.HighPart ); if( large.LowPart == INVALID_SET_FILE_POINTER && ::GetLastError() != NO_ERROR ) { large.QuadPart = 0; } } return ( large.QuadPart ); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 149 ] ] ]
c67397fe6403ce00ef85ce54f295e9b6da30e940
e54016b03aa042b8d702f4196a484365f24697db
/arkanoid.cpp
0e974dedcfb9c910318f6714817c3c0762a94dd0
[]
no_license
chaozik1337/qtarkanoid
80f3d40e030e21e884568ff9adcbab27366aa8bb
188106e35408d4d74ad24facc6c87685e9a64bef
refs/heads/master
2021-01-10T19:16:14.943229
2010-11-19T04:45:09
2010-11-19T04:45:09
34,384,578
0
0
null
null
null
null
UTF-8
C++
false
false
8,712
cpp
#include "arkanoid.h" #include "mainwindow.h" #include <QPainter> //#include <QApplication> Arkanoid::Arkanoid(QWidget *parent) : QWidget(parent) { x = 0; this->score = 0; this->lives = 3; this->level = 1; gameOver = FALSE; gameWon = FALSE; paused = FALSE; gameStarted = FALSE; paddle = new Paddle(); ball = new Ball(); //block = new Block(this, 1, this->level, 0, 0); lvl = new Level(this, this->level); //startGame(); setWindowTitle("qtArkanoid"); setMouseTracking(true); setGameArea(440, 570); this->setFixedSize(gameAreaWidth, gameAreaHeight); this->setPalette(QPalette(Qt::black)); this->setAutoFillBackground(true); hitCount = 0; } Arkanoid::~Arkanoid() { delete paddle; } bool Arkanoid::checkCollision() { bool ret = false; if (ball->XChanged) { if (ball->nextPosX > gameAreaWidth - 6) //ball hits right wall { ball->speedX = -1 * ball->speedX; ball->posX = gameAreaWidth - 6; ball->nextPosX = ball->posX; ret = true; } else if (ball->nextPosX < 6) //ball hits left wall { ball->speedX = -1 * ball->speedX; ball->posX = 6; ball->nextPosX = ball->posX; ret = true; } else //ball doesn't hit walls { ret = checkBlockCollision(true); } } if (ball->YChanged) { //check if ball hit top if (ball->nextPosY < 6) { ball->speedY = -1 * ball->speedY; ball->posY = 6; ball->nextPosY = ball->posY; ret = true; } //if ball hit paddle else if (floor(ball->nextPosY) >= 500 - 6 && floor(ball->nextPosY) < 500 - 6 + 5) { hitCount++; if (floor(ball->posX) >= paddle->getPosX() - 40 - 6 && floor(ball->posX) <= paddle->getPosX() + 40 + 6) { if (ball->speedY > 0) { double dif = paddle->getPosX() - floor(ball->posX); if (dif > 0) //ball hits left side of paddle { if (dif > 40) { ball->speedX = -1 * ball->speedResultant / sqrt(1 + pow(tan((90.0 - 80.0) / 180.0 * PI),2)); ball->speedY = -1 * sqrt(pow(ball->speedResultant,2) - pow(ball->speedX,2)); } else { ball->speedX = -1 * ball->speedResultant / sqrt(1 + pow(tan((90.0 - dif * 2.0) / 180.0 * PI),2)); ball->speedY = -1 * sqrt(pow(ball->speedResultant,2) - pow(ball->speedX,2)); } ball->posY = floor(ball->nextPosY); ret = true; } if (dif < 0) //ball hits right side of paddle { if (dif < -40) { ball->speedX = ball->speedResultant / sqrt(1 + pow(tan((90.0 - 80.0) / 180.0 * PI),2)); ball->speedY = -1 * sqrt(pow(ball->speedResultant,2) - pow(ball->speedX,2)); } else { ball->speedX = ball->speedResultant / sqrt(1 + pow(tan((90.0 - qAbs(dif) * 2) / 180.0 * PI),2)); ball->speedY = -1 * sqrt(pow(ball->speedResultant,2) - pow(ball->speedX,2)); } } if (dif == 0) //ball hits center of paddle { ball->speedX = 0; ball->speedY = ball->speedResultant; } } } } //testing only else if (ball->nextPosY > 570 - 6) { lives = lives - 1; if (lives == 0) { this->stopGame(); } ball->speedY = -1 * ball->speedY; ball->posY = 570 - 6; ball->nextPosY = ball->posY; ret = true; } //check if ball hits blocks else { ret = checkBlockCollision(false); } } return ret; } bool Arkanoid::checkBlockCollision(bool X) { int closestBlock = -1; int smallestDif = 100; int dif = -1; bool ret = false; if (!X) //Y { for (int n = 0; n < lvl->blocks.count(); n++) { dif = -1; if (floor(ball->posX) >= lvl->blocks[n]->x1 - 6 && floor(ball->posX) <= lvl->blocks[n]->x2 + 6) { if (floor(ball->nextPosY) <= lvl->blocks[n]->y2 + 6 && floor(ball->nextPosY) >= lvl->blocks[n]->y1 - 6) { dif = qAbs(lvl->blocks[n]->x1 + 20 - ball->posX); if (dif < smallestDif) { smallestDif = dif; closestBlock = n; } } } } if (closestBlock != -1) { if (ball->speedY > 0) { ball->posY = lvl->blocks[closestBlock]->y1 - 6; } else { ball->posY = lvl->blocks[closestBlock]->y2 + 6; } ball->speedY = -1 * ball->speedY; ball->nextPosY = ball->posY; if (checkVictory(closestBlock)) { victory(); } ret = true; } else { ball->posY = floor(ball->nextPosY); } } else //X { for (int n = 0; n < lvl->blocks.count(); n++) { dif = -1; if (floor(ball->nextPosX) >= lvl->blocks[n]->x1 - 6 && floor(ball->nextPosX) <= lvl->blocks[n]->x2 + 6) { if (floor(ball->posY) <= lvl->blocks[n]->y2 + 6 && floor(ball->posY) >= lvl->blocks[n]->y1 - 6) { dif = qAbs(lvl->blocks[n]->x1 + 20 - ball->posX); if (dif < smallestDif) { smallestDif = dif; closestBlock = n; } } } } if (closestBlock != -1) { if (ball->speedX > 0) { ball->posX = lvl->blocks[closestBlock]->x1 - 6; } else { ball->posX = lvl->blocks[closestBlock]->x2 + 6; } ball->speedX = -1 * ball->speedX; ball->nextPosX = ball->posX; if (checkVictory(closestBlock)) { victory(); } ret = true; } else { ball->posX = floor(ball->nextPosX); } } return ret; } bool Arkanoid::checkVictory(int n) { this->score = this->score + this->lvl->blocks[n]->score; this->lvl->blocks.removeAt(n); if (this->lvl->blocks.count() == 0) { return true; } return false; } int Arkanoid::getGameAreaW() { return gameAreaWidth; } int Arkanoid::getGameAreaH() { return gameAreaHeight; } void Arkanoid::setGameArea(int width, int height) { if (height > 0) { gameAreaHeight = height; } if (width > 0) { gameAreaWidth = width; } } void Arkanoid::paintEvent(QPaintEvent *event) { QPainter painter(this); if (gameOver) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Game Over"); painter.setFont(font); int h = height(); int w = width(); painter.translate(QPoint(w/2, h/2)); painter.drawText(-textWidth/2, 0, "Game Over"); } else if(gameWon) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Victory"); painter.setFont(font); int h = height(); int w = width(); painter.translate(QPoint(w/2, h/2)); painter.drawText(-textWidth/2, 0, "Victory"); } else if(!paused) { painter.drawImage(paddle->getRect(), paddle->getImage()); painter.drawImage(ball->posX - 6, ball->posY - 6, ball->getImage()); //painter.drawImage(block->getRect(), block->getImage()); for (int n = 0; n < this->lvl->blocks.count(); n++) { painter.drawImage(this->lvl->blocks[n]->getRect(), this->lvl->blocks[n]->getImage()); } } } void Arkanoid::mouseMoveEvent(QMouseEvent *event) { if (gameStarted == true && paused == false) { QPoint pos = event->pos(); paddle->movePaddle(pos.x(), gameAreaWidth); //ball->moveBall(pos.x(), pos.y(), gameAreaWidth, gameAreaHeight); } } void Arkanoid::startGame() { if (!gameStarted) { paddle->resetState(); gameOver = FALSE; gameWon = FALSE; gameStarted = TRUE; timerId = startTimer(10); } } bool Arkanoid::isPaused() { if (paused) { return true; } return false; } bool Arkanoid::isGameStarted() { if (gameStarted) { return true; } return false; } void Arkanoid::pauseGame() { if (paused) { timerId = startTimer(10); paused = FALSE; } else { paused = TRUE; killTimer(timerId); } } void Arkanoid::stopGame() { killTimer(timerId); gameOver = TRUE; gameStarted = FALSE; } void Arkanoid::victory() { killTimer(timerId); gameWon = TRUE; gameStarted = FALSE; }
[ "valtteri.ahlstrom@335dc8c3-04d5-5766-ad82-7559d14b8888" ]
[ [ [ 1, 394 ] ] ]
4f47c15618297ce79ad81a289cba400c1382e3bc
b8abaaf2f7a1f94efe3bbc0d14ca49228471b43f
/libs/Box2D/Dynamics/b2Fixture.cpp
e20b07be7f52bf4794056e5d9417d1c4fb5a86f6
[ "Zlib" ]
permissive
julsam/Momoko-Engine
e8cf8a2ad4de6b3925c8c85dc66272e7602e7e73
7503a2a81d53bf569eb760c890158d4f38d9baf9
refs/heads/master
2021-01-22T12:08:41.642354
2011-04-12T11:12:21
2011-04-12T11:12:21
1,494,202
2
0
null
null
null
null
UTF-8
C++
false
false
4,112
cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b2Fixture.h" #include "Contacts/b2Contact.h" #include "../Collision/Shapes/b2CircleShape.h" #include "../Collision/Shapes/b2PolygonShape.h" #include "../Collision/b2BroadPhase.h" #include "../Collision/b2Collision.h" #include "../Common/b2BlockAllocator.h" b2Fixture::b2Fixture() { m_userData = NULL; m_body = NULL; m_next = NULL; m_proxyId = b2BroadPhase::e_nullProxy; m_shape = NULL; m_density = 0.0f; } b2Fixture::~b2Fixture() { b2Assert(m_shape == NULL); b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); } void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) { m_userData = def->userData; m_friction = def->friction; m_restitution = def->restitution; m_body = body; m_next = NULL; m_filter = def->filter; m_isSensor = def->isSensor; m_shape = def->shape->Clone(allocator); m_density = def->density; } void b2Fixture::Destroy(b2BlockAllocator* allocator) { // The proxy must be destroyed before calling this. b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); // Free the child shape. switch (m_shape->m_type) { case b2Shape::e_circle: { b2CircleShape* s = (b2CircleShape*)m_shape; s->~b2CircleShape(); allocator->Free(s, sizeof(b2CircleShape)); } break; case b2Shape::e_polygon: { b2PolygonShape* s = (b2PolygonShape*)m_shape; s->~b2PolygonShape(); allocator->Free(s, sizeof(b2PolygonShape)); } break; default: b2Assert(false); break; } m_shape = NULL; } void b2Fixture::CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf) { b2Assert(m_proxyId == b2BroadPhase::e_nullProxy); // Create proxy in the broad-phase. m_shape->ComputeAABB(&m_aabb, xf); m_proxyId = broadPhase->CreateProxy(m_aabb, this); } void b2Fixture::DestroyProxy(b2BroadPhase* broadPhase) { if (m_proxyId == b2BroadPhase::e_nullProxy) { return; } // Destroy proxy in the broad-phase. broadPhase->DestroyProxy(m_proxyId); m_proxyId = b2BroadPhase::e_nullProxy; } void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) { if (m_proxyId == b2BroadPhase::e_nullProxy) { return; } // Compute an AABB that covers the swept shape (may miss some rotation effect). b2AABB aabb1, aabb2; m_shape->ComputeAABB(&aabb1, transform1); m_shape->ComputeAABB(&aabb2, transform2); m_aabb.Combine(aabb1, aabb2); b2Vec2 displacement = transform2.position - transform1.position; broadPhase->MoveProxy(m_proxyId, m_aabb, displacement); } void b2Fixture::SetFilterData(const b2Filter& filter) { m_filter = filter; if (m_body == NULL) { return; } // Flag associated contacts for filtering. b2ContactEdge* edge = m_body->GetContactList(); while (edge) { b2Contact* contact = edge->contact; b2Fixture* fixtureA = contact->GetFixtureA(); b2Fixture* fixtureB = contact->GetFixtureB(); if (fixtureA == this || fixtureB == this) { contact->FlagForFiltering(); } edge = edge->next; } } void b2Fixture::SetSensor(bool sensor) { m_isSensor = sensor; }
[ [ [ 1, 163 ] ] ]
9c921b248246b975a97d748961f9408016e67242
02ffe34054155a76c1e4612d4f0772c796bedb77
/TCC_NDS/flib/source/FPalette.cpp
5642cf5af5840e3206f875bbbaebc8038ff44ef6
[]
no_license
btuduri/programming-nds
5fe58bbb768c517ae2ae2b07e6df9b13376a276e
81e6b9e0d4afaba1178b1fb0d8e4b000c5fdaf22
refs/heads/master
2020-06-09T07:21:31.930053
2009-12-08T17:39:17
2009-12-08T17:39:17
32,271,835
0
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
#include "FLib.h" FPalette::FPalette(u16* palette) { this->palette = palette; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// u16 FPalette::GetColor(int index) { return palette[index]; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FPalette::SetColor(int index, u16 color) { palette[index] = color; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FPalette::Load(const void* memory) { dmaCopy(memory, palette, 510); }
[ "thiagoauler@f17e7a6a-8b71-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 33 ] ] ]
39410a4ba586678aeba8ec5f4acccdeedfa19bbc
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Serialize/Version/hkVersionUtil.h
d6f6449c04dd0689b9664f0d7d0fbe56c09b4a34
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,344
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_SERIALIZE_VERSIONUTIL_H #define HK_SERIALIZE_VERSIONUTIL_H #include <Common/Serialize/Version/hkVersionRegistry.h> class hkObjectUpdateTracker; class hkClassNameRegistry; class hkPackfileReader; /// Versioning utility functions and structures. namespace hkVersionUtil { /// Get the current sdk version as written in packfiles. const char* HK_CALL getCurrentVersion(); /// Copies the old named member to the new named member. /// The members must have identical sizes. void HK_CALL renameMember( hkVariant& oldObj, const char* oldName, hkVariant& newObj, const char* newName ); /// Copy defaults for new members. /// For each member in newClass which is not in oldClass and which /// has a specified default, copy it in into obj. void HK_CALL copyDefaults( void* obj, const hkClass& oldClass, const hkClass& newClass ); /// Find variants in obj and update their class pointers. /// For each variant member in obj, update its class to the class /// from the given registry. /// ie. obj.m_variant.m_class = reg.getClassByName( obj.m_variant.m_class->getName() ) void HK_CALL updateVariantClassPointers( void* obj, const hkClass& klass, hkClassNameRegistry& reg, int numObj=1 ); /// Utility function to recompute member offsets. void HK_CALL recomputeClassMemberOffsets( hkClass*const* classes, int classVersion ); /// Low level interface to versioning. /// Apply the updateDescriptions to each object in objectsInOut. /// Note that the size and ordering of objectsInOut may change. hkResult HK_CALL updateSingleVersion( hkArray<hkVariant>& objectsInOut, hkObjectUpdateTracker& tracker, const hkVersionRegistry::UpdateDescription& updateDescription, const hkClassNameRegistry* newClassRegistry ); /// Search for and apply a sequence of updates. /// Given fromVersion and toVersion, search for a sequence /// of updates which will convert between them. Calls /// updateSingleVersion for each step in the sequence. hkResult HK_CALL updateBetweenVersions( hkArray<hkVariant>& objectsInOut, hkObjectUpdateTracker& tracker, const hkVersionRegistry& reg, const char* fromVersion, const char* toVersion = HK_NULL ); /// Update the packfile contents to the latest version in reg. /// Usually the the hkVersionRegistry singleton is used for reg. /// Updating will fail if a binary packfile has been stripped of its /// table of contents. Xml packfiles can always be updated. hkResult HK_CALL updateToCurrentVersion( hkPackfileReader& reader, const hkVersionRegistry& reg ); /// Utility function to generate extern list of classes of current version. /// The classes extern declaration is output into provided hkOStream. hkResult HK_CALL generateCppExternClassList(hkOstream& os, const char* headerMacro, const hkClass*const* classesToGenerate, const char* registryVariableName); /// Utility function to generate list of classes of current version. /// The classes are generated as static data in C++ format and output /// into provided hkOStream. The pch file name may be provided for /// convenience, so the output can be used as source file in project /// without modifications. hkResult HK_CALL generateCppClassList(hkOstream& os, const hkClass*const* classesToGenerate, const char* pchfilename, const char* registryVariableName); } class CollectClassDefinitions { public: CollectClassDefinitions(const hkArray<const hkClass*>& originalClassList, hkPointerMap<const hkClassEnum*, char*>& enumNameFromPointer, hkStringMap<hkBool32>& enumDoneFlagFromName); const hkString& getClassExternList() const; const hkString& getClassDefinitionList() const; void defineClassClass(const hkClass& klass); private: const hkClassEnum* m_classMemberEnumType; const hkArray<const hkClass*>& m_originalClassList; hkString m_classExternList; hkString m_classDefinitionList; hkPointerMap<const hkClassEnum*, char*>& m_enumNameFromPointer; hkStringMap<hkBool32>& m_enumDoneFlagFromName; hkStringMap<hkBool32> m_doneClasses; }; #endif // HK_SERIALIZE_VERSIONUTIL_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 120 ] ] ]
464162df4b5128c0413981ce42b7235947e6c830
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Query/Collector/PointCollector/hkpClosestCdPointCollector.h
5091760a119b46091eafacbdd31b80105e887c89
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,910
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_CLOSEST_CD_POINT_COLLECTOR_H #define HK_CLOSEST_CD_POINT_COLLECTOR_H #include <Physics/Collide/Agent/Query/hkpCdPointCollector.h> #include <Physics/Collide/Query/Collector/PointCollector/hkpRootCdPoint.h> /// This class collects only the closest contact point returned in addCdPoint() callbacks /// Please read the notes for hkpCdPointCollector for information about how these collectors are used /// Note: As this class cannot store hkpCdBody information, which may be just temporary, it converts the /// hkpCdBody into a hkpRootCdPoint. class hkpClosestCdPointCollector : public hkpCdPointCollector { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_AGENT, hkpClosestCdPointCollector); /// Constructor calls reset. inline hkpClosestCdPointCollector(); /// Resets the early out condition, /// You must call this function if you want to reuse an object of this class. inline void reset(); inline virtual ~hkpClosestCdPointCollector(); /// Returns true, if this class has collected at least one hit inline hkBool hasHit( ) const; /// Get the full hit information. inline const hkpRootCdPoint& getHit() const; /// Returns only the physical hit information: position, normal, distance<br> /// This is identical to getHit().m_contact inline const hkContactPoint& getHitContact() const; protected: // this implementation keeps track of the hkpCdPoint with the smallest distance virtual void addCdPoint( const hkpCdPoint& pointInfo ) ; protected: hkpRootCdPoint m_hitPoint; }; #include <Physics/Collide/Query/Collector/PointCollector/hkpClosestCdPointCollector.inl> #endif // HK_CLOSEST_CD_POINT_COLLECTOR_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 73 ] ] ]
76f09ba284d651f797faee5fce4cd1306779adf4
a51ac532423cf58c35682415c81aee8e8ae706ce
/CameraAPI/BMP.cpp
6686ebf753f24965811d4ea01d792b3d3221b44e
[]
no_license
anderslindmark/PickNPlace
b9a89fb2a6df839b2b010b35a0c873af436a1ab9
00ca4f6ce2ecfeddfea7db5cb7ae8e9d0023a5e1
refs/heads/master
2020-12-24T16:59:20.515351
2008-05-25T01:32:31
2008-05-25T01:32:31
34,914,321
1
0
null
null
null
null
UTF-8
C++
false
false
3,322
cpp
#include "BMP.h" #include <fstream> #include <stdexcept> #include "log.h" namespace camera { namespace util { /* struct BITMAPFILEHEADER { unsigned short bfType; unsigned long bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned long bfOffBits; }; struct BITMAPINFOHEADER { unsigned long biSize; long biWidth; long biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned long biCompression; unsigned long biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; unsigned long biClrUsed; unsigned long biClrImportant; }; */ // Because the datatype char (1 byte) and short (2 bytes) is saved as a long (4 bytes) all char have been removed and all short have been replaced struct BMPHeader { unsigned long bfSize; unsigned long bfReserved1And2; unsigned long bfOffBits; }; struct BMPInfoHeader { unsigned long biSize; long biWidth; long biHeight; unsigned long biPlanesAndBitCount; unsigned long biCompression; unsigned long biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; unsigned long biClrUsed; unsigned long biClrImportant; }; Image *loadBMP(const char *filename) { LOG_TRACE("loadBMP()"); LOG_ERROR("loadBMP not implemented! Returning NULL"); return NULL; } void saveBMP(const char *filename, const Image *image) { LOG_TRACE("saveBMP()"); if(image == NULL) { LOG_ERROR("saveBMP: image is NULL "); throw std::runtime_error("image is NULL"); } if(image->getFormat() != Image::FORMAT_RGB32) { LOG_ERROR("saveBMP: Trying to save ImageBuffer with format " << image->getFormat()); throw std::runtime_error("The only supported format is RGB32"); } int width = image->getWidth(); int height = image->getHeight(); std::ofstream file(filename, std::ios_base::out | std::ios_base::binary); BMPHeader header; header.bfSize = 54 + image->getBufferSize(); // TODO: Check header.bfReserved1And2 = 0; header.bfOffBits = 54; // TODO: Check BMPInfoHeader infoHeader; infoHeader.biSize = 40; infoHeader.biWidth = image->getWidth(); infoHeader.biHeight = image->getHeight(); infoHeader.biPlanesAndBitCount = (24 << 16) | 1; infoHeader.biCompression = 0; // Compression is bad :P infoHeader.biSizeImage = 0; // Can be 0 only if we do not use compression infoHeader.biXPelsPerMeter = 0; infoHeader.biYPelsPerMeter = 0; infoHeader.biClrUsed = 0; infoHeader.biClrImportant = 0; file.put('B'); file.put('M'); file.write((char *) &header, sizeof(BMPHeader)); file.write((char *) &infoHeader, sizeof(BMPInfoHeader)); camera::ImageBuffer *buffer = image->getBufferAddress(); int linePadding = width % 4; // Start with the bottom left pixel (WHY MICROSOFT? WHY?!) buffer += 4 * (width * height - width); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { file.put(*(buffer)); // B file.put(*(buffer + 1)); // G file.put(*(buffer + 2)); // R // Move to next pixel buffer += 4; } // Every line must be n * 4 bytes for(int i = 0; i < linePadding; i++) { file.put('\0'); } // Move up one line buffer -= 4 * 2 * width; } file.close(); } } // namespace util } // namespace camera
[ "kers@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7", "js@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7" ]
[ [ [ 1, 5 ], [ 10, 11 ], [ 14, 20 ], [ 23, 37 ], [ 40, 44 ], [ 47, 60 ], [ 62, 67 ], [ 69, 75 ], [ 77, 112 ], [ 117, 122 ], [ 124, 124 ], [ 127, 128 ], [ 130, 138 ] ], [ [ 6, 9 ], [ 12, 13 ], [ 21, 22 ], [ 38, 39 ], [ 45, 46 ], [ 61, 61 ], [ 68, 68 ], [ 76, 76 ], [ 113, 116 ], [ 123, 123 ], [ 125, 126 ], [ 129, 129 ] ] ]
8fbe9e69222a65e7b61efae2c75fc039462a7fbc
6f23c03e72ff1e044f8766abc2886dd7d7e2e5f4
/source/include/M3DSkydomeTexture.h
212e1e01c7150eeb3b2cd78891b11cec279833a5
[]
no_license
lphpc/Mobile3D
c52f673e048d895d1f8c84309a81328ed3ccedaa
0b4392a35a4eebccdd64fa23b7119cb078073d09
refs/heads/master
2016-09-06T19:16:41.957813
2011-08-03T08:26:22
2011-08-03T08:26:22
1,262,640
4
0
null
null
null
null
UTF-8
C++
false
false
434
h
/* * Skydome with texture. */ #ifndef _M3D_SKYDOMETEXTURE_H_ #define _M3D_SKYDOMETEXTYRE_H_ #include "model.h" M3D_BEGIN_NAMESPACE class SkydomeT : public Model { public: /** * Constructor */ SkydomeT(int radius, float dtheta, float dphi); /** * Destructor */ virtual ~SkydomeT(); }; M3D_END_NAMESPACE #endif
[ [ [ 1, 32 ] ] ]
6929ab2ce015d8087bd1e6a8b18d15dd25dcdb5f
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Query/Collector/PointCollector/hkpSimpleClosestContactCollector.inl
e5b9288656aa310cae9ee885add001b95c22fb69
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,687
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ void hkpSimpleClosestContactCollector::reset() { m_hasHit = false; m_hitPoint.setDistance( HK_REAL_MAX ); hkpCdPointCollector::reset(); } hkpSimpleClosestContactCollector::hkpSimpleClosestContactCollector() { reset(); } hkpSimpleClosestContactCollector::~hkpSimpleClosestContactCollector() { } hkBool hkpSimpleClosestContactCollector::hasHit( ) const { return m_hasHit; } const hkContactPoint& hkpSimpleClosestContactCollector::getHitContact() const { return m_hitPoint; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 52 ] ] ]
bf331e95ba285b9878d42c18fd46d88b43a21197
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nspatialdb/src/sdbviewer/nsdbviewer.cc
3d72d406b0f9d7b4e3d7a81969fcea23c347c9a0
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
4,825
cc
//------------------------------------------------------------------------------ /** @page NebulaToolsnviewer nviewer nviewer Selfcontained viewer application for Nebula. <dl> <dt>-script</dt> <dd>script to run</dd> <dt>-view</dt> <dd>data to load and view with the default lighting setup</dd> <dt>-stage</dt> <dd>the light stage to load, default is: home:bin/stdlight.tcl </dd> <dt>-fullscreen</dt> <dd>if present, then nviewer will go fullscreen</dd> <dt>-alwaysontop</dt> <dd>if present the window will be allways on top</dd> <dt>-w</dt> <dd>width of window to open (default: 640)</dd> <dt>-h</dt> <dd>height of window to open (default: 480)</dd> <dt>-x</dt> <dd>the x position of the window (default: 0)</dd> <dt>-y</dt> <dd>the y position of the window (default: 0)</dd> <dt>-projdir</dt> <dd>the project directory</dd> </dl> nviewer also defines some default input handling: @todo Document default inputhandling (C) 2002 RadonLabs GmbH */ //------------------------------------------------------------------------------ #include "kernel/nkernelserver.h" #include "sdbviewer/nsdbviewerapp.h" #ifdef __WIN32__ #include "kernel/nwin32loghandler.h" #include "tools/nwinmaincmdlineargs.h" #else #include "tools/ncmdlineargs.h" #endif nNebulaUsePackage(nnebula); nNebulaUsePackage(ndinput8); nNebulaUsePackage(ndirect3d9); nNebulaUsePackage(ndshow); nNebulaUsePackage(ngui); nNebulaUsePackage(nlua); nNebulaUsePackage(nspatialdb); //------------------------------------------------------------------------------ /* */ #ifdef __WIN32__ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, LPSTR lpCmdLine, int nCmdShow) { nWinMainCmdLineArgs args(lpCmdLine); #else int main(int argc, const char** argv) { nCmdLineArgs args(argc, argv); #endif nString scriptserverArg = args.GetStringArg("-scriptserver", "nluaserver"); nString sceneserverArg = args.GetStringArg("-sceneserver", "nsceneserver"); nString startupArg = args.GetStringArg("-startup", "home:code/contrib/nspatialdb/bin/startup.lua"); nString viewArg = args.GetStringArg("-view", 0); nString stageArg = args.GetStringArg("-stage", "luascript:stdlight.lua"); nString inputArg = args.GetStringArg("-input", "luascript:stdinput.lua"); bool fullscreenArg = args.GetBoolArg("-fullscreen"); bool alwaysOnTopArg = args.GetBoolArg("-alwaysontop"); int xPosArg = args.GetIntArg("-x", 0); int yPosArg = args.GetIntArg("-y", 0); int widthArg = args.GetIntArg("-w", 640); int heightArg = args.GetIntArg("-h", 480); nString projDir = args.GetStringArg("-projdir", 0); if (viewArg.IsEmpty()) viewArg = "localgfxlib:unitsphere.n2"; // initialize a display mode object nString title; if (viewArg.IsValid()) { title.Append(viewArg); title.Append(" - "); } title.Append("SpatialDB viewer"); nDisplayMode2 displayMode; if (fullscreenArg) { displayMode.Set(title.Get(), nDisplayMode2::Fullscreen, xPosArg, yPosArg, widthArg, heightArg, true, false, NULL); } else if (alwaysOnTopArg) { displayMode.Set(title.Get(), nDisplayMode2::AlwaysOnTop, xPosArg, yPosArg, widthArg, heightArg, true, false, NULL); } else { displayMode.Set(title.Get(), nDisplayMode2::Windowed, xPosArg, yPosArg, widthArg, heightArg, true, false, NULL); } // initialize Nebula runtime nKernelServer kernelServer; #ifdef __WIN32__ nWin32LogHandler logHandler("nsdbviewer"); kernelServer.SetLogHandler(&logHandler); #endif kernelServer.AddPackage(nnebula); kernelServer.AddPackage(ndinput8); kernelServer.AddPackage(ndirect3d9); kernelServer.AddPackage(ngui); kernelServer.AddPackage(nlua); kernelServer.AddPackage(nspatialdb); // initialize a viewer app object nSDBViewerApp viewerApp(&kernelServer); viewerApp.SetDisplayMode(displayMode); if (viewArg.Get()) { viewerApp.SetSceneFile(viewArg.Get()); } if (projDir.Get()) { viewerApp.SetProjDir(projDir.Get()); } viewerApp.SetScriptServerClass(scriptserverArg.Get()); viewerApp.SetSceneServerClass(sceneserverArg.Get()); viewerApp.SetStartupScript(startupArg.Get()); viewerApp.SetStageScript(stageArg.Get()); viewerApp.SetInputScript(inputArg.Get()); // open and run viewer if (viewerApp.Open()) { viewerApp.Run(); viewerApp.Close(); } return 0; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 149 ] ] ]
7d3f3c7f03a39e3098a5aa2a2da707a4fe828f70
58865be8e22939fd980af6c9697add3571868b17
/source/AudioEndpointHandle.cpp
f1c5420aab0904319acf3ba15e9355a18c60c315
[ "BSD-2-Clause" ]
permissive
dilyanrusev/foo-mm-keys
73fb63a10730fac1a4b5e52ee901a2b0e854195c
ab326f7243e997550186a99cdc73a4f147bc3d2c
refs/heads/master
2020-04-05T23:27:47.251505
2011-12-01T07:52:27
2011-12-01T07:52:27
32,144,913
0
0
null
null
null
null
UTF-8
C++
false
false
4,276
cpp
/* Copyright (c) 2011, Dilyan Rusev All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "StdAfx.h" #include "AudioEndpointHandle.hxx" #include "common.hxx" AudioEndpointHandle::AudioEndpointHandle(void) : _pDevEnumerator(NULL) , _pAudioDeveice(NULL) , _pEndpointVolume(NULL) { HRESULT hr; log_message("Getting IMMDeviceEnumerator..."); hr = ::CoCreateInstance( __uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&_pDevEnumerator ); if (FAILED(hr)) { throw std::runtime_error("Failed to obtain instance of IMMDeviceEnumerator"); } log_message("Getting IMMDevice..."); hr = _pDevEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &_pAudioDeveice); if (FAILED(hr)) { throw std::runtime_error("Failed to obtain instance of IMMDevice"); } log_message("Getting IAudioEndpointVolume..."); hr = _pAudioDeveice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_LOCAL_SERVER, NULL, (void**)&_pEndpointVolume); if (FAILED(hr)) { throw std::runtime_error("Failed to obtain instance of IAudioEndpointVolume"); } hr = _pEndpointVolume->GetVolumeRange(&_minVolume, &_maxVolume, &_volumeIncrement); if (FAILED(hr)) { throw std::runtime_error("Unable to determine device volume range"); } } AudioEndpointHandle::~AudioEndpointHandle(void) { if (NULL != _pEndpointVolume) { _pEndpointVolume->Release(); _pEndpointVolume = NULL; ::log_message("IAudioEndpointVolume released"); } if (NULL != _pAudioDeveice) { _pAudioDeveice->Release(); _pAudioDeveice = NULL; ::log_message("IMMDevice released"); } if (NULL != _pDevEnumerator) { _pDevEnumerator->Release(); _pDevEnumerator = NULL; ::log_message("IMMDeviceEnumerator released"); } } void AudioEndpointHandle::toggle_mute() { BOOL muted; if (SUCCEEDED(_pEndpointVolume->GetMute(&muted))) { if (FAILED(_pEndpointVolume->SetMute(!muted, NULL))) { ::log_message("IAudioEndpointVolume::SetMute failed"); } } else { ::log_message("IAudioEndpointVolume::GetMute failed"); } } void AudioEndpointHandle::increase_volume() { float currentVolume; if (SUCCEEDED(_pEndpointVolume->GetMasterVolumeLevel(&currentVolume))) { float newVolumeLevel = min(currentVolume + _volumeIncrement, _maxVolume); if (FAILED(_pEndpointVolume->SetMasterVolumeLevel(newVolumeLevel, NULL))) { ::log_message("IAudioEndpointVolume::SetMute failed"); } } else { ::log_message("IAudioEndpointVolume::GetMasterVolumeLevel failed"); } } void AudioEndpointHandle::decrease_volume() { float currentVolume; if (SUCCEEDED(_pEndpointVolume->GetMasterVolumeLevel(&currentVolume))) { float newVolumeLevel = max(currentVolume - _volumeIncrement, _minVolume); if (FAILED(_pEndpointVolume->SetMasterVolumeLevel(newVolumeLevel, NULL))) { ::log_message("IAudioEndpointVolume::SetMute failed"); } } else { ::log_message("IAudioEndpointVolume::GetMasterVolumeLevel failed"); } }
[ [ [ 1, 125 ] ] ]
5f98cbd337337070adb2404d54bc9a9390d279d4
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/skin/Samples/Skinmagic Toolkit 2.4/MFC/MFCControls/MFCControlsDlg.cpp
6df0ab9e117c573493f923cb31e681c4d3e9e3c4
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
GB18030
C++
false
false
7,687
cpp
// MFCControlsDlg.cpp : implementation file // #include "stdafx.h" #include "MFCControls.h" #include "MFCControlsDlg.h" #include "../About/AboutDlg.h" #include "../TestDll/TestDll.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMFCControlsDlg dialog CMFCControlsDlg::CMFCControlsDlg(CWnd* pParent /*=NULL*/) : CDialog(CMFCControlsDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMFCControlsDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMFCControlsDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMFCControlsDlg) // NOTE: the ClassWizard will add DDX and DDV calls here DDX_Control(pDX, IDC_LIST1, m_List); DDX_Control(pDX, IDC_SCROLLBAR1, m_HorzScroll); DDX_Control(pDX, IDC_SCROLLBAR2, m_VertScroll); DDX_Control(pDX, IDC_COMBO1, m_Combo); DDX_Control(pDX, IDC_PAUSEPLAY, m_PausePlayButton); DDX_Control(pDX, IDC_PROGRESS1, m_Progress); DDX_Control(pDX, IDC_TAB1, m_Tab); DDX_Text(pDX, IDC_EDIT1, m_Edit); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_SLIDER1, m_Slider1); DDX_Control(pDX, IDC_SLIDER2, m_Slider2); DDX_Control(pDX, IDC_SLIDER3, m_Slider3); DDX_Control(pDX, IDC_SLIDER4, m_Slider4); DDX_Control(pDX, IDC_SLIDER5, m_Slider5); DDX_Control(pDX, IDC_SLIDER6, m_Slider6); } BEGIN_MESSAGE_MAP(CMFCControlsDlg, CDialog) //{{AFX_MSG_MAP(CMFCControlsDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_TIMER() ON_BN_CLICKED(IDC_PAUSEPLAY, OnPauseplay) ON_WM_CREATE() ON_WM_DESTROY() ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnSelchangeTab1) ON_BN_CLICKED(IDC_SKINMAGIC, OnSkinmagic) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMFCControlsDlg message handlers BOOL CMFCControlsDlg::OnInitDialog() { CFont* pFont = GetFont(); LOGFONT logfont; pFont->GetLogFont(&logfont); logfont.lfWeight = 700; CFont myFont; myFont.CreateFontIndirect(&logfont); SetFont(&myFont,TRUE); myFont.Detach(); CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 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 // Setup demo controls - no more skinning-specific code in this method for (int i = 0; i < 5; i ++) { TCHAR szTab[20] = {0}; _stprintf(szTab, _T("Tab %d"), (i+1)); m_Tab.InsertItem(i, szTab); } for (int j = 0; j < 10; j++) { m_List.InsertString(j, _T("SkinMagic Toolkit!")); } m_bPlaying = TRUE; m_Progress.SetRange(0, 1000); m_Progress.SetPos(0); m_VertScroll.SetScrollRange(0, 1000, TRUE); m_HorzScroll.SetScrollRange(0, 1000, TRUE); SendDlgItemMessage(IDC_RADIO3, BM_SETCHECK, 1, 0); SendDlgItemMessage(IDC_CHECK3, BM_SETCHECK, 1, 0); m_Slider1.SetRange(0,100,0); m_Slider2.SetRange(0,100,0); m_Slider3.SetRange(0,100,0); m_Slider4.SetRange(0,100,0); m_Slider5.SetRange(0,100,0); m_Slider6.SetRange(0,100,0); m_Slider1.SetPos(0); m_Slider2.SetPos(50); m_Slider3.SetPos(100); m_Slider4.SetPos(0); m_Slider5.SetPos(50); m_Slider6.SetPos(100); // Set a timer to update //SetTimer(1000, 250, NULL); return TRUE; // return TRUE unless you set the focus to a control } void CMFCControlsDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 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 CMFCControlsDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCControlsDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CMFCControlsDlg::OnTimer(UINT nIDEvent) { CDialog::OnTimer(nIDEvent); if(nIDEvent == 1000) { if(m_VertScroll.GetScrollPos() == 1000) m_VertScroll.SetScrollPos(0, TRUE); else m_VertScroll.SetScrollPos(m_VertScroll.GetScrollPos() + 50, TRUE); if(m_HorzScroll.GetScrollPos() == 1000) m_HorzScroll.SetScrollPos(0, TRUE); else m_HorzScroll.SetScrollPos(m_HorzScroll.GetScrollPos() + 50, TRUE); if(m_Tab.GetCurSel() == 4) m_Tab.SetCurSel(0); else m_Tab.SetCurSel(m_Tab.GetCurSel() + 1); m_Tab.Invalidate(); m_Slider1.SetPos(rand() % 101); m_Slider2.SetPos(rand() % 101); m_Slider3.SetPos(rand() % 101); m_Slider4.SetPos(rand() % 101); m_Slider5.SetPos(rand() % 101); m_Slider6.SetPos(rand() % 101); } } static DWORD WINAPI _ScoreThreadProc(LPVOID lpParameter) { ASSERT(lpParameter); CMFCControlsDlg * pThis = (CMFCControlsDlg*)lpParameter; pThis->ScoreThreadProc(); return 0; } void CMFCControlsDlg::ScoreThreadProc () { _hWait = CreateEvent(NULL, TRUE, FALSE, NULL); while(1) { int nPos = 0; int cur = m_Progress.GetPos(); if(cur >= 1000) m_Progress.SetPos(0); else m_Progress.SetPos(cur + 200); // 1个小时报告一次 //SendDlgItemMessage(IDC_PROGRESS1, WM_USER+2, nPos, 0); //SendDlgItemMessage( IDC_PROGRESS1, ) DWORD dwWait = WaitForSingleObject(_hWait, 1000); if(dwWait == WAIT_OBJECT_0) break; } } void CMFCControlsDlg::OnPauseplay() { if(m_bPlaying) { m_bPlaying = FALSE; KillTimer(1000); m_PausePlayButton.SetWindowText(_T("Play")); } else { m_bPlaying = TRUE; SetTimer(1000, 250, NULL); m_PausePlayButton.SetWindowText(_T("Pause")); } } int CMFCControlsDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here return 0; } void CMFCControlsDlg::OnDestroy() { CDialog::OnDestroy(); } void CMFCControlsDlg::OnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult) { m_Tab.Invalidate(); *pResult = 0; } void CMFCControlsDlg::OnSkinmagic() { CAboutDlg dlgAbout; dlgAbout.DoModal(); }
[ "zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 308 ] ] ]
9e80a4b3ed14f36b8762e4d999f23bca64ef3813
7347ab0d3daab6781af407d43ac29243daeae438
/src/connectstate.cpp
c48df7a9f37003012ff7200e652c421cb8a5768d
[]
no_license
suprafun/smalltowns
e096cdfc11e329674a7f76486452f4cd58ddaace
c722da7dd3a1d210d07f22a6c322117b540e63da
refs/heads/master
2021-01-10T03:09:47.664318
2011-06-03T01:22:29
2011-06-03T01:22:29
50,808,558
0
0
null
null
null
null
UTF-8
C++
false
false
8,189
cpp
/********************************************* * * Author: David Athay * * License: New BSD License * * Copyright (c) 2009, CT Games * 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 CT Games 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. * * * Date of file creation: 09-01-30 * * $Id$ * ********************************************/ #include "connectstate.h" #include "input.h" #include "game.h" #include "loginstate.h" #include "resourcemanager.h" #include "graphics/camera.h" #include "graphics/graphics.h" #include "interface/interfacemanager.h" #include "net/networkmanager.h" #include "utilities/log.h" #include "utilities/stringutils.h" #include "utilities/xml.h" #include <SDL.h> #include <sstream> namespace ST { int timeout = 0; bool connecting = false; void submit_connect(AG_Event *event) { std::string hostname; int port = 0; // get the pointers to the input boxes AG_Textbox *one = static_cast<AG_Textbox*>(AG_PTR(1)); AG_Textbox *two = static_cast<AG_Textbox*>(AG_PTR(2)); // check they are valid, then assign their values if (one && two) { hostname = AG_TextboxDupString(one); port = AG_TextboxInt(two); } // check the input isnt blank and not already connecting if (!connecting && !hostname.empty() && port != 0) { // set when timeout starts, connect to server timeout = SDL_GetTicks(); networkManager->connect(hostname, port); connecting = true; // reset any error messages interfaceManager->setErrorMessage(""); interfaceManager->showErrorWindow(false); } else { if (connecting) { interfaceManager->setErrorMessage("Already connecting, please be patient."); } else if (hostname.empty()) { interfaceManager->setErrorMessage("Invalid hostname, please enter a server to connect to."); } else if (port == 0) { interfaceManager->setErrorMessage("Invalid port number, please enter the port to connect to."); } interfaceManager->showErrorWindow(true); } } ConnectState::ConnectState() { } void ConnectState::enter() { int screenWidth = graphicsEngine->getScreenWidth(); int screenHeight = graphicsEngine->getScreenHeight(); int halfScreenWidth = screenWidth / 2; int halfScreenHeight = screenHeight / 2; // create window for entering username and password AG_Window *win = AG_WindowNew(AG_WINDOW_PLAIN|AG_WINDOW_KEEPBELOW); AG_WindowShow(win); AG_WindowMaximize(win); interfaceManager->addWindow(win); // Load windows from file XMLFile file; std::string filename; std::string name; std::string title; std::string hostText; std::string portText; std::string buttonText; int w; int h; filename = "connect."; filename.append(game->getLanguage()); filename.append(".xml"); if (file.load(resourceManager->getDataPath(filename))) { file.setElement("window"); name = file.readString("window", "name"); title = file.readString("window", "title"); w = file.readInt("window", "width"); h = file.readInt("window", "height"); file.setSubElement("input"); hostText = file.readString("input", "text"); file.nextSubElement("input"); portText = file.readString("input", "text"); file.setSubElement("button"); buttonText = file.readString("button", "text"); file.close(); AG_Window *test = AG_WindowNewNamed(AG_WINDOW_NOBUTTONS|AG_WINDOW_KEEPABOVE, name.c_str()); AG_WindowSetCaption(test, title.c_str()); AG_WindowSetSpacing(test, 12); AG_WindowSetGeometry(test, halfScreenWidth - (w / 2) , halfScreenHeight - (h / 2), w, h); AG_Textbox *hostname = AG_TextboxNew(test, 0, hostText.c_str()); AG_Textbox *port = AG_TextboxNew(test, AG_TEXTBOX_INT_ONLY, portText.c_str()); AG_ExpandHoriz(hostname); AG_ExpandHoriz(port); // set defaults AG_TextboxSetString(hostname, "server.casualgamer.co.uk"); AG_TextboxSetString(port, "9910"); AG_Button *button = AG_ButtonNewFn(test, 0, buttonText.c_str(), submit_connect, "%p%p", hostname, port); AG_ButtonJustify(button, AG_TEXT_CENTER); AG_WidgetFocus(button); AG_WindowHide(test); interfaceManager->addWindow(test); } else { logger->logDebug("XML file not found"); // XML file wasnt found, load default AG_Window *test = AG_WindowNewNamed(AG_WINDOW_NOBUTTONS|AG_WINDOW_KEEPABOVE, "Connection"); AG_WindowSetCaption(test, "Connect to server"); AG_WindowSetSpacing(test, 12); AG_WindowSetGeometry(test, halfScreenWidth - 125, halfScreenHeight - 45, 225, 135); AG_Textbox *hostname = AG_TextboxNew(test, 0, "Server: "); AG_Textbox *port = AG_TextboxNew(test, AG_TEXTBOX_INT_ONLY, "Port: "); // set defaults AG_TextboxSetString(hostname, "server.casualgamer.co.uk"); AG_TextboxSetString(port, "9910"); AG_Button *button = AG_ButtonNewFn(test, 0, "Submit", submit_connect, "%p%p", hostname, port); AG_ButtonJustify(button, AG_TEXT_CENTER); AG_WidgetFocus(button); AG_WindowHide(test); interfaceManager->addWindow(test); } timeout = SDL_GetTicks(); networkManager->connect(); connecting = true; } void ConnectState::exit() { interfaceManager->removeAllWindows(); } bool ConnectState::update() { // Check for input, if escape pressed, exit if (inputManager->getKey(AG_KEY_ESCAPE)) { return false; } // when connected, send the version if (networkManager->isConnected() && connecting) { connecting = false; networkManager->sendVersion(); } // check if its timedout if (timeout && (SDL_GetTicks() - timeout > 5000)) { connecting = false; networkManager->disconnect(); // reset timeout, and log the error timeout = 0; logger->logWarning("Connecting timed out"); interfaceManager->showWindow("/Connection", true); // set error label, and stop connecting interfaceManager->setErrorMessage("Error: Connection timed out"); interfaceManager->showErrorWindow(true); } SDL_Delay(0); return true; } }
[ "ko2fan@2ae5cb60-8703-11dd-9899-c7ba65f7c4c7" ]
[ [ [ 1, 255 ] ] ]
8f8a66a091cc1e81d05adead21f30a64b968ebb1
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/node/nshadernode_main.cc
ea12f2a43ca28439bb0b22359119360af012728b
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,283
cc
#define N_IMPLEMENTS nShaderNode //------------------------------------------------------------------- // nshadernode_main.cc // (C) 2000 RadonLabs GmbH -- A.Weissflog //------------------------------------------------------------------- #include "node/nshadernode.h" #include "gfx/ngfxserver.h" #include "gfx/npixelshader.h" #include "gfx/nscenegraph2.h" nNebulaScriptClass(nShaderNode, "nvisnode"); //------------------------------------------------------------------- // ~nShaderNode() // 21-Aug-00 floh created //------------------------------------------------------------------- nShaderNode::~nShaderNode() { release_ref(this->ref_ps); } //------------------------------------------------------------------- // SetColorOp() // 25-Aug-00 floh created //------------------------------------------------------------------- bool nShaderNode::SetColorOp(int stage, const char *str) { n_assert(str); char buf[N_MAXNAMELEN]; n_strncpy2(buf,str,sizeof(buf)); // get the opcode nPSI::nOp op = nPSI::NOP; nPSI::nScale scale = nPSI::ONE; nPSI::nArg arg0 = nPSI::NOARG; nPSI::nArg arg1 = nPSI::NOARG; nPSI::nArg arg2 = nPSI::NOARG; char *op_str = strtok(buf," "); n_assert(op_str); char *arg_str; // translate it and get number of expected args int num_args = this->ps_desc.Str2Op(op_str,op,scale); if (num_args == 0 && op != nPSI::NOP) { n_error("nShaderNode::SetColorOp(): opcode '%s' not accepted.\n",op_str); } if (num_args > 0) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg0)) { n_error("nShaderNode::SetColorOp(): invalid arg0 string '%s' on stage '%d'.\n",arg_str,stage); } } if (num_args > 1) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg1)) { n_error("nShaderNode::SetColorOp(): invalid arg1 string '%s' on stage '%d'.\n",arg_str,stage); } } if (num_args > 2) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg2)) { n_error("nShaderNode::SetColorOp(): invalid arg2 string '%s' on stage '%d'.\n",arg_str,stage); } } this->ps_desc.SetColorOp(stage,op,arg0,arg1,arg2,scale); return true; } //------------------------------------------------------------------- // SetAlphaOp() // 25-Aug-00 floh created //------------------------------------------------------------------- bool nShaderNode::SetAlphaOp(int stage, const char *str) { n_assert(str); char buf[N_MAXNAMELEN]; n_strncpy2(buf,str,sizeof(buf)); // get the opcode nPSI::nOp op = nPSI::NOP; nPSI::nScale scale = nPSI::ONE; nPSI::nArg arg0 = nPSI::NOARG; nPSI::nArg arg1 = nPSI::NOARG; nPSI::nArg arg2 = nPSI::NOARG; char *op_str = strtok(buf," "); n_assert(op_str); char *arg_str; // translate it and get number of expected args int num_args = this->ps_desc.Str2Op(op_str,op,scale); if (num_args > 0) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg0)) { n_error("nShaderNode::SetAlphaOp(): invalid arg0 string '%s' on stage '%d'.\n",arg_str,stage); } } if (num_args > 1) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg1)) { n_error("nShaderNode::SetAlphaOp(): invalid arg1 string '%s' on stage '%d'.\n",arg_str,stage); } } if (num_args > 2) { arg_str = strtok(NULL," "); if (!this->ps_desc.Str2Arg(arg_str,arg2)) { n_error("nShaderNode::SetAlphaOp(): invalid arg2 string '%s' on stage '%d'.\n",arg_str,stage); } } this->ps_desc.SetAlphaOp(stage,op,arg0,arg1,arg2,scale); return true; } //------------------------------------------------------------------- // GetColorOp() // 22-Aug-00 floh created //------------------------------------------------------------------- void nShaderNode::GetColorOp(int stage, char *buf, int /*buf_size*/) { nPSI::nOp op; nPSI::nScale scale; nPSI::nArg arg0,arg1,arg2; char tmp_buf[N_MAXNAMELEN]; this->ps_desc.GetColorOp(stage,op,arg0,arg1,arg2,scale); this->ps_desc.Op2Str(op,scale,tmp_buf,sizeof(tmp_buf)); strcpy(buf,tmp_buf); if (arg0 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg0,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } if (arg1 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg1,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } if (arg2 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg2,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } } //------------------------------------------------------------------- // GetAlphaOp() // 22-Aug-00 floh created //------------------------------------------------------------------- void nShaderNode::GetAlphaOp(int stage, char *buf, int /*buf_size*/) { nPSI::nOp op; nPSI::nScale scale; nPSI::nArg arg0,arg1,arg2; char tmp_buf[N_MAXNAMELEN]; this->ps_desc.GetAlphaOp(stage,op,arg0,arg1,arg2,scale); this->ps_desc.Op2Str(op,scale,tmp_buf,sizeof(tmp_buf)); strcpy(buf,tmp_buf); if (arg0 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg0,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } if (arg1 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg1,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } if (arg2 != nPSI::NOARG) { this->ps_desc.Arg2Str(arg2,tmp_buf,sizeof(tmp_buf)); strcat(buf," "); strcat(buf,tmp_buf); } } //------------------------------------------------------------------- // init_pixelshader() // 05-Oct-00 floh created //------------------------------------------------------------------- void nShaderNode::init_pixelshader(void) { n_assert(!this->ref_ps.isvalid()); nPixelShader *ps = this->refGfx->NewPixelShader(this->GetFullName().c_str()); if (ps) { this->ref_ps = ps; ps->SetShaderDesc(&(this->ps_desc)); } } //------------------------------------------------------------------- // Preload() // 28-Sep-01 floh created //------------------------------------------------------------------- void nShaderNode::Preload() { if (!this->ref_ps.isvalid()) { this->init_pixelshader(); } nVisNode::Preload(); } //------------------------------------------------------------------- // Attach() // 22-Aug-00 floh created // 10-Oct-00 floh + added transparency and renderpri // 31-May-01 floh + new behaviour //------------------------------------------------------------------- bool nShaderNode::Attach(nSceneGraph2 *sceneGraph) { n_assert(sceneGraph); if (nVisNode::Attach(sceneGraph)) { sceneGraph->AttachShaderNode(this); sceneGraph->AttachRenderPri(this->render_pri); sceneGraph->AttachOpaqueness(!this->GetAlphaEnable()); return true; } return false; } //------------------------------------------------------------------- // Compute() // 22-Aug-00 floh created // 31-May-01 floh new behaviour //------------------------------------------------------------------- void nShaderNode::Compute(nSceneGraph2 *sceneGraph) { n_assert(sceneGraph); nVisNode::Compute(sceneGraph); // initialize pixel shader on demand (pixel shaders may // become invalid during runtime, for instance when // switching gfx servers) if (!this->ref_ps.isvalid()) { this->init_pixelshader(); } // the actual rendering of the pixel shader will happen // inside the mesh rendering sceneGraph->SetPixelShader(this->ref_ps.get()); } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 261 ] ] ]
d713fc8ff753ee850b0565372886918606392e84
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAICompassSensor.h
6805aa7f949d23dd00b0efcc6cfba10c17cec266
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
1,102
h
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAICOMPASSSENSOR_H #define MOAICOMPASSSENSOR_H #include <moaicore/MOAISensor.h> //================================================================// // MOAICompassSensor //================================================================// /** @name MOAICompassSensor @text Device heading sensor. */ class MOAICompassSensor : public MOAISensor { private: float mHeading; USLuaRef mCallback; //----------------------------------------------------------------// static int _getHeading ( lua_State* L ); static int _setCallback ( lua_State* L ); public: DECL_LUA_FACTORY ( MOAICompassSensor ) //----------------------------------------------------------------// void HandleEvent ( USStream& eventStream ); MOAICompassSensor (); ~MOAICompassSensor (); void RegisterLuaClass ( USLuaState& state ); void RegisterLuaFuncs ( USLuaState& state ); static void WriteEvent ( USStream& eventStream, float heading ); }; #endif
[ [ [ 1, 40 ] ] ]
bb82519d6db8208156b47ccda0dc52529e2e2828
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Operator/UserDataDTO.h
27a1e4aa4580bd841a0a396e3b67916832cb8aa5
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
/**@file UserDataDTO.h * @brief 유저 개인의 정보를 담는 DTO를 정의한다. * @author siva */ #ifndef USER_DATA_DTO_H #define USER_DATA_DTO_H /**@ingroup GroupDAM * @class CUserDataDTO * @brief 유저 개인의 정보를 담는다.\n * @remarks 비밀번호는 모두 단방향 해싱을 거친 값들을 갖는다.\n * 유저 id는 당방향 해싱 후의 로우레벨 패스워드(학번)다. */ class CUserDataDTO { public : /**@brief 여기선 단순히 해당 유저의 low level password를 사용한다. */ CString m_userId; CString m_name; CString m_lowLevelPassword; /**@brief sha1으로 해싱된 digest message를 갖는다. */ CString m_highLevelPassword; int m_level; CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, CString a_highLevelPassword, int a_level); CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, int a_level, CString a_hashedHighLevelPassword); CUserDataDTO(){} ~CUserDataDTO(){} private : CString HashMessage(CString a_message); }; #endif
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 36 ] ] ]
b37939e1bf53b43c86a4d776c2d551030aa3dc7f
46b3500c9ab98883091eb9d4ca49a6854451d76b
/ghost/ghost.h
0876fb60158c92577bfa4e442493751ad0094790
[ "Apache-2.0" ]
permissive
kr4uzi/pyghost
7baa511fa05ddaba57880d2c7483694d5c5816b7
35e5bdd838cb21ad57b3c686349251eb277d2e6a
refs/heads/master
2020-04-25T21:05:20.995556
2010-11-21T13:57:49
2010-11-21T13:57:49
42,011,079
0
0
null
null
null
null
UTF-8
C++
false
false
8,901
h
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #ifndef GHOST_H #define GHOST_H #include "includes.h" // // CGHost // class CUDPSocket; class CTCPServer; class CTCPSocket; class CGPSProtocol; class CCRC32; class CSHA1; class CBNET; class CBaseGame; class CAdminGame; class CGHostDB; class CBaseCallable; class CLanguage; class CMap; class CSaveGame; class CConfig; class CGHost { public: CUDPSocket *m_UDPSocket; // a UDP socket for sending broadcasts and other junk (used with !sendlan) CTCPServer *m_ReconnectSocket; // listening socket for GProxy++ reliable reconnects vector<CTCPSocket *> m_ReconnectSockets;// vector of sockets attempting to reconnect (connected but not identified yet) CGPSProtocol *m_GPSProtocol; CCRC32 *m_CRC; // for calculating CRC's CSHA1 *m_SHA; // for calculating SHA1's vector<CBNET *> m_BNETs; // all our battle.net connections (there can be more than one) CBaseGame *m_CurrentGame; // this game is still in the lobby state CAdminGame *m_AdminGame; // this "fake game" allows an admin who knows the password to control the bot from the local network vector<CBaseGame *> m_Games; // these games are in progress CGHostDB *m_DB; // database CGHostDB *m_DBLocal; // local database (for temporary data) vector<CBaseCallable *> m_Callables; // vector of orphaned callables waiting to die vector<BYTEARRAY> m_LocalAddresses; // vector of local IP addresses CLanguage *m_Language; // language CMap *m_Map; // the currently loaded map CMap *m_AdminMap; // the map to use in the admin game CMap *m_AutoHostMap; // the map to use when autohosting CSaveGame *m_SaveGame; // the save game to use vector<PIDPlayer> m_EnforcePlayers; // vector of pids to force players to use in the next game (used with saved games) bool m_Exiting; // set to true to force ghost to shutdown next update (used by SignalCatcher) bool m_ExitingNice; // set to true to force ghost to disconnect from all battle.net connections and wait for all games to finish before shutting down bool m_Enabled; // set to false to prevent new games from being created string m_Version; // GHost++ version string uint32_t m_HostCounter; // the current host counter (a unique number to identify a game, incremented each time a game is created) string m_AutoHostGameName; // the base game name to auto host with string m_AutoHostOwner; string m_AutoHostServer; uint32_t m_AutoHostMaximumGames; // maximum number of games to auto host uint32_t m_AutoHostAutoStartPlayers; // when using auto hosting auto start the game when this many players have joined uint32_t m_LastAutoHostTime; // GetTime when the last auto host was attempted bool m_AutoHostMatchMaking; double m_AutoHostMinimumScore; double m_AutoHostMaximumScore; bool m_AllGamesFinished; // if all games finished (used when exiting nicely) uint32_t m_AllGamesFinishedTime; // GetTime when all games finished (used when exiting nicely) string m_LanguageFile; // config value: language file string m_Warcraft3Path; // config value: Warcraft 3 path bool m_TFT; // config value: TFT enabled or not string m_BindAddress; // config value: the address to host games on uint16_t m_HostPort; // config value: the port to host games on bool m_Reconnect; // config value: GProxy++ reliable reconnects enabled or not uint16_t m_ReconnectPort; // config value: the port to listen for GProxy++ reliable reconnects on uint32_t m_ReconnectWaitTime; // config value: the maximum number of minutes to wait for a GProxy++ reliable reconnect uint32_t m_MaxGames; // config value: maximum number of games in progress char m_CommandTrigger; // config value: the command trigger inside games string m_MapCFGPath; // config value: map cfg path string m_SaveGamePath; // config value: savegame path string m_MapPath; // config value: map path bool m_SaveReplays; // config value: save replays string m_ReplayPath; // config value: replay path string m_VirtualHostName; // config value: virtual host name bool m_HideIPAddresses; // config value: hide IP addresses from players bool m_CheckMultipleIPUsage; // config value: check for multiple IP address usage uint32_t m_SpoofChecks; // config value: do automatic spoof checks or not bool m_RequireSpoofChecks; // config value: require spoof checks or not bool m_ReserveAdmins; // config value: consider admins to be reserved players or not bool m_RefreshMessages; // config value: display refresh messages or not (by default) bool m_AutoLock; // config value: auto lock games when the owner is present bool m_AutoSave; // config value: auto save before someone disconnects uint32_t m_AllowDownloads; // config value: allow map downloads or not bool m_PingDuringDownloads; // config value: ping during map downloads or not uint32_t m_MaxDownloaders; // config value: maximum number of map downloaders at the same time uint32_t m_MaxDownloadSpeed; // config value: maximum total map download speed in KB/sec bool m_LCPings; // config value: use LC style pings (divide actual pings by two) uint32_t m_AutoKickPing; // config value: auto kick players with ping higher than this uint32_t m_BanMethod; // config value: ban method (ban by name/ip/both) string m_IPBlackListFile; // config value: IP blacklist file (ipblacklist.txt) uint32_t m_LobbyTimeLimit; // config value: auto close the game lobby after this many minutes without any reserved players uint32_t m_Latency; // config value: the latency (by default) uint32_t m_SyncLimit; // config value: the maximum number of packets a player can fall out of sync before starting the lag screen (by default) bool m_VoteKickAllowed; // config value: if votekicks are allowed or not uint32_t m_VoteKickPercentage; // config value: percentage of players required to vote yes for a votekick to pass string m_DefaultMap; // config value: default map (map.cfg) string m_MOTDFile; // config value: motd.txt string m_GameLoadedFile; // config value: gameloaded.txt string m_GameOverFile; // config value: gameover.txt bool m_LocalAdminMessages; // config value: send local admin messages or not bool m_AdminGameCreate; // config value: create the admin game or not uint16_t m_AdminGamePort; // config value: the port to host the admin game on string m_AdminGamePassword; // config value: the admin game password string m_AdminGameMap; // config value: the admin game map config to use unsigned char m_LANWar3Version; // config value: LAN warcraft 3 version uint32_t m_ReplayWar3Version; // config value: replay warcraft 3 version (for saving replays) uint32_t m_ReplayBuildNumber; // config value: replay build number (for saving replays) bool m_TCPNoDelay; // config value: use Nagle's algorithm or not uint32_t m_MatchMakingMethod; // config value: the matchmaking method CGHost( CConfig *CFG ); ~CGHost( ); // processing functions bool Update( long usecBlock ); // events void EventBNETConnecting( CBNET *bnet ); void EventBNETConnected( CBNET *bnet ); void EventBNETDisconnected( CBNET *bnet ); void EventBNETLoggedIn( CBNET *bnet ); void EventBNETGameRefreshed( CBNET *bnet ); void EventBNETGameRefreshFailed( CBNET *bnet ); void EventBNETConnectTimedOut( CBNET *bnet ); void EventBNETWhisper( CBNET *bnet, string user, string message ); void EventBNETChat( CBNET *bnet, string user, string message ); void EventBNETEmote( CBNET *bnet, string user, string message ); void EventGameCreated( CBaseGame *game ); void EventGameDeleted( CBaseGame *game ); // other functions void ReloadConfigs( ); void SetConfigs( CConfig *CFG ); void ExtractScripts( ); void LoadIPToCountryData( ); void CreateGame( CMap *map, unsigned char gameState, bool saveGame, string gameName, string ownerName, string creatorName, string creatorServer, bool whisper ); public: static void RegisterPythonClass( ); }; #endif
[ "kr4uzi@88aed30e-2b04-91ce-7a47-0ae997e79d63" ]
[ [ [ 1, 171 ] ] ]
289da8b6aebedf55f213ea7d31ff0063955565ad
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qtextlayout.h
39c6b10193342d141efe4d9f93c5dd79aa42f8b9
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,377
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTEXTLAYOUT_H #define QTEXTLAYOUT_H #include <QtCore/qstring.h> #include <QtCore/qnamespace.h> #include <QtCore/qrect.h> #include <QtCore/qvector.h> #include <QtGui/qcolor.h> #include <QtCore/qobject.h> #include <QtGui/qevent.h> #include <QtGui/qtextformat.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QTextEngine; class QFont; class QRect; class QRegion; class QTextFormat; class QPalette; class QPainter; class Q_GUI_EXPORT QTextInlineObject { public: QTextInlineObject(int i, QTextEngine *e) : itm(i), eng(e) {} inline QTextInlineObject() : itm(0), eng(0) {} inline bool isValid() const { return eng; } QRectF rect() const; qreal width() const; qreal ascent() const; qreal descent() const; qreal height() const; Qt::LayoutDirection textDirection() const; void setWidth(qreal w); void setAscent(qreal a); void setDescent(qreal d); int textPosition() const; int formatIndex() const; QTextFormat format() const; private: friend class QTextLayout; int itm; QTextEngine *eng; }; class QPaintDevice; class QTextFormat; class QTextLine; class QTextBlock; class QTextOption; class Q_GUI_EXPORT QTextLayout { public: // does itemization QTextLayout(); QTextLayout(const QString& text); QTextLayout(const QString& text, const QFont &font, QPaintDevice *paintdevice = 0); QTextLayout(const QTextBlock &b); ~QTextLayout(); void setFont(const QFont &f); QFont font() const; void setText(const QString& string); QString text() const; void setTextOption(const QTextOption &option); QTextOption textOption() const; void setPreeditArea(int position, const QString &text); int preeditAreaPosition() const; QString preeditAreaText() const; struct FormatRange { int start; int length; QTextCharFormat format; }; void setAdditionalFormats(const QList<FormatRange> &overrides); QList<FormatRange> additionalFormats() const; void clearAdditionalFormats(); void setCacheEnabled(bool enable); bool cacheEnabled() const; void beginLayout(); void endLayout(); void clearLayout(); QTextLine createLine(); int lineCount() const; QTextLine lineAt(int i) const; QTextLine lineForTextPosition(int pos) const; enum CursorMode { SkipCharacters, SkipWords }; bool isValidCursorPosition(int pos) const; int nextCursorPosition(int oldPos, CursorMode mode = SkipCharacters) const; int previousCursorPosition(int oldPos, CursorMode mode = SkipCharacters) const; void draw(QPainter *p, const QPointF &pos, const QVector<FormatRange> &selections = QVector<FormatRange>(), const QRectF &clip = QRectF()) const; void drawCursor(QPainter *p, const QPointF &pos, int cursorPosition) const; void drawCursor(QPainter *p, const QPointF &pos, int cursorPosition, int width) const; QPointF position() const; void setPosition(const QPointF &p); QRectF boundingRect() const; qreal minimumWidth() const; qreal maximumWidth() const; QTextEngine *engine() const { return d; } void setFlags(int flags); private: QTextLayout(QTextEngine *e) : d(e) {} Q_DISABLE_COPY(QTextLayout) friend class QPainter; friend class QPSPrinter; friend class QGraphicsSimpleTextItemPrivate; friend class QGraphicsSimpleTextItem; friend void qt_format_text(const QFont &font, const QRectF &_r, int tf, const QTextOption *, const QString& str, QRectF *brect, int tabstops, int* tabarray, int tabarraylen, QPainter *painter); QTextEngine *d; }; class Q_GUI_EXPORT QTextLine { public: inline QTextLine() : i(0), eng(0) {} inline bool isValid() const { return eng; } QRectF rect() const; qreal x() const; qreal y() const; qreal width() const; qreal ascent() const; qreal descent() const; qreal height() const; qreal naturalTextWidth() const; QRectF naturalTextRect() const; enum Edge { Leading, Trailing }; enum CursorPosition { CursorBetweenCharacters, CursorOnCharacter }; /* cursorPos gets set to the valid position */ qreal cursorToX(int *cursorPos, Edge edge = Leading) const; inline qreal cursorToX(int cursorPos, Edge edge = Leading) const { return cursorToX(&cursorPos, edge); } int xToCursor(qreal x, CursorPosition = CursorBetweenCharacters) const; void setLineWidth(qreal width); void setNumColumns(int columns); void setNumColumns(int columns, qreal alignmentWidth); void setPosition(const QPointF &pos); QPointF position() const; int textStart() const; int textLength() const; int lineNumber() const { return i; } void draw(QPainter *p, const QPointF &point, const QTextLayout::FormatRange *selection = 0) const; private: QTextLine(int line, QTextEngine *e) : i(line), eng(e) {} void layout_helper(int numGlyphs); friend class QTextLayout; int i; QTextEngine *eng; }; QT_END_NAMESPACE QT_END_HEADER #endif // QTEXTLAYOUT_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 243 ] ] ]
ac10a8459cc5161cb2aa9d58d9c66e357def8fef
c39f656a6799501c1d569c8a96e0bd4d83b72f3a
/Firmware_BootRom/temperature.cpp
34bbf7bf926f367f7415fbd31ecd59c72049b6f4
[]
no_license
tsuckow/thermostat
36f7c9c7e5b8fca3721b5a73f998be13e19bfcd8
a8e532cff07ca29b0abbb4343927faa0645f2bfc
refs/heads/master
2021-01-25T07:40:12.179775
2011-09-28T15:51:45
2011-09-28T15:51:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,007
cpp
#include "temperature.h" #include <unistd.h> #include "debug.h" #include "touchscreen.h" #include "sprs.h" #include "math.h" namespace { bool temp2_next = false; volatile uint32_t * const TEMP_SPI = (uint32_t * const)0xFFFF0040; //SPI Module Address, change this size_t const SPI_Rx0 = 0; size_t const SPI_Tx0 = 0; size_t const SPI_CTRL = 4; size_t const SPI_DIV = 5; size_t const SPI_SS = 6; uint32_t const SPI_CTRL_ASS = (1 << 13); //Auto Slave Select uint32_t const SPI_CTRL_TXNEG= (1 << 10); uint32_t const SPI_CTRL_RXNEG= (1 << 9); uint32_t const SPI_CTRL_BUSY = (1 << 8); //Busy Flag/Start XFER void spi_ss_on() { TEMP_SPI[SPI_SS] = 1; } void spi_ss_off() { TEMP_SPI[SPI_SS] = 0; } void spi_ss_auto() { uint32_t ctrl = TEMP_SPI[SPI_CTRL]; ctrl |= SPI_CTRL_ASS; TEMP_SPI[SPI_CTRL] = ctrl; } void spi_ss_manual() { uint32_t ctrl = TEMP_SPI[SPI_CTRL]; ctrl &= ~SPI_CTRL_ASS; TEMP_SPI[SPI_CTRL] = ctrl; } unsigned spi_busy() { return TEMP_SPI[SPI_CTRL] & SPI_CTRL_BUSY; } void spi_setSpeed(uint8_t speed) { speed &= 0xFE; TEMP_SPI[SPI_DIV] = speed; } void spi_startXFER(void) { TEMP_SPI[SPI_CTRL] |= SPI_CTRL_BUSY; } uint16_t spi_send(uint16_t outgoing) { uint16_t incoming; TEMP_SPI[SPI_Tx0] = outgoing; spi_startXFER(); while( spi_busy() ); incoming = TEMP_SPI[SPI_Rx0]; return(incoming); } uint32_t const CONVTIME = 4*20000;//20000; //We assume 2 clocks per loop iteration //NO-OP NU NU CONV4 CONV3 CONV2 CONV1 DV4 DV2 NU NU CHS CAL NUL PDX PD uint16_t const ADC_OP = (1 << 15); uint16_t const ADC_CONV_21MS = (0x9 << 9); uint16_t const ADC_CONV_41MS = (0x3 << 9); uint16_t const ADC_CONV_164MS = (0x6 << 9); uint16_t const ADC_CONV_205MS = (0x0 << 9); uint16_t const ADC_DV4 = (1 << 8); uint16_t const ADC_DV2 = (1 << 7); uint16_t const ADC_CHS = (1 << 4); uint16_t const ADC_CAL = (1 << 3); uint16_t const ADC_NUL = (1 << 2); //ADC_OP | ADC_CONV_21MS; uint16_t ADC_CONFIG = ADC_OP | ADC_CONV_164MS | ADC_DV4; } void temperature_init() { spi_ss_off(); spi_ss_manual(); TEMP_SPI[SPI_CTRL] |= 16; //16 bit transfers TEMP_SPI[SPI_CTRL] |= SPI_CTRL_TXNEG; //Transmit changes on negedge / Latch Pos edge spi_setSpeed( 20 ); spi_ss_on(); spi_ss_auto(); //Calibrate CH1 spr_int_setmask(0x04);//Hackish, clean this up spi_send(ADC_CONFIG | ADC_CAL | ADC_NUL); //Step 1/3 spr_int_clearflags(0x0); while( spr_int_getflags() & 0x4 == 0 ); //for( int volatile i = 0; i < CONVTIME; ++i ); spi_send(ADC_CONFIG | ADC_CAL ); //Step 2/3 spr_int_clearflags(0x0); while( spr_int_getflags() & 0x4 == 0 ); //for( int volatile i = 0; i < CONVTIME*20; ++i ); spi_send(ADC_CONFIG | ADC_NUL); //Step 3/3 spr_int_clearflags(0x0); while( spr_int_getflags() & 0x4 == 0 ); //for( int volatile i = 0; i < CONVTIME; ++i ); spi_send(ADC_CONFIG); //Step 4/3 spr_int_clearflags(0x0); while( spr_int_getflags() & 0x4 == 0 ); //for( int volatile i = 0; i < CONVTIME; ++i ); } int16_t temperature_lastconvert1() { return (int16_t)spi_send(ADC_CONFIG); } int16_t temperature_lastconvert2() { return (int16_t)spi_send(ADC_CONFIG | ADC_CHS); } float raw_to_celcius(int raw) { const float rinf = 32824.3; const float b = -12.6334; float tmp; tmp = raw/rinf; tmp = log(tmp); tmp = b/tmp; return tmp; } int16_t temp1 = 0, temp2 = 0; void temp_event() { //We alernate what temp we read and queue the next if( temp2_next ) { temp2 = temperature_lastconvert1(); } else { temp1 = temperature_lastconvert2(); } temp2_next = !temp2_next; }
[ "[email protected]", "tsuckow" ]
[ [ [ 1, 4 ], [ 8, 10 ], [ 12, 12 ], [ 19, 19 ], [ 24, 24 ], [ 29, 29 ], [ 57, 76 ], [ 78, 79 ], [ 93, 96 ], [ 127, 128 ], [ 130, 130 ], [ 132, 133 ], [ 135, 135 ] ], [ [ 5, 7 ], [ 11, 11 ], [ 13, 18 ], [ 20, 23 ], [ 25, 28 ], [ 30, 56 ], [ 77, 77 ], [ 80, 92 ], [ 97, 126 ], [ 129, 129 ], [ 131, 131 ], [ 134, 134 ], [ 136, 164 ] ] ]
c3c048fe899de5a328d366523b54c37babeed0f6
d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18
/source/client/hud/hud_motd.cpp
5c44e3cbd4d949324dfe8aeb6c306c97e86fb5c4
[]
no_license
ferhan66h/Xash3D_ancient
7491cd4ff1c7d0b48300029db24d7e08ba96e88a
075e0a6dae12a0952065eb9b2954be4a8827c72f
refs/heads/master
2021-12-10T07:55:29.592432
2010-05-09T00:00:00
2016-07-30T17:37:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,132
cpp
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // // for displaying a server-sent message of the day // #include "extdll.h" #include "utils.h" #include "hud.h" DECLARE_MESSAGE( m_MOTD, MOTD ); int CHudMOTD :: MOTD_DISPLAY_TIME; int CHudMOTD :: Init( void ) { gHUD.AddHudElem( this ); HOOK_MESSAGE( MOTD ); CVAR_REGISTER( "motd_display_time", "6", 0, "time to show message of the day" ); m_iFlags &= ~HUD_ACTIVE; // start out inactive m_szMOTD[0] = 0; return 1; } int CHudMOTD :: VidInit( void ) { // Load sprites here return 1; } void CHudMOTD :: Reset( void ) { m_iFlags &= ~HUD_ACTIVE; // start out inactive m_szMOTD[0] = 0; m_iLines = 0; m_flActiveTill = 0; } #define LINE_HEIGHT 13 int CHudMOTD :: Draw( float fTime ) { // Draw MOTD line-by-line if( m_flActiveTill < gHUD.m_flTime ) { // finished with MOTD, disable it m_szMOTD[0] = 0; m_iLines = 0; m_iFlags &= ~HUD_ACTIVE; return 1; } // cap activetill time to the display time m_flActiveTill = min( gHUD.m_flTime + MOTD_DISPLAY_TIME, m_flActiveTill ); // find the top of where the MOTD should be drawn, so the whole thing is centered in the screen int ypos = max(((ScreenHeight - (m_iLines * LINE_HEIGHT)) / 2) - 40, 30 ); // shift it up slightly char *ch = m_szMOTD; while( *ch ) { int line_length = 0; // count the length of the current line for( char *next_line = ch; *next_line != '\n' && *next_line != 0; next_line++ ) line_length += gHUD.m_scrinfo.charWidths[ *next_line ]; char *top = next_line; if( *top == '\n' ) *top = 0; else top = NULL; // find where to start drawing the line int xpos = (ScreenWidth - line_length) / 2; gHUD.DrawHudString( xpos, ypos, ScreenWidth, ch, 255, 180, 0 ); ypos += LINE_HEIGHT; if( top ) *top = '\n'; // restore ch = next_line; if( *ch == '\n' ) ch++; if ( ypos > ( ScreenHeight - 20 )) break; // don't let it draw too low } return 1; } int CHudMOTD :: MsgFunc_MOTD( const char *pszName, int iSize, void *pbuf ) { if( m_iFlags & HUD_ACTIVE ) { Reset(); // clear the current MOTD in prep for this one } BEGIN_READ( pszName, iSize, pbuf ); int is_finished = READ_BYTE(); strcat( m_szMOTD, READ_STRING() ); if( is_finished ) { m_iFlags |= HUD_ACTIVE; MOTD_DISPLAY_TIME = CVAR_GET_FLOAT( "motd_display_time" ); m_flActiveTill = gHUD.m_flTime + MOTD_DISPLAY_TIME; for( char *sz = m_szMOTD; *sz != 0; sz++ ) // count the number of lines in the MOTD { if( *sz == '\n' ) m_iLines++; } } return 1; }
[ [ [ 1, 132 ] ] ]
1ff6e50860b1443adbea6b33e8809057081abeb6
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/libs/opmapcontrol/src/internals/core.h
931adbd7f76d7519307f10cb1e5cfbe0fa20ad6d
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,982
h
/** ****************************************************************************** * * @file core.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef CORE_H #define CORE_H #include "debugheader.h" #include "../internals/pointlatlng.h" #include "mousewheelzoomtype.h" #include "../core/size.h" #include "../core/point.h" #include "../core/maptype.h" #include "rectangle.h" #include "QThreadPool" #include "tilematrix.h" #include <QQueue> #include "loadtask.h" #include "copyrightstrings.h" #include "rectlatlng.h" #include "../internals/projections/lks94projection.h" #include "../internals/projections/mercatorprojection.h" #include "../internals/projections/mercatorprojectionyandex.h" #include "../internals/projections/platecarreeprojection.h" #include "../internals/projections/platecarreeprojectionpergo.h" #include "../core/geodecoderstatus.h" #include "../core/opmaps.h" #include <QSemaphore> #include <QThread> #include <QDateTime> #include <QObject> namespace mapcontrol { class OPMapControl; class MapGraphicItem; } namespace internals { class Core:public QObject,public QRunnable { Q_OBJECT friend class mapcontrol::OPMapControl; friend class mapcontrol::MapGraphicItem; public: Core(); ~Core(); void run(); PointLatLng CurrentPosition()const{return currentPosition;} void SetCurrentPosition(const PointLatLng &value); core::Point GetcurrentPositionGPixel(){return currentPositionPixel;} void SetcurrentPositionGPixel(const core::Point &value){currentPositionPixel=value;} core::Point GetrenderOffset(){return renderOffset;} void SetrenderOffset(const core::Point &value){renderOffset=value;} core::Point GetcenterTileXYLocation(){return centerTileXYLocation;} void SetcenterTileXYLocation(const core::Point &value){centerTileXYLocation=value;} core::Point GetcenterTileXYLocationLast(){return centerTileXYLocationLast;} void SetcenterTileXYLocationLast(const core::Point &value){centerTileXYLocationLast=value;} core::Point GetdragPoint(){return dragPoint;} void SetdragPoint(const core::Point &value){dragPoint=value;} core::Point GetmouseDown(){return mouseDown;} void SetmouseDown(const core::Point &value){mouseDown=value;} core::Point GetmouseCurrent(){return mouseCurrent;} void SetmouseCurrent(const core::Point &value){mouseCurrent=value;} core::Point GetmouseLastZoom(){return mouseLastZoom;} void SetmouseLastZoom(const core::Point &value){mouseLastZoom=value;} MouseWheelZoomType::Types GetMouseWheelZoomType(){return mousewheelzoomtype;} void SetMouseWheelZoomType(const MouseWheelZoomType::Types &value){mousewheelzoomtype=value;} PointLatLng GetLastLocationInBounds(){return LastLocationInBounds;} void SetLastLocationInBounds(const PointLatLng &value){LastLocationInBounds=value;} Size GetsizeOfMapArea(){return sizeOfMapArea;} void SetsizeOfMapArea(const Size &value){sizeOfMapArea=value;} Size GetminOfTiles(){return minOfTiles;} void SetminOfTiles(const Size &value){minOfTiles=value;} Size GetmaxOfTiles(){return maxOfTiles;} void SetmaxOfTiles(const Size &value){maxOfTiles=value;} Rectangle GettileRect(){return tileRect;} void SettileRect(const Rectangle &value){tileRect=value;} core::Point GettilePoint(){return tilePoint;} void SettilePoint(const core::Point &value){tilePoint=value;} Rectangle GetCurrentRegion(){return CurrentRegion;} void SetCurrentRegion(const Rectangle &value){CurrentRegion=value;} QList<core::Point> tileDrawingList; PureProjection* Projection() { return projection; } void SetProjection(PureProjection* value) { projection=value; tileRect=Rectangle(core::Point(0,0),value->TileSize()); } bool IsDragging()const{return isDragging;} int Zoom()const{return zoom;} void SetZoom(int const& value); int MaxZoom()const{return maxzoom;} void UpdateBounds(); MapType::Types GetMapType(){return mapType;} void SetMapType(MapType::Types const& value); void StartSystem(); void UpdateCenterTileXYLocation(); void OnMapSizeChanged(int const& width, int const& height);//TODO had as slot void OnMapClose();//TODO had as slot GeoCoderStatusCode::Types SetCurrentPositionByKeywords(QString const& keys); RectLatLng CurrentViewArea(); PointLatLng FromLocalToLatLng(int const& x, int const& y); Point FromLatLngToLocal(PointLatLng const& latlng); int GetMaxZoomToFitRect(RectLatLng const& rect); void BeginDrag(core::Point const& pt); void EndDrag(); void ReloadMap(); void GoToCurrentPosition(); bool MouseWheelZooming; void DragOffset(core::Point const& offset); void Drag(core::Point const& pt); void CancelAsyncTasks(); void FindTilesAround(QList<core::Point> &list); void UpdateGroundResolution(); TileMatrix Matrix; bool isStarted(){return started;} signals: void OnCurrentPositionChanged(internals::PointLatLng point); void OnTileLoadComplete(); void OnTilesStillToLoad(int number); void OnTileLoadStart(); void OnMapDrag(); void OnMapZoomChanged(); void OnMapTypeChanged(MapType::Types type); void OnEmptyTileError(int zoom, core::Point pos); void OnNeedInvalidation(); private: PointLatLng currentPosition; core::Point currentPositionPixel; core::Point renderOffset; core::Point centerTileXYLocation; core::Point centerTileXYLocationLast; core::Point dragPoint; Rectangle tileRect; core::Point mouseDown; bool CanDragMap; core::Point mouseCurrent; PointLatLng LastLocationInBounds; core::Point mouseLastZoom; MouseWheelZoomType::Types mousewheelzoomtype; Size sizeOfMapArea; Size minOfTiles; Size maxOfTiles; core::Point tilePoint; Rectangle CurrentRegion; QQueue<LoadTask> tileLoadQueue; int zoom; PureProjection* projection; bool isDragging; QMutex MtileLoadQueue; QMutex Moverlays; QMutex MtileDrawingList; #ifdef DEBUG_CORE QMutex Mdebug; static qlonglong debugcounter; #endif Size TooltipTextPadding; MapType::Types mapType; QSemaphore loaderLimit; QThreadPool ProcessLoadTaskCallback; QMutex MtileToload; int tilesToload; int maxzoom; protected: bool started; int Width; int Height; int pxRes100m; // 100 meters int pxRes1000m; // 1km int pxRes10km; // 10km int pxRes100km; // 100km int pxRes1000km; // 1000km int pxRes5000km; // 5000km void SetCurrentPositionGPixel(core::Point const& value){currentPositionPixel = value;} void GoToCurrentPositionOnZoom(); }; } #endif // CORE_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 278 ] ] ]
02c86c56be44a9d99f341f4a5d997a800410bdc7
e776dbbd4feab1ce37ad62e5608e22a55a541d22
/MMOGame/SGCommon/SGLua.cpp
db681d6aa1cf0f93cc0de6e1ca67b5beb63fec5b
[]
no_license
EmuxEvans/sailing
80f2e2b0ae0f821ce6da013c3f67edabc8ca91ec
6d3a0f02732313f41518839376c5c0067aea4c0f
refs/heads/master
2016-08-12T23:47:57.509147
2011-04-06T03:39:19
2011-04-06T03:39:19
43,952,647
0
0
null
null
null
null
UTF-8
C++
false
false
92
cpp
#include "SGCode.h" #include "SGData.h" #define TOLUA_API extern #include "SGLua.inl"
[ "gamemake@74c81372-9d52-0410-afc2-f743258a769a" ]
[ [ [ 1, 5 ] ] ]
6869fbb3a9f0905d7bf7b2b7dbbecb51f7214ace
90aa2eebb1ab60a2ac2be93215a988e3c51321d7
/castor/branches/Dev1.1/includes/ops.h
314ba326b4495a909607ee27c63dd0dccb419186
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
roshannaik/castor
b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6
e86e2bf893719bf3164f9da9590217c107cbd913
refs/heads/master
2021-04-18T19:24:38.612073
2010-08-18T05:10:39
2010-08-18T05:10:39
126,150,539
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,725
h
// Castor : Logic Programming Library // Copyright © 2008 Roshan Naik ([email protected]). // This software is goverened by the MIT license (http://www.opensource.org/licenses/mit-license.php). #if !defined CASTOR_OPS_H #define CASTOR_OPS_H 1 #include "relation.h" #include "lref.h" #include "workaround.h" namespace castor { #ifdef CASTOR_ALL_REGULAR_OPS #undef CASTOR_USE_GENERIC_OR #define CASTOR_USE_REGULAR_OR #undef CASTOR_USE_GENERIC_AND #define CASTOR_USE_REGULAR_AND #undef CASTOR_USE_GENERIC_EXOR #define CASTOR_USE_REGULAR_EXOR #endif #ifdef CASTOR_ALL_GENERIC_OPS #define CASTOR_USE_GENERIC_OR #undef CASTOR_USE_REGULAR_OR #define CASTOR_USE_GENERIC_AND #undef CASTOR_USE_REGULAR_AND #define CASTOR_USE_GENERIC_EXOR #undef CASTOR_USE_REGULAR_EXOR #endif #if !defined(CASTOR_USE_GENERIC_OR) && !defined(CASTOR_USE_REGULAR_OR) #define CASTOR_USE_GENERIC_OR #endif #if !defined(CASTOR_USE_GENERIC_AND) && !defined(CASTOR_USE_REGULAR_AND) #define CASTOR_USE_REGULAR_AND #endif #if !defined(CASTOR_USE_GENERIC_EXOR) && !defined(CASTOR_USE_REGULAR_EXOR) #define CASTOR_USE_GENERIC_EXOR #endif //--------------------------------------------------------------- // Relational OR operator : provides backtracking //--------------------------------------------------------------- //Concepts: L supports bool operator() // : R supports bool operator() template<typename L, typename R> class Or_r : public Coroutine { L l; R r; public: Or_r(const L & l, const R & r) : l(l), r(r) { } bool operator() (void) { co_begin(); while(l()) co_yield(true); while(r()) co_yield(true); co_end(); } }; #ifdef CASTOR_USE_GENERIC_OR template<typename L, typename R> inline Or_r<L,R> operator || (const L& l, const R & r) { return Or_r<L,R>(l, r); } #else inline Or_r<relation,relation> operator || (const relation& l, const relation& r) { return Or_r<relation,relation>(l, r); } #endif //--------------------------------------------------------------- // Relational AND operator //--------------------------------------------------------------- template<typename L, typename R, bool fast=false> class And_r : public Coroutine { L l; relation r; R rbegin; public: And_r(const L& l, const R& r) : l(l), r(r), rbegin(r) { } bool operator () (void) { // SLOW co_begin(); while(l()) { while(r()) co_yield(true); r=rbegin; } co_end(); } }; template<typename L, typename R> class And_r <L,R,true> : public Coroutine { L l; R r; public: And_r(const L& l, const R& r) : l(l), r(r) { } bool operator () (void) { co_begin(); while(l()) { if(r()) co_yield(true); r.reset(); } co_end(); } }; namespace detail { struct twoBytes { char a[2]; }; template<typename T> char fastAndCheck(typename T::UseFastAnd *); template<typename T> twoBytes fastAndCheck(...); } // namespace detail template<typename T> struct IsTestOnlyRelation { enum {result=( sizeof(::castor::detail::fastAndCheck<T>(0))==1 )}; }; template<typename Rel> struct IsRelation_Constraint { static void constraints(Rel a) { relation r = a; } }; #ifdef CASTOR_USE_GENERIC_AND template<typename L, typename R> inline And_r<L,R,IsTestOnlyRelation<R>::result> operator && (const L & l, const R & r) { return And_r<L,R,IsTestOnlyRelation<R>::result>(l, r); } #else #if defined(CASTOR_DISABLE_AND_OPTIMIZATION) inline And_r<relation,relation, false> operator && (const relation & l, const relation & r) { return And_r<relation, relation, false>(l, r); } #else template<typename R> inline And_r<relation,R,IsTestOnlyRelation<R>::result> operator && (const relation & l, const R & r) { return And_r<relation, R, IsTestOnlyRelation<R>::result>(l, r); } #endif #endif template<typename L, typename R> class ExOr_r : public Coroutine { L l; R r; bool lSucceeded; public: ExOr_r(const L& l, const R& r) : l(l), r(r), lSucceeded(false) { } bool operator () (void) { co_begin(); while(l()) { lSucceeded=true; co_yield(true); } if(lSucceeded) co_return(false); while(r()) { co_yield(true); } co_end(); } }; #ifdef CASTOR_USE_GENERIC_EXOR template<typename L, typename R> inline ExOr_r<L,R> operator ^ (const L & l, const R & r) { return ExOr_r<L,R>(l, r); } #else inline ExOr_r<relation,relation> operator ^ (const relation & l, const relation & r) { return ExOr_r<relation,relation>(l, r); } #endif } // namespace castor #endif
[ [ [ 1, 200 ] ] ]
785a2968acee3a5b3ac23300a3b0314227b2f999
61fc00b53ce93f09a6a586a48ae9e484b74b6655
/src/tool/src/wrapper/chemical/wrapper_chemicalcmd_to_avoaction.cpp
c37769e8310891c503fa776faf653c6aa0dbd82b
[]
no_license
mickaelgadroy/wmavo
4162c5c7c8d9082060be91e774893e9b2b23099b
db4a986d345d0792991d0e3a3d728a4905362a26
refs/heads/master
2021-01-04T22:33:25.103444
2011-11-04T10:44:50
2011-11-04T10:44:50
1,381,704
2
0
null
null
null
null
UTF-8
C++
false
false
59,177
cpp
/******************************************************************************* Copyright (C) 2010,2011 Mickael Gadroy, University of Reims Champagne-Ardenne (Fr) Project managers: Eric Henon and Michael Krajecki Financial support: Region Champagne-Ardenne (Fr) Some portions : Copyright (C) 2007-2009 Marcus D. Hanwell Copyright (C) 2006,2008,2009 Geoffrey R. Hutchison Copyright (C) 2006,2007 Donald Ephraim Curtis Copyright (C) 2008,2009 Tim Vandermeersch This file is part of WmAvo (WiiChem project) WmAvo - Integrate the Wiimote and the Nunchuk in Avogadro software for the handling of the atoms and the camera. For more informations, see the README file. WmAvo 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. WmAvo 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 WmAvo. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ #include "wrapper_chemicalcmd_to_avoaction.h" #include "wmtool.h" #include "moleculemanipulation.h" #include "contextmenu_to_avoaction.h" namespace Avogadro { const Eigen::Vector3d WrapperChemicalCmdToAvoAction::m_vect3d0(Eigen::Vector3d(0., 0., 0.)) ; Eigen::Transform3d WrapperChemicalCmdToAvoAction::m_transf3d0 ; const QPoint WrapperChemicalCmdToAvoAction::m_qpoint0(QPoint(0,0)) ; const double WrapperChemicalCmdToAvoAction::m_PI180=M_PI/180.0 ; const double WrapperChemicalCmdToAvoAction::m_180PI=180.0/M_PI ; WrapperChemicalCmdToAvoAction::WrapperChemicalCmdToAvoAction ( GLWidget *widget, WITD::ChemicalWrap *chemWrap, InputDevice::WmDevice *wmdev ) : m_widget(widget), m_moleculeManip(NULL), m_wmDev(wmdev), m_isCalculDistDiedre(false), m_isMoveAtom(false), m_tmpBarycenter(m_vect3d0), m_isRenderRect(false), m_rectP1(m_qpoint0), m_rectP2(m_qpoint0), m_needAnUpdateMore(false), m_isAtomDraw(false), m_isBondOrder(false), m_drawBeginAtom(false), m_drawCurrentAtom(false), m_drawBond(false), m_hasAddedBeginAtom(false), m_hasAddedCurAtom(false), m_hasAddedBond(false), m_beginPosDraw(m_vect3d0), m_curPosDraw(m_vect3d0), m_lastCursor(m_qpoint0), m_beginAtomDraw(NULL), m_curAtomDraw(NULL), m_bondDraw(NULL), m_timeFirst(0), m_timeSecond(0), m_canDrawOther(false) { /// Initiate the objects. m_moleculeManip = new MoleculeManipulation( widget->molecule() ) ; m_contextMenu = new ContextMenuToAvoAction( widget, m_moleculeManip, chemWrap ) ; m_transf3d0.matrix().setIdentity() ; /// Initiate some attributs to realize mouse simulations. m_testEventPress = false ; m_p = new QPoint(1,1) ; m_me1 = new QMouseEvent(QEvent::MouseButtonPress, *m_p, Qt::LeftButton, Qt::NoButton, Qt::NoModifier) ; m_me2 = new QMouseEvent(QEvent::MouseMove, *m_p, Qt::NoButton, Qt::LeftButton, Qt::NoModifier) ; m_me3 = new QMouseEvent(QEvent::MouseButtonRelease, *m_p, Qt::LeftButton, Qt::NoButton, Qt::NoModifier) ; m_time.start() ; m_nbUpdate1 = new WIWO<unsigned int>(20) ; m_nbUpdate2 = new WIWO<unsigned int>(20) ; m_nbUpdate3 = new WIWO<unsigned int>(20) ; } WrapperChemicalCmdToAvoAction::~WrapperChemicalCmdToAvoAction() { if( m_me1 != NULL ){ delete( m_me1 ) ; m_me1=NULL ; } if( m_me2 != NULL ){ delete( m_me2 ) ; m_me2=NULL ; } if( m_me3 != NULL ){ delete( m_me3 ) ; m_me3=NULL ; } if( m_p != NULL ){ delete( m_p ) ; m_p=NULL ; } if( m_nbUpdate1 != NULL ){ delete( m_nbUpdate1 ) ; m_nbUpdate1=NULL ; } if( m_nbUpdate2 != NULL ){ delete( m_nbUpdate2 ) ; m_nbUpdate2=NULL ; } if( m_nbUpdate3 != NULL ){ delete( m_nbUpdate3 ) ; m_nbUpdate3=NULL ; } } MoleculeManipulation* WrapperChemicalCmdToAvoAction::getMoleculeManip() { return m_moleculeManip ; } ContextMenuToAvoAction* WrapperChemicalCmdToAvoAction::getContextMenu() { return m_contextMenu ; } /** * Transform a wrapper action to an Avogadro action. * @param wmData All Wiimote data get. */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToAvoAction( WITD::ChemicalWrapData_from *data ) { WITD::ChemicalWrapData_from::wrapperActions_t wa ; WITD::ChemicalWrapData_from::positionCamera_t pc ; WITD::ChemicalWrapData_from::positionPointed_t pp ; //bool upWa=data->getWrapperAction( wa ) ; //bool upPc=data->getPositionCamera( pc ) ; //bool upPp=data->getPositionPointed( pp ) ; wa = data->getWrapperAction() ; pc = data->getPositionCamera() ; pp = data->getPositionPointed() ; QPoint posCursor=pp.posCursor ; int state=wa.actionsWrapper ; Eigen::Vector3d pos3dCurrent=pp.pos3dCur ; Eigen::Vector3d pos3dLast=pp.pos3dLast ; double rotCamAxeXDeg=pc.angleRotateDegree[0] ; double rotCamAxeYDeg=pc.angleRotateDegree[1] ; double distCamXTranslate=pc.distanceTranslate[0] ; double distCamYTranslate=pc.distanceTranslate[1] ; double distCamZoom=pc.distanceTranslate[2] ; //cout << nbDotsDetected << " " << nbSourcesDetected << " " << distBetweenSource << endl ; // Adjustment for the rotation of atoms. if( WMAVO_IS2(state,WMAVO_CAM_ROTATE_BYWM) && m_widget->selectedPrimitives().size()>=2 ) { // Disable the context menu action. WMAVO_SETOFF2( state, WMAVO_CAM_ROTATE_BYWM ) ; WMAVO_SETON2( state, WMAVO_ATOM_MOVE ) ; WMAVO_SETON2( state, WMAVO_ATOM_ROTATE ) ; } const Eigen::Vector3d pointRef=m_moleculeManip->getBarycenterMolecule() ; transformWrapperActionToMoveAtom( state, pointRef, pos3dCurrent, pos3dLast, rotCamAxeXDeg, rotCamAxeYDeg ) ; transformWrapperActionToMoveMouse( state, posCursor ) ; transformWrapperActionToSelectAtom( state, posCursor ) ; transformWrapperActionToCreateAtomBond( state, pointRef, posCursor ) ; transformWrapperActionToDeleteAllAtomBond( state ) ; transformWrapperActionToRemoveAtomBond( state, posCursor ) ; transformWrapperActionToRotateCamera( state, pointRef, rotCamAxeXDeg, rotCamAxeYDeg ) ; transformWrapperActionToTranslateCamera( state, pointRef, distCamXTranslate, distCamYTranslate ) ; transformWrapperActionToZoomCamera( state, pointRef, distCamZoom ) ; transformWrapperActionToInitiateCamera( state, pointRef ) ; transformWrapperActionToSaturateAtoms( state ) ; transformWrapperActionToUseContextMenu( state, posCursor ) ; transformWrapperActionToAvoUpdate( state ) ; } void WrapperChemicalCmdToAvoAction::transformWrapperActionToAvoUpdate( int state ) { // // Update Avogadro to see modification. updateForAvoActions1( state ) ; updateForAvoActions2( state ) ; updateForAvoActions3( state ) ; } /** * Transform a wrapper action to an Avogadro action : move the mouse cursor. * @param wmavoAction All actions ask by the wrapper * @param posCursor The new position of the mouse cursor */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveMouse( int wmavoAction, const QPoint& posCursor ) { if( WMAVO_IS2(wmavoAction,WMAVO_CURSOR_MOVE) || WMAVO_IS2(wmavoAction,WMAVO_CREATE) ) { //cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveMouse" << endl ; QCursor::setPos(posCursor) ; } } /** * Transform a wrapper action to an Avogadro action : select an atom, * (or a bond to initiate a rotation axe). * @param wmavoAction All actions ask by the wrapper * @param posCursor The position where a "click" is realised */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom( int wmavoAction, const QPoint& posCursor ) { if( WMAVO_IS2(wmavoAction,WMAVO_SELECT) || WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI) ) { //cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom" << endl ; if( WMAVO_IS2(wmavoAction,WMAVO_SELECT) ) { // Select only 1 object. /* { // Test to add a real mouse click // - Code occurs crash. // - It can't access to the menu pull-down. QPoint p=QCursor::pos() ; //QCoreApplication *app=QCoreApplication::instance() ; //QWidget *widget=app->widgetAt( p ) ; QWidget *widget=QApplication::widgetAt( p ) ; //QWidget *widget=QApplication::activeWindow() ; if( widget!=NULL ) { mytoolbox::dbgMsg( widget->accessibleName() ) ; QPoint p2=widget->mapFromGlobal(p) ; QEvent *me1 = new QMouseEvent( QEvent::MouseButtonPress, p2, Qt::LeftButton, Qt::NoButton, Qt::NoModifier ) ; QEvent *me3 = new QMouseEvent( QEvent::MouseButtonRelease, p2, Qt::LeftButton, Qt::NoButton, Qt::NoModifier ) ; QApplication::postEvent( widget, me1 ) ; QApplication::postEvent( widget, me3 ) ; } else { mytoolbox::dbgMsg( "nada" ) ; } } */ // Just one rumble. InputDevice::RumbleSettings rumble( false, false, 10 ) ; rumble.setStart( true ) ; rumble.setDistance( 0 ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; QPoint p=m_widget->mapFromGlobal(posCursor) ; bool hasAddHydrogen=m_moleculeManip->hasAddedHydrogen() ; Atom *atom=NULL ; Bond *bond=NULL ; // One method: // Not adapted here: atom = m_widget->computeClickedAtom( p ) ; // OR, // use the method below : QList<GLHit> hits=m_widget->hits( p.x()-5, p.y()-5, 10, 10 ) ; // Search the 1st primitive which is interesting. foreach( const GLHit& hit, hits ) { if( hit.type() == Primitive::AtomType ) { atom = m_widget->molecule()->atom( hit.name() ) ; break ; } if( hit.type() == Primitive::BondType ) { bond = m_widget->molecule()->bond( hit.name() ) ; break ; } } if( atom==NULL && bond==NULL ) { // No selection. m_widget->clearSelected() ; m_moleculeManip->resetRotationAxe() ; } else if( bond != NULL ) { // Bond selection. // Get the previous bond. Bond *oldBond=m_moleculeManip->getRotationAxeBond() ; // Check if identical with the new. if( oldBond!=NULL && oldBond==bond ) { // Disable it. m_moleculeManip->resetRotationAxe() ; PrimitiveList pl ; pl.append( oldBond ) ; m_widget->setSelected( pl, false ) ; } else { // Enable the new, and disable the old. m_moleculeManip->setRotationAxe( bond ) ; if( oldBond != NULL ) { // Unselect the previous bond used to the rotation axe. PrimitiveList pl ; pl.append( oldBond ) ; m_widget->setSelected( pl, false ) ; } // Select the new bond used to the rotation axe. PrimitiveList pl ; pl.append( bond ) ; m_widget->setSelected( pl, true ) ; } } else if( atom != NULL ) { // Atom seletion. m_moleculeManip->resetRotationAxe() ; if( m_isCalculDistDiedre ) { // Manage the selection of atom for the calculation of distance & Co. // It works with an association of the WmTool class. // Put the "calcul distance" mode of the WrapperChemicalCmdToAvoAction class to off. m_isCalculDistDiedre = false ; // Inform the WmTool class of the selected atom. emit sendAtomToCalculDistDiedre( atom ) ; // To wmTool. // Nota Bene : it is the WmTool class which infoms the WrapperChemicalCmdToAvoAction class when // it is necessary to select an atom for the "calcul distance" mode. } else { // Manage the selection of one atom. QList<Primitive*> hitList ; hitList.append(atom) ; m_widget->toggleSelected(hitList) ; //m_widget->setSelected(hitList, true) ; // Select H-neighbors. if( hasAddHydrogen && m_widget->isSelected(static_cast<Primitive*>(atom)) && !atom->isHydrogen() ) { Atom *a=NULL ; PrimitiveList pl ; foreach( unsigned long ai, atom->neighbors() ) { a = m_widget->molecule()->atomById(ai) ; if( a!=NULL && a->isHydrogen() ) pl.append( a ) ; } m_widget->setSelected( pl, true) ; } } } } else //if( WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI) ) { // Multiple selection. // For the display of the selection rectangle. if( !m_isRenderRect ) { // Save the 1st point of the rectangle. m_isRenderRect = true ; m_rectP1 = posCursor ; } // Save the 2nd point of the rectangle. m_rectP2 = posCursor ; QPoint p1=m_widget->mapFromGlobal(m_rectP1) ; QPoint p2=m_widget->mapFromGlobal(m_rectP2) ; // Adjust the 1st point always at bottom/left, // the 2nd point always at up/right. int x1=( p1.x()<p2.x() ? p1.x() : p2.x() ) ; int y1=( p1.y()<p2.y() ? p1.y() : p2.y() ) ; int x2=( p1.x()>p2.x() ? p1.x() : p2.x() ) - 1 ; int y2=( p1.y()>p2.y() ? p1.y() : p2.y() ) - 1 ; // Inform the WmTool class of the 2 points of the selection rectangle for the display. emit renderedSelectRect( true, QPoint(x1,y1), QPoint(x2,y2) ) ; } } else { if( m_isRenderRect ) { // // 1. Realize the selection QList<GLHit> hitList ; PrimitiveList pList ; Primitive *p=NULL ; Atom *a=NULL ; QPoint p1=m_widget->mapFromGlobal(m_rectP1) ; QPoint p2=m_widget->mapFromGlobal(m_rectP2) ; int x1=( p1.x()<p2.x() ? p1.x() : p2.x() ) ; int y1=( p1.y()<p2.y() ? p1.y() : p2.y() ) ; int x2=( p1.x()>p2.x() ? p1.x() : p2.x() ) ; // - 1 ; int y2=( p1.y()>p2.y() ? p1.y() : p2.y() ) ; // - 1 ; // Perform an OpenGL selection and retrieve the list of hits. hitList = m_widget->hits( x1, y1, x2-x1, y2-y1 ) ; if( hitList.empty() ) { m_widget->clearSelected() ; } else { // Build a primitiveList for toggleSelected() method. foreach( const GLHit& hit, hitList ) { if( hit.type() == Primitive::AtomType ) { a = m_widget->molecule()->atom( hit.name() ) ; p = static_cast<Primitive *>( a ) ; if( p != NULL ) pList.append( p ) ; else mytoolbox::dbgMsg( "Bug in WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom : a NULL-object not expected." ) ; } } // Toggle the selection. m_widget->toggleSelected( pList ) ; // or setSelected() //cout << "toggle primitive" << endl ; } // // 2. Finish the action. m_isRenderRect = false ; m_needAnUpdateMore = true ; m_rectP1 = QPoint( 0, 0 ) ; m_rectP2 = QPoint( 0, 0 ) ; p1 = m_widget->mapFromGlobal(m_rectP1) ; p2 = m_widget->mapFromGlobal(m_rectP2) ; emit renderedSelectRect( false, p1, p2) ; } } } /** * Transform a wrapper action to an Avogadro action : move the selected atoms. * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point * @param pos3dCurrent The current position calculate by the Wiimote * @param pos3dLast The last position calculate by the Wiimote * @param rotAtomDegX The desired X-axis angle * @param rotAtomDegY The desired Y-axis angle */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveAtom ( int wmavoAction, const Eigen::Vector3d& pointRef, const Eigen::Vector3d& pos3dCurrent, const Eigen::Vector3d& pos3dLast, double rotAtomDegX, double rotAtomDegY ) { if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_MOVE) ) { // Object is in "travel mode", but just in the mode. // It is necessary to know what is the movement. if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE) ) { // Work when an atom is moving. If no movement, do not pass here. //cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveAtom" << endl ; Eigen::Vector3d vectAtomTranslate ; Eigen::Transform3d transfAtomRotate ; bool isMoved=calculateTransformationMatrix ( wmavoAction, pos3dCurrent, pos3dLast, pointRef, rotAtomDegX, rotAtomDegY, vectAtomTranslate, transfAtomRotate ) ; if( isMoved ) { if( !m_isMoveAtom ) m_isMoveAtom = true ; QList<Primitive*> pList=m_widget->selectedPrimitives().subList(Primitive::AtomType) ; if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) ) m_moleculeManip->tranlateAtomBegin( pList, vectAtomTranslate ) ; else if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE) ) m_moleculeManip->rotateAtomBegin( pList, transfAtomRotate ) ; // Active rumble in the Wiimote only if one atom is selected. if( pList.size() == 1 ) { Atom *a=static_cast<Atom*>(pList.at(0)) ; if( a != NULL ) { Atom *an=m_moleculeManip->calculateNearestAtom( a->pos(), a ) ; Eigen::Vector3d dist = *(a->pos()) - *(an->pos()) ; double act = dist.norm() ; InputDevice::RumbleSettings rumble( false, true ) ; rumble.setStart( true ) ; rumble.setDistance( act, WMRUMBLE_MIN_DISTANCE, WMRUMBLE_MAX_DISTANCE ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; } } } } } else { // Finish the action. if( m_isMoveAtom ) // Caution, this attribut is initialised/used in moveAtom*() methods. { m_isMoveAtom = false ; QList<Primitive*> pList=m_widget->selectedPrimitives().subList(Primitive::AtomType) ; m_moleculeManip->moveAtomEnd( pList ) ; InputDevice::RumbleSettings rumble( false, false ) ; rumble.setStart( false ) ; rumble.setDistance( 0 ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; m_tmpBarycenter = m_vect3d0 ; } } } /** * Transform a wrapper action to an Avogadro action : create atom(s) and bond(s). * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point * @param posCursor The position of the cursor */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToCreateAtomBond ( int wmavoAction, const Eigen::Vector3d& pointRef, const QPoint &posCursor ) { if( WMAVO_IS2(wmavoAction,WMAVO_CREATE) || m_isAtomDraw ) // for m_isAtomDraw : Necessary for the action of "isCreateAtom". { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToCreateAtomBond" ; Molecule *mol=m_widget->molecule() ; // molecule->lock()->tryLockForWrite() : // GLWidget::render(): Could not get read lock on molecule. // Lock the write on the molecule => so it locks the render too ... // This means the possibility that the Avogadro software can be really multi-thread // (or in anticipation). // The lock justifies it by the array used to store a new atom, and with the search // of a new id for this new atom y tutti quanti ... //if( molecule->lock()->tryLockForWrite() ) //{ // Add an atom. QPoint p=m_widget->mapFromGlobal(posCursor) ; if( !m_isAtomDraw ) { // The 1st action : a request of creation m_lastCursor = p ; Primitive* prim=m_widget->computeClickedPrimitive( p ) ; m_timeFirst = m_time.elapsed() ; if( prim == NULL ) { m_isAtomDraw = true ; m_drawBeginAtom = true ; m_drawCurrentAtom = false ; m_drawBond = false ; //cout << "cursor position:" << p.x() << "," << p.y() << endl ; //cout << "ref position:" << pointRef[0] << "," << pointRef[1] << "," << pointRef[2] << endl ; m_beginPosDraw = m_widget->camera()->unProject( p, pointRef ) ; m_curPosDraw = m_beginPosDraw ; } else if( prim->type() == Primitive::AtomType ) { m_isAtomDraw = true ; m_drawBeginAtom = false ; m_drawCurrentAtom = false ; m_drawBond = false ; m_beginAtomDraw = static_cast<Atom*>(prim) ; m_beginPosDraw = *(m_beginAtomDraw->pos()) ; m_curPosDraw = m_beginPosDraw ; } else if( prim->type() == Primitive::BondType ) { m_isBondOrder = true ; m_isAtomDraw = true ; m_drawBeginAtom = false ; m_drawCurrentAtom = false ; m_drawBond = false ; m_bondDraw = static_cast<Bond*>(prim) ; } //else // Nothing to do. // Request the temporary display of the 1st atom(by the WmTool class). if( m_isAtomDraw || m_isBondOrder ) emit renderedAtomBond( m_beginPosDraw, m_curPosDraw, m_drawBeginAtom, m_drawCurrentAtom, m_drawBond ) ; } else if( m_isAtomDraw && WMAVO_IS2(wmavoAction,WMAVO_CREATE) && !m_isBondOrder ) { // The 2nd action. // That means, the 1st atom has been "selected/created" and // the mouse is moving to create/select an 2nd atom with (new) bond. // Timeout before to create a 2nd atom. if( !m_canDrawOther ) { m_timeSecond = m_time.elapsed() ; if( (m_timeSecond-m_timeFirst) > 1000 ) m_canDrawOther = true ; } if( m_canDrawOther ) { m_curPosDraw = m_widget->camera()->unProject(p, pointRef) ; Atom *an = m_moleculeManip->calculateNearestAtom( &m_curPosDraw, NULL ) ; if( an != NULL ) { Eigen::Vector3d dist=m_curPosDraw - *(an->pos()) ; double act=dist.norm() ; // Activate rumble. InputDevice::RumbleSettings rumble( false, true ) ; rumble.setStart( true ) ; rumble.setDistance( act, WMRUMBLE_MIN_DISTANCE, WMRUMBLE_MAX_DISTANCE ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; } // Methode0 : SPEED !! Atom* a=NULL ; // Methode1 : SLOW !! //a = m_widget->computeClickedAtom( p ) ; // Methode2 : SLOW !! /* QList<GLHit> hits=m_widget->hits( p.x()-5, p.y()-5, 10, 10 ) ; foreach( const GLHit& hit, hits ) { if( hit.type() == Primitive::AtomType ) { // Le 1er element est le plus proche. a = m_widget->molecule()->atom( hit.name() ) ; break ; } }*/ if( a == NULL ) { double var1=m_beginPosDraw[0]-m_curPosDraw[0] ; double var2=m_beginPosDraw[1]-m_curPosDraw[1] ; double var3=m_beginPosDraw[2]-m_curPosDraw[2] ; double distVect=sqrt( var1*var1 + var2*var2 + var3*var3 ) ; // Draw a 2nd atom only if the distance is bigger than ... if( distVect > WMEX_DISTBEFORE_CREATE ) { //cout << "Display current atom & bond" << endl ; m_drawCurrentAtom = true ; if( m_beginAtomDraw!=NULL && m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count()>0 ) m_drawBond = false ; else m_drawBond = true ; m_curAtomDraw = a ; } else { m_drawCurrentAtom = false ; m_drawBond = false ; m_curAtomDraw = NULL ; } } else if( *(a->pos()) == m_beginPosDraw ) { //cout << "Display nothing" << endl ; m_drawCurrentAtom = false ; m_drawBond = false ; m_curAtomDraw = NULL ; } else //if( a ) { //cout << "Display Bond" << endl ; m_drawCurrentAtom = false ; m_drawBond = true ; // Limit the number of bond if Hydrogen Atom. if( a->isHydrogen() && a->bonds().count() > 0 ) m_drawBond = false ; if( m_drawBond && m_beginAtomDraw!=NULL && m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count() > 0 ) m_drawBond = false ; m_curAtomDraw = a ; m_curPosDraw = *(a->pos()) ; } // Request the temporary display of the atoms and bond (by the WmTool class). emit renderedAtomBond( m_beginPosDraw, m_curPosDraw, m_drawBeginAtom, m_drawCurrentAtom, m_drawBond ) ; } } else if( m_isAtomDraw && !WMAVO_IS2(wmavoAction,WMAVO_CREATE) ) { // The 3rd and last action : creation // - either adjust number of bond ; // - or create atoms(s) and bond. bool addSmth=false ; //QUndoCommand *undo=NULL ; if( m_isBondOrder ) { //int oldBondOrder = m_bondDraw->order() ; #if !AVO_DEPRECATED_FCT // 1. m_moleculeManip->changeOrderBondBy1( m_bondDraw ) ; #else // 2. undo = new ChangeBondOrderDrawCommand( m_bondDraw, oldBondOrder, m_addHydrogens ) ; m_widget->undoStack()->push( undo ) ; #endif } else //if( m_isAtomDraw && !m_isBondOrder ) { //cout << "End of the creation of atom/bond" << endl ; Atom* a=NULL ; Eigen::Vector3d addAtomPos ; InputDevice::RumbleSettings rumble( false, false ) ; rumble.setStart( false ) ; rumble.setDistance( 0 ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; if( m_beginAtomDraw == NULL ) { addSmth = true ; m_hasAddedBeginAtom = true ; } // Timeout before to create a 2nd atom. if( !m_canDrawOther ) { m_timeSecond = m_time.elapsed() ; if( (m_timeSecond-m_timeFirst) > 1000 ) m_canDrawOther = true ; } // Add 2nd atom & bond. if( m_canDrawOther ) { a = m_widget->computeClickedAtom( p ) ; if( a == NULL ) { // Create atome/bond. double var1=m_beginPosDraw[0]-m_curPosDraw[0] ; double var2=m_beginPosDraw[1]-m_curPosDraw[1] ; double var3=m_beginPosDraw[2]-m_curPosDraw[2] ; double distVect=sqrt( var1*var1 + var2*var2 + var3*var3 ) ; // Draw a 2nd atom only if the distance is bigger than ... if( distVect > 0.6 ) { addAtomPos = m_widget->camera()->unProject( p, pointRef ) ; addSmth = true ; m_hasAddedCurAtom = true ; if( m_drawBond /* !(m_curAtomDraw->isHydrogen() && m_curAtomDraw->bonds().count()>0) && !(m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count()>0) */ ) m_hasAddedBond = true ; } } else { // Create bond. if( *(a->pos()) != m_beginPosDraw && mol->bond(a,m_beginAtomDraw) == NULL && m_drawBond /* !(a->isHydrogen() && a->bonds().count()>0) && !(m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count()>0) */ ) { m_curAtomDraw = a ; addSmth = true ; m_hasAddedBond = true ; } } } if( mol->lock()->tryLockForWrite() ) { int atomicNumber=m_moleculeManip->getAtomicNumberCurrent() ; // Create just the 1st atom. if( m_hasAddedBeginAtom && !m_hasAddedCurAtom && !m_hasAddedBond ) m_beginAtomDraw = m_moleculeManip->addAtom( &m_beginPosDraw, atomicNumber ) ; // Create just the 2nd atom. if( !m_hasAddedBeginAtom && m_hasAddedCurAtom && !m_hasAddedBond ) m_curAtomDraw = m_moleculeManip->addAtom( &addAtomPos, atomicNumber ) ; // Create just the bond. if( !m_hasAddedBeginAtom && !m_hasAddedCurAtom && m_hasAddedBond ) m_bondDraw = m_moleculeManip->addBond( m_beginAtomDraw, a, 1 ) ; // Create the 2nd atom bonded at 1st. if( !m_hasAddedBeginAtom && m_hasAddedCurAtom && m_hasAddedBond ) m_curAtomDraw = m_moleculeManip->addAtom ( &addAtomPos, atomicNumber, m_beginAtomDraw, 1 ) ; // Create the 1st atom bonded at 2nd. if( m_hasAddedBeginAtom && !m_hasAddedCurAtom && m_hasAddedBond ) m_beginAtomDraw = m_moleculeManip->addAtom ( &m_beginPosDraw, atomicNumber, m_curAtomDraw, 1 ) ; // Create 2 atoms. if( m_hasAddedBeginAtom && m_hasAddedCurAtom ) { int order=0 ; PrimitiveList *pl=NULL ; if( m_hasAddedBond ) order = 1 ; pl = m_moleculeManip->addAtoms ( &m_beginPosDraw, atomicNumber, &addAtomPos, atomicNumber, order ) ; if( pl!=NULL && pl->size()>=2 ) { PrimitiveList::const_iterator ipl=pl->begin() ; m_beginAtomDraw = static_cast<Atom*>(*ipl) ; ipl++ ; m_curAtomDraw = static_cast<Atom*>(*ipl) ; } if( pl != NULL ) delete pl ; } // Substitute atom by atom. if( !m_hasAddedBeginAtom && !m_hasAddedCurAtom && !m_hasAddedBond && !m_canDrawOther ) m_moleculeManip->changeAtomicNumber( m_beginAtomDraw, atomicNumber ) ; GLfloat projectionMatrix[16] ; glGetFloatv( GL_PROJECTION_MATRIX, projectionMatrix ) ; //cout << "Projection Matrix:" << endl ; //cout<<" "<<projectionMatrix[0]<<" "<<projectionMatrix[4]<<" "<<projectionMatrix[8]<<" "<<projectionMatrix[12]<<endl; //cout<<" "<<projectionMatrix[1]<<" "<<projectionMatrix[5]<<" "<<projectionMatrix[9]<<" "<<projectionMatrix[13]<<endl; //cout<<" "<<projectionMatrix[2]<<" "<<projectionMatrix[6]<<" "<<projectionMatrix[10]<<" "<<projectionMatrix[14]<<endl; //cout<<" "<<projectionMatrix[3]<<" "<<projectionMatrix[7]<<" "<<projectionMatrix[11]<<" "<<projectionMatrix[15]<<endl; } mol->lock()->unlock() ; } mol->update() ; if( addSmth ) { InputDevice::RumbleSettings rumble( false, false, 10 ) ; rumble.setStart( true ) ; rumble.setDistance( 0 ) ; InputDevice::WmDeviceData_to wmDevDataTo ; wmDevDataTo.setRumble( rumble ) ; m_wmDev->setDeviceDataTo( wmDevDataTo ) ; } //addAdjustHydrogenRedoUndo( molecule ) ; // Initialization before next use. m_isBondOrder=false ; m_isAtomDraw=false ; m_drawBeginAtom=false ; m_drawCurrentAtom=false ; m_drawBond=false ; m_hasAddedBeginAtom=false ; m_hasAddedCurAtom=false ; m_hasAddedBond=false ; m_beginAtomDraw=NULL ; m_curAtomDraw=NULL ; m_bondDraw=NULL ; m_timeFirst=0 ; m_timeSecond=0 ; m_canDrawOther = false ; // "Push" all modifications & redraw of the molecule. emit renderedAtomBond( m_vect3d0, m_vect3d0, false, false, false ) ; } //} } } /** * Transform a wrapper action to an Avogadro action : delete all atom. * @param wmavoAction All actions ask by the wrapper */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToDeleteAllAtomBond( int wmavoAction ) { if( WMAVO_IS2(wmavoAction,WMAVO_DELETEALL) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToDeleteAllAtomBond" ; m_moleculeManip->deleteAllElement() ; } } /** * Transform a wrapper action to an Avogadro action : delete atom(s). * @param wmavoAction All actions ask by the wrapper * @param posCursor The position of the cursor */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToRemoveAtomBond( int wmavoAction, const QPoint &posCursor ) { if( WMAVO_IS2(wmavoAction,WMAVO_DELETE) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToRemoveAtomBond" ; Molecule *mol=m_widget->molecule() ; if( mol->lock()->tryLockForWrite() ) { QPoint p=m_widget->mapFromGlobal(posCursor) ; Primitive* prim=m_widget->computeClickedPrimitive( p ) ; PrimitiveList pl=m_widget->selectedPrimitives() ; if( prim == NULL ) { // Remove the selected atoms. #if !AVO_DEPRECATED_FCT m_moleculeManip->removeAtoms( &pl ) ; #else // 2. with undo/redo, not adjust hydrogen ... deleteSelectedElementUndoRedo( mol ) ; #endif } else { if( prim->type() == Primitive::AtomType ) { // Remove atom. Atom *atom = static_cast<Atom*>(prim) ; m_moleculeManip->removeAtom( atom ) ; } if( prim->type() == Primitive::BondType ) { // Remove bond. Bond *bond = static_cast<Bond*>(prim) ; #if !AVO_DEPRECATED_FCT // 1. m_moleculeManip->removeBond( bond ) ; #else // 2. deleteBondWithUndoRedo( bond ) ; #endif } } mol->lock()->unlock() ; } } } /** * Transform a wrapper action to an Avogadro action : rotate the camera. * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point * @param rotCamAxeXDeg The desired angle on the X-axis of the screen * @param rotCamAxeYDeg The desired angle on the Y-axis of the screen */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToRotateCamera ( int wmavoAction, const Eigen::Vector3d &pointRef, double rotCamAxeXDeg, double rotCamAxeYDeg ) { if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToRotateCamera" ; if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE_BYWM) ) { // If use the cross of the Wiimote. // Use this method to get the wanted angle of rotation. // Value in (radian / Avogadro::ROTATION_SPEED) == the desired angle. double rotCamAxeXRad = (rotCamAxeXDeg*m_PI180) / Avogadro::ROTATION_SPEED ; double rotCamAxeYRad = (rotCamAxeYDeg*m_PI180) / Avogadro::ROTATION_SPEED ; Navigate::rotate( m_widget, pointRef, rotCamAxeXRad, rotCamAxeYRad ) ; } else if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE_BYNC) ) { // Turn in a direction. // Do not search an unit speed or other, just a direction. Navigate::rotate( m_widget, pointRef, rotCamAxeXDeg, rotCamAxeYDeg ) ; } } } /** * Transform a wrapper action to an Avogadro action : translate the camera. * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point * @param distCamXTranslate Desired distance on the X-axis of the screen * @param distCamYTranslate Desired distance on the Y-axis of the screen */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToTranslateCamera ( int wmavoAction, const Eigen::Vector3d &pointRef, double distCamXTranslate, double distCamYTranslate ) { if( WMAVO_IS2(wmavoAction,WMAVO_CAM_TRANSLATE) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToTranslateCamera" ; Navigate::translate( m_widget, pointRef, distCamXTranslate, distCamYTranslate ) ; } } /** * Transform a wrapper action to an Avogadro action : zoom the camera. * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point * @param distCamZoom Desired distance for the zoom on the Z-axis of the screen */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToZoomCamera ( int wmavoAction, const Eigen::Vector3d &pointRef, double distCamZoom ) { if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ZOOM) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToZoomCamera" ; Navigate::zoom( m_widget, pointRef, distCamZoom ) ; } } /** * Transform a wrapper action to an Avogadro action : initiate the camera. * @param wmavoAction All actions ask by the wrapper * @param pointRef The position of the reference point. */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToInitiateCamera ( int wmavoAction, const Eigen::Vector3d &pointRef ) { if( WMAVO_IS2(wmavoAction,WMAVO_CAM_INITIAT) ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToInitiateCamera" ; #if 0 // 1 //m_widget->camera()->setModelview( m_cameraInitialViewPoint ) ; if( !( ((rotCamAxeXDeg==90.0 || rotCamAxeXDeg==-90.0) && rotCamAxeYDeg==0.0) || ((rotCamAxeYDeg==90.0 || rotCamAxeYDeg==-90.0) && rotCamAxeXDeg==0.0) ) ) { // If not use the cross of the Wiimote. // 2 //mytoolbox::dbgMsg( "pointRefRot:" << pointRefRot[0] << pointRefRot[1] << pointRefRot[2] ; //Navigate::translate( m_widget, pointRefRot, -pointRefRot[0], -pointRefRot[1] ) ; // 3 Eigen::Vector3d barycenterScreen=m_widget->camera()->project(pointRefRot) ; QPoint barycenterScreen2(barycenterScreen[0], barycenterScreen[1]) ; //mytoolbox::dbgMsg( "pointRefRot:" << barycenterScreen[0] << barycenterScreen[1] << barycenterScreen[2] ; //Navigate::translate( m_widget, pointRefRot, -barycentreEcran[0], -barycentreEcran[1] ) ; // 4 //Navigate::zoom( m_widget, pointRefRot, m_widget->cam_beginPosDrawmera()->distance(pointRefRot)/*+10*/ ) ; //mytoolbox::dbgMsg( " distance:" << m_widget->camera()->distance(pointRefRot) ; // 5 Eigen::Vector3d transformedGoal = m_widget->camera()->modelview() * pointRefRot ; double distance=m_widget->camera()->distance(pointRefRot) ; double distanceToGoal = transformedGoal.norm() ; //mytoolbox::dbgMsg( " distance:" << distance ; //mytoolbox::dbgMsg( " distanceToGoal:" << distanceToGoal ; /* double distanceToGoal = transformedGoal.norm();m_beginPosDraw double t = ZOOM_SPEED * delta; const double minDistanceToGoal = 2.0 * CAMERA_NEAR_DISTANCE; double u = minDistanceToGoal / distanceToGoal - 1.0; if( t < u ) { t = u; Navigate::rotate( m_widget, pointRefRot, rotCamAxeXDeg, rotCamAxeYDeg ) ; } widget->camera()->modelview().pretranslate(transformedGoal * t); */ // 6 //m_widget->camera()->modelview().pretranslate(-transformedGoal /*+ (camBackTransformedZAxis*-40)*/ ) ; //m_widget->camera()->modelview().translate(-transformedGoal /*+ (camBackTransformedZAxis*-10)*/ ) ; // 7 //Eigen::Vector3d camBackTransformedZAxis=m_widget->camera()->transformedZAxis() ; //m_widget->camera()->modelview().translate( camBackTransformedZAxis*-10.0 ) ; distance=m_widget->camera()->distance(pointRefRot) ; distanceToGoal = transformedGoal.norm(); //mytoolbox::dbgMsg( " distance:" << distance ; //mytoolbox::dbgMsg( " distanceToGoal:" << distanceToGoal ; #endif //Eigen::Vector3d barycenterScreen=m_widget->camera()->project(pointRefRot) ; //QPoint barycenterScreen2(barycenterScreen[0], barycenterScreen[1]) ; //mytoolbox::dbgMsg( "pointRefRot:" << barycenterScreen[0] << barycenterScreen[1] << barycenterScreen[2] ; //Eigen::Transform3d cam=m_widget->camera()->modelview() ; /* OK Eigen::Vector3d right(cam(0,0), cam(1,0), cam(2,0)) ; Eigen::Vector3d up(cam(0,1), cam(1,1), cam(2,1)) ; Eigen::Vector3d dir(cam(0,2), cam(1,2), cam(2,2)) ; Eigen::Vector3d pos(cam(0,3), cam(1,3), cam(2,3)) ; cout << "right:" << right << endl ; cout << "dir:" << dir << endl ; cout << "up:" << up << endl ; cout << "pos:" << pos << endl ; */ /* OK cam(0,3) = 0 ; cam(1,3) = 0 ; cam(2,3) = -20 ; */ /* Oui, et non, apres quelques rotations de camera, le barycentre n'est plus centre. mytoolbox::dbgMsg( "pointRefRot:" << pointRefRot[0] << pointRefRot[1] ; cam(0,3) = -pointRefRot[0] ; cam(1,3) = -pointRefRot[1] ; cam(2,3) = -25 ; m_widget->camera()->setModelview(cam) ; */ Eigen::Vector3d barycenterScreen=m_widget->camera()->project( pointRef ) ; QPoint barycenterScreen2((int)barycenterScreen[0], (int)barycenterScreen[1]) ; GLint params[4] ; // Do not work (with .h and compilation flag, the final error is : ~"impossible to use without a first call of glinit"~). //int screen_pos_x = glutGet((GLenum)GLUT_WINDOW_X); //int screen_pos_y = glutGet((GLenum)GLUT_WINDOW_Y); //mytoolbox::dbgMsg( " :" << screen_pos_x << screen_pos_y ; glGetIntegerv( GL_VIEWPORT, params ) ; GLenum errCode ; const GLubyte *errString ; if( (errCode=glGetError()) != GL_NO_ERROR ) { errString = gluErrorString( errCode ) ; fprintf (stderr, "OpenGL Error: %s\n", errString); } GLdouble x=params[0] ; GLdouble y=params[1] ; GLdouble width=params[2] ; GLdouble height=params[3] ; QPoint widgetCenter( (int)((x+width)/2.0), (int)((y+height)/2.0) ) ; Navigate::translate( m_widget, pointRef, barycenterScreen2, widgetCenter ) ; Eigen::Transform3d cam=m_widget->camera()->modelview() ; cam(2,3) = -25 ; m_widget->camera()->setModelview(cam) ; } } /** * Transform a wrapper action to an Avogadro action : enable/disable the atom saturation. * @param wmavoAction All actions ask by the wrapper */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToSaturateAtoms ( int wmavoAction ) { if( WMAVO_IS2(wmavoAction,WMAVO_SATURATE_ATOMS) ) { m_moleculeManip->invertHasAddHydrogen() ; } } /** * Transform a wrapper action to an context menu action. * @param wmavoAction All actions ask by the wrapper * @param posCursor The position of the cursor */ void WrapperChemicalCmdToAvoAction::transformWrapperActionToUseContextMenu( int &wmavoAction, const QPoint &posCursor ) { m_contextMenu->manageAction( wmavoAction, posCursor ) ; } /** * Update Avogadro according to the Avogadro actions realized. * Here, the update is for the Avogadro delete actions. * @param wmavoAction All actions ask by the wrapper */ void WrapperChemicalCmdToAvoAction::updateForAvoActions1( int wmavoAction ) { if( WMAVO_IS2(wmavoAction,WMAVO_DELETE) || WMAVO_IS2(wmavoAction,WMAVO_DELETEALL) /*|| WMAVO_IS2(wmavoAction,WMAVO_CREATE)*/ // Put in the transformWrapperActionToCreateAtomBond() method to // gain update during multiple creation. ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions1" ; // Update // If we have done stuff then trigger a redraw of the molecule m_widget->molecule()->update() ; /* // Not resolve an update problem ... m_widget->molecule()->update() ; m_widget->update() ; // update( &Region ), update( int, int, int, int ) ... m_widget->updateGeometry() ; m_widget->updateGL() ; m_widget->updateOverlayGL() ; m_widget->updatesEnabled() ; //m_widget->molecule()->updateAtom() ; m_widget->molecule()->updateMolecule() ; m_widget->molecule()->calculateGroupIndices() ; */ } } /** * Update Avogadro according to the Avogadro actions realized. * Here, the update is for a lot of Avogadro actions. * This is a special update, because it simulates a mouse click to realize update. * In fact, some optimization are available only when some Avogadro class realize * update. * <br/>To activate the quick render (the previous optimization) , it is necessary to simulate a mouse click. * Explanation, the quick render is activated when : * - Check the quick render option * Set (allowQuickRender) attribut to enable. Now Avogadro MAY accept * quick render. * - While a mouse movement, if the mouse is down * The call of GLWidget::mouseMoveEvent(), and only this method sets * the (quickRender) attribut at true. * * @param wmavoAction All actions ask by the wrapper */ void WrapperChemicalCmdToAvoAction::updateForAvoActions2( int wmavoAction ) { if( //(WMAVO_IS2(wmavoAction, WMAVO_MENU_ACTIVE) ? 0 // To update wmInfo in wmTool class // : 1 ) // To avoid a bug with periodic table. //|| WMAVO_IS2(wmavoAction,WMAVO_SELECT) || WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI) || WMAVO_IS2(wmavoAction,WMAVO_CREATE) || WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE) || WMAVO_IS2(wmavoAction,WMAVO_CAM_ZOOM) || WMAVO_IS2(wmavoAction,WMAVO_CAM_TRANSLATE) || WMAVO_IS2(wmavoAction,WMAVO_CAM_INITIAT) || m_needAnUpdateMore ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions2" ; if( m_needAnUpdateMore ) m_needAnUpdateMore = false ; if( !m_widget->quickRender() ) { // 1. No quick render. m_widget->update() ; } else { // 2. No compile : mouseMove is protected. // Call directly GLWidget->mouseMove signal. //emit m_widget->mouseMove(&me) ; // 3. Call directly Tool->mouseMouseEvent. No quick render. //m_widget->tool()->mouseMoveEvent( m_widget, &me) ; //m_widget->tool()->mouseMoveEvent( m_widget->current(), &me) ; // 4. Try Fake mouse event. WORKS !!! if( !m_testEventPress ) { m_testEventPress = true ; QApplication::sendEvent( m_widget->m_current, m_me1 ) ; } QApplication::sendEvent( m_widget->m_current, m_me2 ) ; // Test, but be carefull, you must allocate the event each time // it put in a queue, and delete the object after use. //QApplication::postEvent( app, me1 ) ; //QApplication::postEvent( app, me3 ) ; // Install something else. // 5. Try Fake mouse event. //qTestEventList events; //events.addMouseMove(p,1); //events.simulate(m_widget); } } else { // 4. Finish fake mouse event. if( m_widget->quickRender() && m_testEventPress ) { m_testEventPress = false ; QApplication::sendEvent( m_widget->m_current, m_me3 ) ; } } } /** * Update Avogadro according to the Avogadro actions realized. * Here, the update is for the Avogadro move actions. * @param wmavoAction All actions ask by the wrapper */ void WrapperChemicalCmdToAvoAction::updateForAvoActions3( int wmavoAction ) { if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_MOVE) ) { // Object is in "travel mode", but just in the mode. // It is necessary to know what is the movement. if( (WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE)) && m_widget->selectedPrimitives().size()>0 ) { //mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions3" ; // 1. No Quick Render. //m_widget->molecule()->update() ; // Update & Redraw (without quick Render) // 2. Quick Render seems activated, but it lags ... m_widget->molecule()->updateMolecule() ; // Update & Redraw. } } } /** * Calculate the transformation vector and/or matrix according to the need. * "Convert" the wiimote coordinate system to the Avogadro coordinate system. * @return TRUE if the transformation matrix is different to null ; FALSE else. * @param wmactions All actions ask by the wrapper * @param curPos The current position calculate by the Wiimote * @param lastPos The last position calculate by the Wiimote * @param refPoint_in The position of the reference point. * @param rotAtomdegX_in The desired X-axis angle * @param rotAtomdegY_in The desired Y-axis angle */ bool WrapperChemicalCmdToAvoAction::calculateTransformationMatrix ( int wmactions_in, const Eigen::Vector3d& curPos_in, const Eigen::Vector3d& lastPos_in, const Eigen::Vector3d& refPoint_in, double rotAtomdegX_in, double rotAtomdegY_in, Eigen::Vector3d &vectAtomTranslate_out, Eigen::Transform3d &transfAtomRotate_out ) { bool isMoved=false ; if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmactions_in,WMAVO_ATOM_ROTATE) ) { QPoint currentPoint((int)curPos_in[0], (int)curPos_in[1]) ; QPoint lastPoint((int)lastPos_in[0], (int)lastPos_in[1]) ; Eigen::Vector3d fromPos=m_widget->camera()->unProject( lastPoint, refPoint_in ) ; Eigen::Vector3d toPos=m_widget->camera()->unProject( currentPoint, refPoint_in ) ; Eigen::Vector3d camBackTransformedXAxis=m_widget->camera()->backTransformedXAxis() ; Eigen::Vector3d camBackTransformedYAxis=m_widget->camera()->backTransformedYAxis() ; Eigen::Vector3d camBackTransformedZAxis=m_widget->camera()->backTransformedZAxis() ; if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE) && !(curPos_in[0]==lastPos_in[0] && curPos_in[1]==lastPos_in[1]) ) { vectAtomTranslate_out = (toPos - fromPos) / WMAVO_ATOM_SMOOTHED_MOVE_XY ; //cout << "currentWmPos.x():" << currentWmPos.x() << " currentWmPos.y():" << currentWmPos.y() << endl ; //cout << " lastWmPos.x():" << lastWmPos.x() << " lastWmPos.y():" << lastWmPos.y() << endl ; //cout << " fromPos[0]:" << fromPos[0] << " fromPos[1]:" << fromPos[1] << " fromPos[2]:" << fromPos[2] << endl ; //cout << " toPos[0]:" << toPos[0] << " toPos[1]:" << toPos[1] << " fromPos[2]:" << fromPos[2] << endl ; //cout << " newVectAtomTranslate:" << m_vectAtomTranslate[0] << " " << m_vectAtomTranslate[1] << " " << m_vectAtomTranslate[2] << endl ; if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE) ) { // Z-movement. if( (curPos_in[2]-lastPos_in[2]) <= -WMAVO_WM_Z_MINPOINTING_MOVEALLOWED ) vectAtomTranslate_out += (camBackTransformedZAxis*WMAVO_ATOM_MAX_MOVE_Z) ; if( (curPos_in[2]-lastPos_in[2]) >= WMAVO_WM_Z_MINPOINTING_MOVEALLOWED ) vectAtomTranslate_out -= (camBackTransformedZAxis*WMAVO_ATOM_MAX_MOVE_Z) ; } isMoved = true ; //cout << " m_vectAtomTranslate:" << m_vectAtomTranslate[0] << " " << m_vectAtomTranslate[1] << " " << m_vectAtomTranslate[2] << endl ; } else if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_ROTATE) ) { Eigen::Vector3d rotAxe=m_moleculeManip->getRotationAxe() ; if( m_tmpBarycenter == m_vect3d0 ) { // Calculate the barycenter of selected atoms. Eigen::Vector3d tmp=m_vect3d0 ; int i=0 ; Atom *a=NULL ; foreach( Primitive *p, m_widget->selectedPrimitives() ) { if( p->type() == Primitive::AtomType ) { a = static_cast<Atom*>(p) ; tmp += *(a->pos()) ; i++ ; } } m_tmpBarycenter = tmp / i ; } if( rotAxe != m_vect3d0 ) { Eigen::Vector3d rotAxePoint=m_moleculeManip->getRotationAxePoint() ; // Rotate the selected atoms about the center // rotate only selected primitives transfAtomRotate_out.matrix().setIdentity(); // Return to the center of the 3D-space. transfAtomRotate_out.translation() = rotAxePoint ; // Apply rotations. transfAtomRotate_out.rotate( Eigen::AngleAxisd( (rotAtomdegX_in/90.0)* 0.1, rotAxe) ) ; // /90.0 => Eliminate the initial 90° rotation by the Wiimote, // then to apply a step (in unknown metric). transfAtomRotate_out.rotate( Eigen::AngleAxisd( (rotAtomdegY_in/90.0)*-0.1, rotAxe ) ) ; // Return to the object. transfAtomRotate_out.translate( -rotAxePoint ) ; } else { // Rotation around the barycenter. // Rotate the selected atoms about the center // rotate only selected primitives transfAtomRotate_out.matrix().setIdentity(); // Return to the center of the 3D-space. transfAtomRotate_out.translation() = m_tmpBarycenter ; // Apply rotations. transfAtomRotate_out.rotate( Eigen::AngleAxisd( (rotAtomdegX_in/90.0)* 0.1, camBackTransformedYAxis) ) ; // /90.0 => Eliminate the initial 90° rotation by the Wiimote, // then to apply a step (in unknown metric). transfAtomRotate_out.rotate( Eigen::AngleAxisd( (rotAtomdegY_in/90.0)*-0.1, camBackTransformedXAxis) ) ; // Return to the object. transfAtomRotate_out.translate( -m_tmpBarycenter ) ; } isMoved = true ; } else { // Put all transformation "at zero". transfAtomRotate_out.matrix().setIdentity(); transfAtomRotate_out.translation() = m_vect3d0 ; vectAtomTranslate_out[0] = 0.0 ; vectAtomTranslate_out[1] = 0.0 ; vectAtomTranslate_out[2] = 0.0 ; isMoved = false ; } } return isMoved ; } /** * Receive the "calcul distance" feature from the WmTool class.. */ void WrapperChemicalCmdToAvoAction::receiveRequestToCalculDistance() { m_isCalculDistDiedre = true ; } }
[ [ [ 1, 141 ], [ 144, 253 ], [ 256, 256 ], [ 259, 262 ], [ 264, 267 ], [ 276, 278 ], [ 280, 282 ], [ 284, 288 ], [ 291, 295 ], [ 301, 302 ], [ 304, 322 ], [ 325, 325 ], [ 328, 338 ], [ 342, 1483 ], [ 1486, 1504 ], [ 1508, 1509 ], [ 1513, 1513 ], [ 1515, 1515 ], [ 1527, 1527 ], [ 1552, 1579 ] ], [ [ 142, 143 ], [ 254, 255 ], [ 257, 258 ], [ 263, 263 ], [ 268, 275 ], [ 279, 279 ], [ 283, 283 ], [ 289, 290 ], [ 296, 300 ], [ 303, 303 ], [ 323, 324 ], [ 326, 327 ], [ 339, 341 ], [ 1484, 1485 ], [ 1505, 1507 ], [ 1510, 1512 ], [ 1514, 1514 ], [ 1516, 1526 ], [ 1528, 1551 ] ] ]
753db4856b74c654b7321239e0dd714a5054a557
25f79693b806edb9041e3786fa3cf331d6fd4b97
/include/core/cal/Event.h
44c77be047d49cea80b9c266d1f7c128164f7531
[]
no_license
ouj/amd-spl
ff3c9faf89d20b5d6267b7f862c277d16aae9eee
54b38e80088855f5e118f0992558ab88a7dea5b9
refs/heads/master
2016-09-06T03:13:23.993426
2009-08-29T08:55:02
2009-08-29T08:55:02
32,124,284
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
h
#ifndef AMDSPL_EVENT_H #define AMDSPL_EVENT_H ////////////////////////////////////////////////////////////////////////// //! //! \file Event.h //! \date 1:3:2009 13:39 //! \author Jiawei Ou //! //! \brief Contains declaration of Event class. //! ////////////////////////////////////////////////////////////////////////// #include "cal.h" #include "SplDefs.h" namespace amdspl { namespace core { namespace cal { ////////////////////////////////////////////////////////////////////////// //! //! \brief Event class is an abstract representation of CAL event. //! It contains method for event checking and event waiting. //! \warning Not thread safe. //! ////////////////////////////////////////////////////////////////////////// class SPL_EXPORT Event { friend class Program; friend class ProgramManager; public: Event(); void set(CALevent e, CALcontext ctx); void reset(); bool isUnused(); CALevent getHandle(); CALcontext getContext(); void waitEvent(); CALresult checkEvent(); private: //! \brief Stores the CAL event handle. CALevent _event; //! \brief Stores the CAL device context the event handle associated to. CALcontext _ctx; }; } } } #endif //AMDSPL_EVENT_H
[ "jiawei.ou@1960d7c4-c739-11dd-8829-37334faa441c" ]
[ [ [ 1, 51 ] ] ]
cbfe6342e5bc6e57218ee57c316c5cd97fff280a
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Game/Object/GameScene/Score.h
29049c1e19cbbaf1dc23c41224737e7dbe0f7366
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,348
h
/*******************************************************************************/ /** * @file Score.h. * * @brief スコアクラスヘッダ定義. * * @date 2008/12/15. * * @version 1.00. * * @author Ryosuke Ogawa. */ /*******************************************************************************/ #ifndef _SCORE_H_ #define _SCORE_H_ #include "IGameDevice.h" #include "Manager/Object/ObjectManager.h" #include "Object/ObjectBase.h" #include "Scene/GameSceneState.h" #include "Manager/Scene/Option/Option.h" class Score : public ObjectBase { public: /*=========================================================================*/ /** * @brief コンストラクタ. * */ Score(IGameDevice& device, ObjectManager& objectManager, Option& option, GameSceneState& gameSceneState, Player& player); /*=========================================================================*/ /** * @brief デストラクタ. * */ ~Score(); /*=========================================================================*/ /** * @brief 初期化処理. * */ void Initialize(); /*=========================================================================*/ /** * @brief 終了処理. * */ void Terminate(); /*=========================================================================*/ /** * @brief 終了しているかどうか. * * @return 終了フラグ. */ bool IsTerminated(); /*=========================================================================*/ /** * @brief オブジェクトの描画処理. * */ void RenderObject(); /*=========================================================================*/ /** * @brief オブジェクトの更新処理. * * @param[in] frameTimer 更新タイマ. */ void UpdateObject(float frameTimer); private: /** 終了フラグ */ bool m_isTerminated; /** ゲームデバイス */ IGameDevice& m_device; /** オブジェクトマネージャメディエータ */ ObjectManager& m_objectManager; /** ゲームオプション */ Option& m_option; /** ゲームシーンステート */ GameSceneState& m_gameSceneState; /** プレーヤ */ Player& m_player; /** y座標 */ float m_y; /** x座標 */ float m_x; }; #endif
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 99 ] ] ]
ca59b404d11d50655df88f32d9bdafe16f510eca
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/rnsgameplay/ncgpgrenadeclass_main.cc
05bffc45457ffeed4e6bc090174086c17ebacccb
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
817
cc
//------------------------------------------------------------------------------ // ncgpgrenadeclass_main.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchrnsgameplay.h" #include "rnsgameplay/ncgpgrenadeclass.h" nNebulaComponentClass(ncGPGrenadeClass,ncGameplayClass); //------------------------------------------------------------------------------ /** */ ncGPGrenadeClass::ncGPGrenadeClass(): launchPower( 1000 ), maxLifeTime( 5.0f ) { // empty } //------------------------------------------------------------------------------ /** */ ncGPGrenadeClass::~ncGPGrenadeClass() { // empty } //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 29 ] ] ]
d2cfa947fd9fed9c7fdc3dba2846f80e32fcce1d
a37df219b4a30e684db85b00dd76d4c36140f3c2
/1.7.1/rox/rox.cpp
40febebd3045eee129d7f5b4e54ef23d056bd8f8
[]
no_license
BlackMoon/bm-net
0f79278f8709cd5d0738a6c3a27369726b0bb793
eb6414bc412a8cfc5c24622977e7fa7203618269
refs/heads/master
2020-12-25T20:20:44.843483
2011-11-29T10:33:17
2011-11-29T10:33:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,009
cpp
// rox.cpp #pragma comment(lib, "../ext/release/ext") #include "../dx/obj.h" #include "../ext/ext.h" #define WIN32_LEAN_AND_MEAN #define STOCK_CONST 4 struct mperiod { char mon[4]; float pmin, pmax, smin, smax; ULONG destp, dests; USHORT date, month, year; inline void fillDate() { if (strcmp(mon, "Jan") == 0) month = 1; else if (strcmp(mon, "Feb") == 0) month = 2; else if (strcmp(mon, "Mar") == 0) month = 3; else if (strcmp(mon, "Apr") == 0) month = 4; else if (strcmp(mon, "May") == 0) month = 5; else if (strcmp(mon, "Jun") == 0) month = 6; else if (strcmp(mon, "Jul") == 0) month = 7; else if (strcmp(mon, "Aug") == 0) month = 8; else if (strcmp(mon, "Sep") == 0) month = 9; else if (strcmp(mon, "Oct") == 0) month = 10; else if (strcmp(mon, "Nov") == 0) month = 11; else if (strcmp(mon, "Dec") == 0) month = 12; } }; struct param { char filename[MAX_PATH], shortname[16]; float min, max; inline param() { min = 0.0f; max = 1.0f; } inline void makeShort() { memset(shortname, 0, 16); getName(shortname, filename); } }; struct wline { UINT x, y; float z0, z1; }; struct dens { float oil, watr, gas, kper; }; typedef vector<float> floatvector; typedef vector<floatvector> floatmatrix; bool dporo = 0; char din[MAX_PATH], dout[MAX_PATH], symb; float zmin, zmax; SPACE space; bool paramConvert(param* ppm) { printf("[%s]\n", ppm->shortname); char header[16], file[MAX_PATH]; memset(file, 0, MAX_PATH); strcpy(file, din); strcat(file, ppm->shortname); FILE *istream = fopen(file, "r"), *ostream; if (!istream) return 0; float fvalue0; floatvector fvector; floatmatrix fmatrix; int i, j, k; fscanf(istream, "%s\n", header); if (strcmp(header, "COOR") == 0) { // read xmin UINT x, y; // first line fscanf(istream, "%u %u %f", &space.xMin, &space.yMax, &fvalue0); zmin = zmax = -fvalue0; fscanf(istream, "%u %u %f", &x, &y, &fvalue0); if (-fvalue0 < zmin) zmin = -fvalue0; if (-fvalue0 > zmax) zmax = -fvalue0; for (i = 1; i < space.square() - 1; i++) { fscanf(istream, "%u %u %f", &x, &y, &fvalue0); if (-fvalue0 < zmin) zmin = -fvalue0; if (-fvalue0 > zmax) zmax = -fvalue0; fscanf(istream, "%u %u %f", &x, &y, &fvalue0); if (-fvalue0 < zmin) zmin = -fvalue0; if (-fvalue0 > zmax) zmax = -fvalue0; } // last line fscanf(istream, "%u %u %f", &space.xMax, &space.yMin, &fvalue0); space.xStep = space.xLen() / space.nX + 1; space.yStep = space.yLen() / space.nY + 1; if (-fvalue0 < zmin) zmin = -fvalue0; if (-fvalue0 > zmax) zmax = -fvalue0; fscanf(istream, "%u %u %f", &x, &y, &fvalue0); if (-fvalue0 < zmin) zmin = -fvalue0; if (-fvalue0 > zmax) zmax = -fvalue0; printf("\tSTEP %u %u\n", space.xStep, space.yStep); printf("\tX %u %u\n", space.xMin, space.xMax); printf("\tY %u %u\n", space.yMin, space.yMax); printf("\tZ %.2f %.2f\n", zmin, zmax); strcpy(file, dout); strcat(file, "grid.txt"); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "SIZE %u %u %u\n", space.nX, space.nY, space.nZ); fprintf(ostream, "STEP %u %u\n", space.xStep, space.yStep); fprintf(ostream, "X %u %u\n", space.xMin, space.xMax); fprintf(ostream, "Y %u %u\n", space.yMin, space.yMax); fprintf(ostream, "Z %.2f %.2f\n", zmin, zmax); fclose(ostream); } else if (strcmp(header, "ZCORN") == 0) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "%.3f %.3f\n", zmin, zmax); float fvalue1; for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); // roof for (j = 0; j < ((space.nY - 1) << 1); j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f %f", &fvalue0, &fvalue1); fvector.push_back(-fvalue0); } fvector.push_back(-fvalue1); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j > 0; j -= 2) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); // sole for (j = 0; j < ((space.nY - 1) << 1); j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f %f", &fvalue0, &fvalue1); fvector.push_back(-fvalue0); } fvector.push_back(-fvalue1); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j > 0; j -= 2) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fclose(ostream); } else if (strcmp(header, "K_X") == 0) { if (symb != 'a') { printf("convert X_Permeability (y/n/a)?"); cin >> symb; } if ((symb == 0x61) || (symb == 0x79)) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max); fscanf(istream, "VARI\n"); for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); for (j = 0; j < space.nY - 1; j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f", &fvalue0); fvector.push_back(fvalue0); } fvector.push_back(fvalue0); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j >= 0; j--) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fclose(ostream); } } else if (strcmp(header, "K_Z") == 0) { if (symb != 'a') { printf("convert Z_Permeability (y/n/a)?"); cin >> symb; } if ((symb == 0x61) || (symb == 0x79)) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max); fscanf(istream, "VARI\n"); for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); for (j = 0; j < space.nY - 1; j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f", &fvalue0); fvector.push_back(fvalue0); } fvector.push_back(fvalue0); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j >= 0; j--) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fclose(ostream); } } else if (strcmp(header, "PORO") == 0) { if (symb != 'a') { printf("convert Porosity (y/n/a)?"); cin >> symb; } if ((symb == 0x61) || (symb == 0x79)) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max); fscanf(istream,"VARI\n"); for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); for (j = 0; j < space.nY - 1; j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f", &fvalue0); fvector.push_back(fvalue0); } fvector.push_back(fvalue0); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j >= 0; j--) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fclose(ostream); } } else if (strcmp(header, "NTOG") == 0) { if (symb != 'a') { printf("convert NTG (y/n/a)?"); cin >> symb; } if ((symb == 0x61) || (symb == 0x79)) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max); fscanf(istream, "VARI\n"); for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); for (j = 0; j < space.nY - 1; j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f", &fvalue0); fvector.push_back(fvalue0); } fvector.push_back(fvalue0); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j >= 0; j--) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) fvalue0 = ppm->min; if (fvalue0 > ppm->max) fvalue0 = ppm->max; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fclose(ostream); } } else if (strcmp(header, "SWAT") == 0) { if (symb != 'a') { printf("convert SWAT (y/n/a)?"); cin >> symb; } if ((symb == 0x61) || (symb == 0x79)) { strcpy(file, dout); strcat(file, ppm->shortname); ostream = fopen(file, "w"); if (!ostream) return 0; fprintf(ostream, " \n"); // place for min & max fscanf(istream, "VARI\n"); for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); for (j = 0; j < space.nY - 1; j++) { for (k = 0; k < space.nX - 1; k++) { fscanf(istream, "%f", &fvalue0); fvector.push_back(1 - fvalue0); } fvector.push_back(1 - fvalue0); // last value fmatrix.push_back(fvector); fvector.clear(); } for (--j; j >= 0; j--) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) ppm->min = fvalue0; if (fvalue0 > ppm->max) ppm->max = fvalue0; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); } // last row fvector = fmatrix[0]; for (k = 0; k < space.nX; k++) { fvalue0 = fvector[k]; if (fvalue0 < ppm->min) ppm->min = fvalue0; if (fvalue0 > ppm->max) ppm->max = fvalue0; fprintf(ostream, "%.3f ", fvalue0); } fprintf(ostream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fseek(ostream, 0, SEEK_SET); fprintf(ostream, "%.3f %.3f", ppm->min, ppm->max); fclose(ostream); } } fclose(istream); printf("\n"); return 1; } bool outConvert(const char* filename, const HANDLE hfile) { bool bres = 1; HANDLE hmap = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, "fileMapping"); LONG rest, size = GetFileSize(hfile, 0); void* pbase = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 0); char buf[USHRT_MAX]; char* pdest; float fvalue, pmin, pmax, smin, smax; mperiod mp; vector<mperiod> mperiods0; int i = 0; for (i; i < size / USHRT_MAX; i++) { memset(buf, 0, USHRT_MAX); memcpy(buf, (LPTSTR)pbase + i * USHRT_MAX, USHRT_MAX); if (pdest = strstr(buf, "Map of PRES")) { memset(&mp, 0, 36); mp.destp = (long)(pdest - buf) + i * USHRT_MAX; if (sscanf(pdest, "Map of PRES at %u %s %u\n", &mp.date, mp.mon, &mp.year) == 0) sscanf(pdest, "Map of PRESSURE at %u %s %u\n", &mp.date, mp.mon, &mp.year); mp.fillDate(); pdest -= 375; sscanf(pdest, "Pressure %f %f %f barsa\n", &mp.pmin, &mp.pmax, &fvalue); pdest += 51; sscanf(pdest, "Soil %f %f %f frac\n", &mp.smin, &mp.smax, &fvalue); } if (pdest = strstr(buf, "Map of soil")) { mp.dests = (long)(pdest - buf) + i * USHRT_MAX; mperiods0.push_back(mp); } } rest = size - i * USHRT_MAX; memset(buf, 0, USHRT_MAX); memcpy(buf, (LPTSTR)pbase + i * USHRT_MAX, rest); if (!(pdest = strstr(buf, "Run finished successfully"))) mperiods0.erase(&mperiods0.back()); UnmapViewOfFile(pbase); CloseHandle(hmap); CloseHandle(hfile); size = (long)mperiods0.size(); if (size != 0) { mp = mperiods0[0]; pmin = mp.pmin; pmax = mp.pmax; smin = mp.smin; smax = mp.smax; printf("\t[1]\t %u %s %u\n", mp.date, mp.mon, mp.year); for (i = 1; i < size; i++) { mp = mperiods0[i]; if (pmin > mp.pmin) pmin = mp.pmin; if (pmax < mp.pmax) pmax = mp.pmax; if (smin > mp.smin) smin = mp.smin; if (smax < mp.smax) smax = mp.smax; printf("\t[%u]\t %u %s %u\n", i + 1, mp.date, mp.mon, mp.year); } int index = 0; vector<int> indices; printf("\nchoose dates (0 - end):\n"); do { printf("\t"); scanf("%d", &index); if ((index < 0) || (index > (int)mperiods0.size())) { printf("error\n"); continue; } indices.push_back(index); } while (index != 0); indices.erase(&indices.back()); // sort sort(indices.begin(), indices.end()); vector<mperiod> mperiods1; if (indices.size() == 0) mperiods1.swap(mperiods0); else { index = indices[0]; mp = mperiods0[--index]; mperiods1.push_back(mp); pmin = mp.pmin; pmax = mp.pmax; smin = mp.smin; smax = mp.smax; for (i = 1; i < (int)indices.size(); i++) { index = indices[i]; mp = mperiods0[--index]; mperiods1.push_back(mp); if (pmin > mp.pmin) pmin = mp.pmin; if (pmax < mp.pmax) pmax = mp.pmax; if (smin > mp.smin) smin = mp.smin; if (smax < mp.smax) smax = mp.smax; } } indices.clear(); mperiods0.clear(); char* pfile = new char[MAX_PATH]; FILE *istream = fopen(filename, "r"), *pstream, *rstream, *sstream; // actn; // input stream if (!istream) return 0; memset(pfile, 0, MAX_PATH); strcpy(pfile, dout); strcat(pfile, "p.txt"); // pres stream pstream = fopen(pfile, "w"); if (!pstream) return 0; fprintf(pstream, "%.3f %.3f\n", pmin, pmax); memset(pfile, 0, MAX_PATH); strcpy(pfile, dout); strcat(pfile, "actn.bin"); // actn stream size = (space.nX - 1) * (space.nY - 1) * space.nZ; bool* pbarr = new bool[size]; // active cells memset(pbarr, 0, size); rstream = fopen(pfile, "wb"); if (!rstream) return 0; memset(pfile, 0, MAX_PATH); strcpy(pfile, dout); strcat(pfile, "soil.txt"); // soil stream sstream = fopen(pfile, "w"); if (!sstream) return 0; fprintf(sstream, "%.3f %.3f\n", smin, smax); floatvector fvector; floatmatrix fmatrix; int ix, jy, kz, n, mpsize, value; mp = mperiods1[0]; // first reading inactive cells i = n = 0; mpsize = (int)mperiods1.size(); if (dporo) // double poro { FILE *sstreamD; memset(pfile, 0, MAX_PATH); strcpy(pfile, dout); strcat(pfile, "soild.txt"); // dporo soil stream sstreamD = fopen(pfile, "w"); delete pfile; if (!sstreamD) return 0; fprintf(sstreamD, "%.3f %.3f\n", smin, smax); // Map of PRESSURE printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax); fseek(istream, mp.destp + 138, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data if (fscanf(istream, "All values are %f", &fvalue) > 0) { for (jy = 0; jy < space.nY - 1; jy++) { for (ix = 0; ix < space.nX - 1; ix++) { fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } else { for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX - 1; ix++) { fvalue = fvector[ix]; // inactive cells if (fvalue >= mp.pmin - 1e-2) { pbarr[i] = 1; n++; } i++; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "%.3f\t", fvalue); fprintf(pstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fwrite(pbarr, 1, size, rstream); SAFE_DELETE_ARRAY(pbarr); fclose(rstream); // Map of soil printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax); fseek(istream, mp.dests + 134, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data if (fscanf(istream, "All values are %f", &fvalue) > 0) { for (jy = 0; jy < space.nY - 1; jy++) { for (ix = 0; ix < space.nX - 1; ix++) { fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } else { for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); fmatrix.clear(); fvector.clear(); } // dporo soil layers fprintf(sstreamD, "%.3f %.3f\n", mp.smin, mp.smax); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data if (fscanf(istream, "All values are %f", &fvalue) > 0) { for (jy = 0; jy < space.nY - 1; jy++) { for (ix = 0; ix < space.nX - 1; ix++) { fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } else { for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstreamD, "%.3f\t", fvalue); } fprintf(sstreamD, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstreamD, "%.3f\t", fvalue); } fprintf(sstreamD, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } // second period for (i = 1; i < mpsize; i++) { mp = mperiods1[i]; // Map of PRESSURE printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax); fseek(istream, mp.destp + 138, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } // Map of soil printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax); fseek(istream, mp.dests + 134, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); fmatrix.clear(); fvector.clear(); } // dporo soil layers fprintf(sstreamD, "%.3f %.3f\n", mp.smin, mp.smax); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstreamD, "%.3f\t", fvalue); } fprintf(sstreamD, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstreamD, "%.3f\t", fvalue); } fprintf(sstreamD, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } } fclose(sstreamD); } else { // Map of PRESSURE printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax); fseek(istream, mp.destp + 138, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data if (fscanf(istream, "All values are %f", &fvalue) > 0) { for (jy = 0; jy < space.nY - 1; jy++) { for (ix = 0; ix < space.nX - 1; ix++) { fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } else { for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX - 1; ix++) { fvalue = fvector[ix]; // inactive cells if (fvalue >= mp.pmin - 1e-2) { pbarr[i] = 1; n++; } i++; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "%.3f\t", fvalue); fprintf(pstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } fwrite(pbarr, 1, size, rstream); delete [] pbarr; fclose(rstream); // Map of soil printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax); fseek(istream, mp.dests + 134, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // if (fscanf(istream, "All values are %f", &fvalue) > 0) { for (jy = 0; jy < space.nY - 1; jy++) { for (ix = 0; ix < space.nX - 1; ix++) { fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } else { for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } // second period for (i = 1; i < mpsize; i++) { mp = mperiods1[i]; // Map of PRESSURE printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax); fseek(istream, mp.destp + 138, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); // read data for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } // last value fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(pstream, "%.3f\t", fvalue); } fprintf(pstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } // Map of soil printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year); fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax); fseek(istream, mp.dests + 134, SEEK_SET); for (kz = 0; kz < space.nZ; kz++) { printf("\tlayer%u", kz + 1); fscanf(istream, "\nLayer iz=%u\nix= :", &value); for (ix = 0; ix < space.nX - 1; ix++) fscanf(istream, "%u", &value); for (jy = 0; jy < space.nY - 1; jy++) { fscanf(istream, "\nRow iy=%u:", &value); for (ix = 0; ix < space.nX - 1; ix++) { fscanf(istream, "%f", &fvalue); fvector.push_back(fvalue); } fvector.push_back(fvalue); fmatrix.push_back(fvector); fvector.clear(); } // save data for (--jy; jy >= 0; jy--) { fvector = fmatrix[jy]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); } // last row fvector = fmatrix[0]; for (ix = 0; ix < space.nX; ix++) { fvalue = fvector[ix]; fprintf(sstream, "%.3f\t", fvalue); } fprintf(sstream, "\n"); fmatrix.clear(); fvector.clear(); printf("\t\tok\n"); } } } fclose(istream); fclose(pstream); fclose(sstream); printf("\nnumber of active cells\t%u", n); printf("\nnumber of periods\t%u\n\n", mpsize); } return bres; } bool wellConvert(const char* filename) { printf("[%s]\n", "trackwell.txt"); char name[9], file[MAX_PATH]; memset(file, 0, MAX_PATH); size_t len = strlen(filename); strcpy(file, din); strncat(file, filename, --len); FILE *istream = fopen(file, "r"), *ostream; if (!istream) return 0; strcpy(file, dout); strcat(file, "\\well.txt"); ostream = fopen(file, "w"); if (!ostream) return 0; bool bvalid; size_t i; wline _wline; vector <wline> wlines; while (fscanf(istream, "%s\n", name) == 1) { bvalid = 0; while (fscanf(istream, "%u %u %f %f\n", &_wline.x, &_wline.y, &_wline.z0, &_wline.z1) == 4) { if (BOUNDS(space).ptBelong(_wline.x, _wline.y)) { bvalid = 1; wlines.push_back(_wline); } } fscanf(istream, "/\n"); if (bvalid) { printf("\twell %s\n", name); fprintf(ostream, " %s\n", name); for (i = 0; i < wlines.size(); i++) { fprintf(ostream, "%u %u %.2f\n", wlines[i].x, wlines[i].y, -wlines[i].z0); } wlines.clear(); fprintf(ostream, "/\n"); } } fclose(ostream); fclose(istream); printf("\n"); return 1; } bool stockConvert(vector<param> *pvec, dens* pdens) { printf("[%s]\n", "stock"); bool bres = 1, bm = 0, bn = 0, bs = 0, bz = 0; // can close streams FILE *streamM, *streamN, *streamS, *streamZ; try { char file[MAX_PATH]; int i; param pm; for (i = 0; i < STOCK_CONST; i++) { pm = pvec->at(i); memset(file, 0, MAX_PATH); strcpy(file, dout); strcat(file, pm.shortname); if (strcmp(pm.shortname, "M.txt") == 0) { streamM = fopen(file, "r"); if (!streamM) throw 0; bm = 1; } if (strcmp(pm.shortname, "NTOG.txt") == 0) { streamN = fopen(file, "r"); if (!streamN) throw 0; bn = 1; } if (strcmp(pm.shortname, "SWAT.txt") == 0) { streamS = fopen(file, "r"); if (!streamS) throw 0; bs = 1; } if (strcmp(pm.shortname, "ZCORN.txt") == 0) { streamZ = fopen(file, "r"); if (!streamZ) throw 0; bz = 1; } } memset(file, 0, MAX_PATH); strcpy(file, dout); strcat(file, "stock.txt"); FILE *ostream = fopen(file, "w"); if (!ostream) throw 0; fprintf(ostream, " \n"); // place for min & max float fvalue, fmin = 10.0f, fmax = 0.0f, fvalueM, fvalueN, fvalueS, fvalueZ; floatvector fvector, fvectorh; floatmatrix fmatrix, fmatrixh; fscanf(streamM, "%f %f", &fvalueS, &fvalueS); fscanf(streamN, "%f %f", &fvalueN, &fvalueN); fscanf(streamS, "%f %f", &fvalueS, &fvalueS); fscanf(streamZ, "%f %f", &fvalueZ, &fvalueZ); int j, k; for (i = 0; i < space.nZ; i++) { printf("\tlayer%u", i + 1); // m, ntog, s, roof for (j = 0; j < space.nY; j++) { for (k = 0; k < space.nX; k++) { fscanf(streamM, "%f", &fvalueM); fscanf(streamN, "%f", &fvalueN); fscanf(streamS, "%f", &fvalueS); fscanf(streamZ, "%f", &fvalueZ); fvalue = fvalueM * fvalueN * fvalueS; fvector.push_back(fvalue); fvectorh.push_back(fvalueZ); } fmatrix.push_back(fvector); fmatrixh.push_back(fvectorh); fvector.clear(); fvectorh.clear(); } // sole for (j = 0; j < space.nY; j++) { fvectorh = fmatrixh[j]; for (k = 0; k < space.nX; k++) { fscanf(streamZ, "%f", &fvalueZ); float f0 = fmatrix[j][k], f1 = fvectorh[k]; fvalue = fmatrix[j][k] * (fvectorh[k] - fvalueZ); fmatrix[j][k] = fvalue; } fvectorh.clear(); } fmatrixh.clear(); // save for (j = 0; j < space.nY; j++) { fvector = fmatrix[j]; for (k = 0; k < space.nX; k++) { fvalue = fvector[k] * pdens->kper * pdens->oil / 1000.0f; if (fvalue < fmin) fmin = fvalue; if (fvalue > fmax) fmax = fvalue; fprintf(ostream, "%.3f ", fvalue); } fprintf(ostream, "\n"); fvector.clear(); } fmatrix.clear(); printf("\t\tok\n"); } fseek(ostream, 0, SEEK_SET); fprintf(ostream, "%.3f %.3f", fmin, fmax); fclose(ostream); } catch (int) { bres = 0; } // close streams if (bm) fclose(streamM); if (bn) fclose(streamN); if (bs) fclose(streamS); if (bz) fclose(streamZ); printf("\n"); return bres; } bool roxConvert(const char* filename) { char file[MAX_PATH]; WIN32_FIND_DATA find; memset(file, 0, MAX_PATH); strcpy(file, din); strcat(file, "\\*.out"); HANDLE hfile0 = FindFirstFile(file, &find); if (hfile0 == INVALID_HANDLE_VALUE) { printf("error: %s files not found\n", file); return 0; } FindClose(hfile0); memset(file, 0, MAX_PATH); strcpy(file, din); strcat(file, find.cFileName); hfile0 = CreateFile(file, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); char buf[USHRT_MAX]; memset(buf, 0, USHRT_MAX); ULONG nbytes; ReadFile(hfile0, buf, USHRT_MAX, &nbytes, 0); // HANDLE hfile1 = CreateFile(filename, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (hfile1 == INVALID_HANDLE_VALUE) { printf("error: %s opening failed\n", filename); return 0; } LONG size = GetFileSize(hfile1, 0); char* pbuf = new char[size]; memset(pbuf, 0, size); ReadFile(hfile1, pbuf, size, &nbytes, 0); CloseHandle(hfile1); // dim memset(&space, 0, sizeof(space)); char* pdest0 = 0; if (pdest0 = strstr(pbuf, "DPORO")) dporo = 1; if (pdest0 = strstr(pbuf, "SIZE")) { sscanf(pdest0, "SIZE %u %u %u", &space.nX, &space.nY, &space.nZ); space.nX++; space.nY++; if (dporo) space.nZ /= 2; printf("SIZE %u %u %u\n\n", space.nX, space.nY, space.nZ); } if (!outConvert(file, hfile0)) return 0; // density & kper dens _dens; if (pdest0 = strstr(pbuf, "FLUID BLACKOIL")) { // water if (pdest0 = strstr(pdest0, "WATR")) { float watr; sscanf(pdest0, "WATR\n %f %f", &watr, &_dens.watr); } // oil if (pdest0 = strstr(pdest0, "BASIC")) sscanf(pdest0, "BASIC\n %f", &_dens.oil); // gas, kper if (pdest0 = strstr(pdest0, "OPVT")) { float p, visc; sscanf(pdest0, "OPVT\n %f %f %f %f", &p, &_dens.kper, &visc, &_dens.gas); } } // params if (pdest0 = strstr(pbuf, "include")) { char *pdest1 = 0; char line[MAX_PATH]; size_t len; param pm; vector<param> params; do { memset(line, 0, MAX_PATH); memset(pm.filename, 0, MAX_PATH); sscanf(pdest0, "include '%s", line); len = strlen(line); strncpy(pm.filename, line, --len); pm.makeShort(); if (strlen(pm.shortname) > 0) { if (strcmp(pm.shortname, "K.txt") == 0) { pdest1 = strstr(buf, "Permx"); sscanf(pdest1, "Permx %f %f", &pm.min, &pm.max); } else if (strcmp(pm.shortname, "KZ.txt") == 0) { pdest1 = strstr(buf, "Permz"); sscanf(pdest1, "Permz %f %f", &pm.min, &pm.max); } else if (strcmp(pm.shortname, "M.txt") == 0) { pdest1 = strstr(buf, "Porosity"); sscanf(pdest1, "Porosity %f %f", &pm.min, &pm.max); params.push_back(pm); } else if (strcmp(pm.shortname, "NTOG.txt") == 0) { pdest1 = strstr(buf, "NTG"); sscanf(pdest1, "NTG %f %f", &pm.min, &pm.max); params.push_back(pm); } else if (strcmp(pm.shortname, "SWAT.txt") == 0) { pm.min = 1.0f; pm.max = 0.0f; params.push_back(pm); } else if (strcmp(pm.shortname, "ZCORN.txt") == 0) { params.push_back(pm); } paramConvert(&pm); } pdest0++; pdest0 = strstr(pdest0, "include"); } while (pdest0); // stock if (params.size() == STOCK_CONST) stockConvert(&params, &_dens); params.clear(); } // wells if (pdest0 = strstr(pbuf, "TFIL")) { sscanf(pdest0, "TFIL\n'%s", file); wellConvert(file); } SAFE_DELETE_ARRAY(pbuf); return 1; } int main(int argc, char* argv[]) { if (argc == 1) { printf("usage: rox [filename]\n"); return 0; } // head printf("\n"); printf("\t\t\t--------------------\n"); printf("\t\t\tRoxar Data Convertor\n"); printf("\t\t\t--------------------\n"); printf("\n"); char dat[MAX_PATH]; memset(dat, 0, MAX_PATH); memset(din, 0, MAX_PATH); getDir(din, argv[1]); if (strlen(din) == 0) { getDir(din, argv[0]); strcpy(dat, din); strcat(dat, argv[1]); } else strcpy(dat, argv[1]); memset(dout, 0, MAX_PATH); strcpy(dout, din); strcat(dout, "out"); CreateDirectory(dout, 0); strcat(dout, "\\"); printf("%s\n\n", dat); if (!roxConvert(dat)) return 1; printf("Press any key to continue\n"); getch(); return 0; }
[ "[email protected]@b6168ec3-97fc-df6f-cbe5-288b4f99fbbd" ]
[ [ [ 1, 1691 ] ] ]
5ba1dd17cec6b4b1d20b61c3148cb67935ca7886
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media3/CAudio.h
69e5f6b520a2faae4973af98b00e14885c4c5320
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
h
#ifndef CAUDIO_H #define CAUDIO_H #include "IMediaStreaming.h" #include "IAudioApi.h" class CAudio : public IMediaStreaming { private: BOOL m_bMutexOwnerSet, m_bRunProcessAudioThread, m_bAudioProcessingPaused; IAudioApi *m_pAudioApi; _SEMAPHORE m_AudioSemaph, m_ProcessAudioSemaph; IThread *m_pProcessAudioThread; public: CAudio(IMediaApi *_pAudioApi, CBufferMedia *_pMediaSource); virtual ~CAudio(); // IMedia implementation virtual ULONG PrepareFrame(); virtual ULONG SyncStreaming(ULONG _ulCurTime, IMediaStreaming *_pOtherMedia); ULONG InitProcessAudioThread(ThreadFunction _ProcessAudio, void *_pCtx); ULONG StopProcessAudioThread(); ULONG ResumeAudioProcessing(); ULONG PauseAudioProcessing(); ULONG PlaySoundBuffer(); ULONG PauseSoundBuffer(); ULONG SampleBufferFull(BOOL *_pbSampleBufferFull); ULONG SoundIsPlaying(BOOL *_pbSoundIsPlaying); ULONG PauseIfBufferEnds(); ULONG WriteFrame(); BOOL ProcessAudioPaused() {return m_bAudioProcessingPaused; } BOOL RunProcessAudio() {return m_bRunProcessAudioThread; } }; #endif
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 51 ] ] ]
e2cafc0ca860a8f3ab1a8a640827a718951f4cef
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/ScExec/PROFILER.CPP
8c8a47106b6738e90392eb55a6ab3b38c2b0c79e
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,462
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== /*#M:Profiler, used by PGM.*/ #include "stdafx.h" #define __PROFILER_CPP #include "sc_defs.h" #include "profiler.h" #include "noise.h" //=========================================================================== CProfileInfo::CProfileInfo() { iLen=0; bLinear = 0; bWrapArround = 0; bStarted = 0; bPaused = 0; bJustLoaded = 0; iPulseSeq = 0; iCurIndex = 0; iPrvIndex = -1; dStartTime = CTimeValue(0.0); dLastTime = CTimeValue(0.0); dPausedVal = 0.0; dFullArea = 0.0; dPrevVal = 0.0; } //=========================================================================== CSimpleProfiler::CSimpleProfiler() { Data.SetSize(0, 0); bLoaded = 0; pInfo = NULL; } //--------------------------------------------------------------------------- CSimpleProfiler::~CSimpleProfiler() { if (pInfo) delete []pInfo; } //--------------------------------------------------------------------------- int CSimpleProfiler::Load(char* Filename, flag LoadHeadings) { if (pInfo) delete []pInfo; pInfo = NULL; bLoaded = 0; if (Filename==NULL) return 1; //cannot open/load the file CVMLoadHelper H; strcpy(H.FName, Filename); H.StartRow = 2; //ignore first row of titles if (!Data.Load(H, NF_Free)) return 1; //cannot open/load the file long Rows = Data.GetRows(); if (Rows==0) return 2; //are no rows long Cols = Data.GetCols(); if (Cols<2) return 3; //must be at least two columns if (!Valid(Data[0][0])) return 6; //time column has a NAN in it for (long i=1; i<Rows; i++) { if (!Valid(Data[i][0])) return 6; //time column has a NAN in it if (Data[i-1][0]>Data[i][0]) return 4; //time column is not incrementing } pInfo = new CProfileInfo[Cols]; pInfo[0].bWrapArround = 1; pInfo[0].bLinear = 1; pInfo[0].iLen = Rows; if (LoadHeadings) { FILE* f=fopen(Filename, "rt"); if (f) { char Buff[8192]; if (fgets(Buff, sizeof(Buff)-1, f)) { char* c[MaxCSVCols]; int Quote; int nFlds = ParseCSVTokens(Buff, c, Quote); if (Quote) { //LogError("Quotes mismatched"); } else { for (int i=0; i<Min(nFlds,(int)Cols); i++) { pInfo[i].sColTagName = (c[i] ? c[i] : ""); } } } fclose(f); } } for (long j=1; j<Cols; j++) { pInfo[j].bWrapArround = 1; i = 0; while (i<Rows && (Valid(Data[i][j]) || HasNANFlag(Data[i][j]))) i++; if (i==0) return 5; //empty column not allowed pInfo[j].iLen = i; } bLoaded = 1; return 0; } //--------------------------------------------------------------------------- void CSimpleProfiler::Options(flag Linear, flag WrapArround, byte Column/*=1*/) { if (bLoaded && Column<Data.GetCols()) { pInfo[Column].bLinear = Linear; pInfo[Column].bWrapArround = WrapArround; } } //--------------------------------------------------------------------------- void CSimpleProfiler::SetAllOptions(flag Linear, flag WrapArround) { if (bLoaded) { for (byte Column=1; Column<Data.GetCols(); Column++) { pInfo[Column].bLinear = Linear; pInfo[Column].bWrapArround = WrapArround; } } } //--------------------------------------------------------------------------- void CSimpleProfiler::JustLoaded(CTimeValue Time, byte Column) { pInfo[Column].dStartTime = Time - (pInfo[Column].dLastTime - pInfo[Column].dStartTime); pInfo[Column].dLastTime = Time; pInfo[Column].bJustLoaded = 0; if (pInfo[Column].iCurIndex>=pInfo[Column].iLen) pInfo[Column].iCurIndex = 0; } //--------------------------------------------------------------------------- double CSimpleProfiler::CalcArea(CTimeValue T1, CTimeValue T2, byte Column) { if (bLoaded && Column<Data.GetCols()) { if (Column==0) //TEMPORARY return 0.0; //TEMPORARY if (T1==T2) return 0.0; CProfileInfo& Info = pInfo[Column]; ASSERT(T1>=0.0 && T2<=Data[Info.iLen-1][0] && T2>T1); double Area = 0.0; CTimeValue DeltaX = 0.0; int i = 0; while (T1>Data[i][0]) i++; if (Info.bLinear || (Column==0)) { //TODO GetAveVal for linear profile Not implemented yet! ASSERT_ALWAYS(FALSE, "KGA : GetAveVal for linear profile Not implemented yet!", __FILE__, __LINE__); } else { if (i>0 && T2>Data[i][0]) { if (Valid(Data[i-1][Column])) { DeltaX = CTimeValue(Data[i][0]) - T1; Area += (DeltaX.Seconds * Data[i-1][Column]); } } flag First = 1; while (T2>Data[i][0]) { if (First) First = 0; else { if (Valid(Data[i-1][Column])) { DeltaX = CTimeValue(Data[i][0]) - Data[i-1][0]; Area += (DeltaX.Seconds * Data[i-1][Column]); } } i++; } if (i==0) { if (Valid(Data[i][Column])) { DeltaX = T2 - T1; Area += (DeltaX * Data[i][Column]); } } else { if (Valid(Data[i-1][Column])) { DeltaX = T2 - Max(T1, Data[i-1][0]); Area += (DeltaX * Data[i-1][Column]); } } } return Area; } return 0.0; } //--------------------------------------------------------------------------- double CSimpleProfiler::Start(CTimeValue Time, byte Column/*=1*/) { if (bLoaded && Column<Data.GetCols()) { if (pInfo[Column].bJustLoaded) JustLoaded(Time, Column); pInfo[Column].dStartTime = Time; pInfo[Column].bStarted = 1; pInfo[Column].bPaused = 0; pInfo[Column].iCurIndex = 0; pInfo[Column].iPrvIndex = -1; if (pInfo[Column].bLinear) pInfo[Column].dFullArea = 0.0; else pInfo[Column].dFullArea = CalcArea(0.0, Data[pInfo[Column].iLen-1][0], Column); return GetVal(Time, Column); } return 0.0; } //--------------------------------------------------------------------------- void CSimpleProfiler::StartAll(CTimeValue Time) { if (bLoaded) { for (byte i=0; i<Data.GetCols(); i++) Start(Time, i); } } //--------------------------------------------------------------------------- double CSimpleProfiler::GetVal(CTimeValue Time, byte Column/*=1*/) { if (bLoaded && Column<Data.GetCols()) { CProfileInfo& Info = pInfo[Column]; if (0) dbgpln("CSimpleProfiler::GetVal %3i %s %s %10.2f %10.2f %10.2f %s", Column, Info.bStarted?"S":" ", Info.bPaused?"P":" ", Info.dLastTime, Info.dPrevVal, Info.dStartTime, Info.sColTagName()); if (Info.bJustLoaded) JustLoaded(Time, Column); if (!Info.bStarted) return Start(Time, Column); if (Info.bPaused) return Info.dPausedVal; Info.dLastTime = Time; CTimeValue RelTime = Time - Info.dStartTime; CTimeValue FullTime = CTimeValue(Data[Info.iLen-1][0]); if (RelTime>FullTime) { if (!Info.bWrapArround) return Data[Info.iLen-1][Column]; if (FullTime==0.0) return Data[Info.iLen-1][Column]; //last entry is at time zero, return this value while (RelTime>FullTime) { Info.dStartTime += FullTime; RelTime = Time - Info.dStartTime; } Info.iCurIndex = 0; } //RelTime -= (FullTime * floor(RelTime/FullTime)); while (RelTime>Data[Info.iCurIndex][0]) Info.iCurIndex++; double RqdValue; if (Info.iCurIndex==0) RqdValue= Data[0][Column]; else if (Info.bLinear || (Column==0)) { CTimeValue DeltaX = CTimeValue(Data[Info.iCurIndex][0]) - CTimeValue(Data[Info.iCurIndex-1][0]); RqdValue=Data[Info.iCurIndex][Column]; if (Valid(RqdValue)) { if (fabs(DeltaX.Seconds)>1.0e-10) RqdValue=Data[Info.iCurIndex-1][Column] + ((RelTime - CTimeValue(Data[Info.iCurIndex-1][0])).Seconds * ((RqdValue - Data[Info.iCurIndex-1][Column]) / DeltaX.Seconds)); else RqdValue=Data[Info.iCurIndex-1][Column]; } else { int xxx=0; } } else RqdValue = Data[Info.iCurIndex-1][Column]; //dbgpln("XXX [%3i,%3i] %f", Info.iCurIndex, Column); if (!Valid(RqdValue)) { // test for buried flags if (HasNANFlag(RqdValue, NF_Pulse)) { if (Info.iCurIndex!=Info.iPrvIndex) Info.iPulseSeq=1; RqdValue = SetNANFlag(NF_Free); } else if (HasNANFlag(RqdValue, NF_Hold)) RqdValue = Info.dPrevVal; else if (HasNANFlag(RqdValue, NF_Free)) { int xxx=0; } switch (Info.iPulseSeq) { case 0: break; case 1: RqdValue = 1; Info.iPulseSeq++; break; case 2: RqdValue = 0; Info.iPulseSeq++; break; case 3: RqdValue = SetNANFlag(NF_Free); Info.iPulseSeq=0; break; } } Info.iPrvIndex=Info.iCurIndex; Info.dPrevVal = RqdValue; return RqdValue; } return 0.0; } //--------------------------------------------------------------------------- double CSimpleProfiler::GetAveVal(CTimeValue Time, byte Column/*=1*/) { if (bLoaded && Column<Data.GetCols()) { CProfileInfo& Info = pInfo[Column]; if (Info.bJustLoaded) JustLoaded(Time, Column); if (!Info.bStarted) return Start(Time, Column); if (Info.bPaused) return Info.dPausedVal; CTimeValue LastTime = Info.dLastTime; CTimeValue TheLastTime = Info.dLastTime; CTimeValue StepTime = Time - LastTime; double Area = 0.0; Info.dLastTime = Time; CTimeValue RelTime = Time - Info.dStartTime; CTimeValue FullTime = Data[Info.iLen-1][0]; if (RelTime>FullTime) { if (LastTime<Info.dStartTime+FullTime) Area += CalcArea(LastTime - Info.dStartTime, Data[Info.iLen-1][0], Column); if (!Info.bWrapArround) { Area += (Data[Info.iLen-1][Column]*(RelTime-Max(FullTime, LastTime-Info.dStartTime)).Seconds); return Area/StepTime.Seconds; } flag First = 1; LastTime = Info.dStartTime + FullTime; while (RelTime>FullTime) { if (First) First = 0; else { Area += Info.dFullArea; LastTime += FullTime; } Info.dStartTime += FullTime; RelTime = Time - Info.dStartTime; } Info.iCurIndex = 0; } Area += CalcArea(LastTime-Info.dStartTime, Time-Info.dStartTime, Column); while (RelTime>Data[Info.iCurIndex][0]) Info.iCurIndex++; return Area/StepTime.Seconds; } return 0.0; } //--------------------------------------------------------------------------- double CSimpleProfiler::Pause(CTimeValue Time, byte Column/*=1*/) { CProfileInfo& Info = pInfo[Column]; if (bLoaded && Column<Data.GetCols()) { Info.dPausedVal = GetVal(Time, Column); Info.bPaused = 1; return Info.dPausedVal; } return 0.0; } //--------------------------------------------------------------------------- double CSimpleProfiler::Continue(CTimeValue Time, byte Column/*=1*/) { CProfileInfo& Info = pInfo[Column]; if (bLoaded && Column<Data.GetCols()) { if (Info.bPaused && Info.bStarted) { Info.dStartTime = Time - (Info.dLastTime - Info.dStartTime); Info.dLastTime = Time; Info.bPaused = 0; return Info.dPausedVal; } else return GetVal(Time, Column); } return 0.0; } //--------------------------------------------------------------------------- /*void CSimpleProfiler::Copy(pCSimpleProfiler p) { ASSERT(p && pInfo==NULL); Data = p->Data; bLoaded = p->bLoaded; if (p->pInfo) { const int Cols = Data.GetCols(); pInfo = new CProfileInfo[Cols]; for (int i=0; i<Cols; i++) pInfo[i] = p->pInfo[i]; } }*/ //========================================================================== const short Idf_ProfLoad = 1; const short Idf_ProfOptions = 2; const short Idf_ProfAllOptions = 3; const short Idf_ProfStart = 4; const short Idf_ProfStartAll = 5; const short Idf_ProfGetVal = 6; const short Idf_ProfGetAveVal = 7; const short Idf_ProfPause = 8; const short Idf_ProfCont = 9; //--------------------------------------------------------------------------- GCProfiler::GCProfiler(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, &IB.m_VarMap, "PROFILER", VarClassDefn) { AddFunct(IB, "Load", 1, 0x0001, Idf_ProfLoad); //Load(filename) AddFunct(IB, "SetOptions", 3, False, Idf_ProfOptions); //SetOptions(Column, WrapArround, Linear) AddFunct(IB, "SetAllOptions", 2, False, Idf_ProfAllOptions); //SetAllOptions(WrapArround, Linear) AddFunct(IB, "Start", 1, False, Idf_ProfStart); //Start(Column) AddFunct(IB, "StartAll", 0, False, Idf_ProfStartAll); //StartAll() AddFunct(IB, "GetVal", 1, False, Idf_ProfGetVal); //GetVal(Column) AddFunct(IB, "GetAveVal", 1, False, Idf_ProfGetAveVal); //GetAveVal(Column) AddFunct(IB, "Pause", 1, False, Idf_ProfPause); //Pause(Column) AddFunct(IB, "Continue", 1, False, Idf_ProfCont); //Continue(Column) } //--------------------------------------------------------------------------- void GCProfiler::Init(pGCClassVar pClassVar) { pClassVar->m_pSubClass = (pvoid)new CSimpleProfiler(); } //--------------------------------------------------------------------------- void GCProfiler::Done(pGCClassVar pClassVar) { delete (pCSimpleProfiler)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCProfiler::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { pCSimpleProfiler pProf = (pCSimpleProfiler)pSubClass; switch (FunctId) { case Idf_ProfLoad: { Strng s,ss; //CNM s.AdaptFilename2(s, IB.GetSParm()); sFilename.FnSearchContract(IB.GetSParm()); s.FnExpand(sFilename()); //CNM s = MakeFullPath(ss, s()); // s = MakeFullFilename(ss, s()); return pProf->Load(s(), false); break; } case Idf_ProfOptions: { flag Linear = IB.GetBParm(); flag WrapArround = IB.GetBParm(); pProf->Options(Linear, WrapArround, IB.GetCParm()); break; } case Idf_ProfAllOptions: { flag Linear = IB.GetBParm(); pProf->SetAllOptions(Linear, IB.GetBParm()); break; } case Idf_ProfStart: return pProf->Start(IB.m_dIC_Time, IB.GetCParm()); break; case Idf_ProfStartAll: return pProf->Start(IB.m_dIC_Time); break; case Idf_ProfGetVal: return pProf->GetVal(IB.m_dIC_Time, IB.GetCParm()); break; case Idf_ProfGetAveVal: return pProf->GetAveVal(IB.m_dIC_Time, IB.GetCParm()); break; case Idf_ProfPause: return pProf->Pause(IB.m_dIC_Time, IB.GetCParm()); break; case Idf_ProfCont: return pProf->Continue(IB.m_dIC_Time, IB.GetCParm()); break; default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCProfiler::OnSave(FilingControlBlock &FCB, pvoid pSubClass) { // if (FCB.SaveAs()) // FCB.CopyFile(sFilename()); pCSimpleProfiler pProf = (pCSimpleProfiler)pSubClass; GCFCBAppendRec(FCB, '{', "PROFILER", NULL, 0); // Start Internal Vars SaveVal(FCB, "Filename", sFilename()); SaveVal(FCB, "ColumnCnt", pProf->ColCnt()); for (byte i=0; i<pProf->ColCnt(); i++) { SaveVal(FCB, "Linear", pProf->Linear(i)); SaveVal(FCB, "WrapArround", pProf->WrapArround(i)); SaveVal(FCB, "Started", pProf->Started(i)); SaveVal(FCB, "StartTime", pProf->StartTime(i)); SaveVal(FCB, "LastTime", pProf->LastTime(i)); SaveVal(FCB, "PausedVal", pProf->PausedVal(i)); SaveVal(FCB, "Paused", pProf->Paused(i)); SaveVal(FCB, "CurIndex", pProf->CurIndex(i)); } GCFCBAppendRec(FCB, '}', "PROFILER", NULL, 0); // End Internal Vars } //--------------------------------------------------------------------------- flag GCProfiler::OnLoad(FilingControlBlock &FCB, pvoid pSubClass) { pCSimpleProfiler pProf = (pCSimpleProfiler)pSubClass; byte ColCnt; byte CurCol = 0; flag Flag; for (;;) { GCFCBBuff Buff; GCFCBReadBuff(FCB, Buff); //dbgpln("..%5i: %c %3i %s",FCB.SetFilePointer(0, FILE_CURRENT), Buff.Hd.Id, Buff.Hd.nTotalLen, Buff.Name()); switch (Buff.Hd.Id) { case '}': { if (pProf->bLoaded) { for (byte i=0; i<pProf->Data.GetCols(); i++) pProf->pInfo[i].bJustLoaded = 1; } return True; } case '{': break; default: if (Buff.Try("Filename", sFilename)) { Strng s; // MakeFullFilename(s, sFilename()); // MakeFullPath(s, sFilename()); sFilename.FnSearchContract(sFilename()); s.FnExpand(sFilename()); // s.FnExpand(sFilename()); pProf->Load(s(), false); break; } if (!pProf->bLoaded) break; if (Buff.Try("ColumnCnt", ColCnt)) break; if (CurCol>=pProf->Data.GetCols()) break; if (Buff.Try("Linear", Flag)) { pProf->pInfo[CurCol].bLinear = Flag; break; } if (Buff.Try("WrapArround", Flag)) { pProf->pInfo[CurCol].bWrapArround = Flag; break; } if (Buff.Try("Started", Flag)) { pProf->pInfo[CurCol].bStarted = Flag; break; } if (Buff.Try("StartTime", pProf->pInfo[CurCol].dStartTime)) break; if (Buff.Try("LastTime", pProf->pInfo[CurCol].dLastTime)) break; if (Buff.Try("PausedVal", pProf->pInfo[CurCol].dPausedVal)) break; if (Buff.Try("Paused", Flag)) { pProf->pInfo[CurCol].bPaused = Flag; break; } long l; if (Buff.Try("CurIndex", l)) { pProf->pInfo[CurCol].iCurIndex = (WORD)l; CurCol++; //move to next column break; } break; } } return True; } //--------------------------------------------------------------------------- /*void GCProfiler::OnRestore(pvoid pOldSubClass, pvoid pNewSubClass) { pCSimpleProfiler pOldProf = (pCSimpleProfiler)pOldSubClass; pCSimpleProfiler pNewProf = (pCSimpleProfiler)pNewSubClass; pNewProf->Copy(pOldProf); }*/ //=========================================================================== /* class CRandomProfiler { public: CBaseNoise OnProf; CBaseNoise OffProf; double dOnOutput; double dOffOutput; double dStartTime; byte bGausian:1; CRandomProfiler(pGCClassVar pClassVar); ~CRandomProfiler(); void Init(double OffMean, double OffStdDev, double OnMean, double OnStdDev); double Start(double Time); double GetVal(double Time); }; //--------------------------------------------------------------------------- CRandomProfiler::CRandomProfiler(pGCClassVar pClassVar) : //OnProf(*(new CBaseNoise(((pGCDoubleVar)pClassVar->GetVarByName("OnMean"))->m_var, ((pGCDoubleVar)pClassVar->GetVarByName("OnStdDev"))->m_var, dOnOutput))), OnProf(((pGCDoubleVar)pClassVar->GetVarByName("OnMean"))->m_var, ((pGCDoubleVar)pClassVar->GetVarByName("OnStdDev"))->m_var, dOnOutput), OffProf(((pGCDoubleVar)pClassVar->GetVarByName("OffMean"))->m_var, ((pGCDoubleVar)pClassVar->GetVarByName("OffStdDev"))->m_var, dOffOutput))) { //pOnProf = new CBaseNoise( bGausian = 1; } //--------------------------------------------------------------------------- CRandomProfiler::~CRandomProfiler() { } //--------------------------------------------------------------------------- void CRandomProfiler::Init(double OffMean, double OffStdDev, double OnMean, double OnStdDev) { } //--------------------------------------------------------------------------- double CRandomProfiler::Start(double Time) { dStartTime = Time; return 0.0; } //--------------------------------------------------------------------------- double CRandomProfiler::GetVal(double Time) { return 0.0; } //=========================================================================== const short Idf_RndProfInit = 1; const short Idf_RndProfOptions = 2; const short Idf_RndProfStart = 3; const short Idf_RndProfGetVal = 4; //--------------------------------------------------------------------------- GCRandomProfiler::GCRandomProfiler(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, "RANDOMPROFILER", VarClassDefn) { AddVar(IB, "Output", &GCDouble, VarConst); AddVar(IB, "OffMean", &GCDouble); AddVar(IB, "OffStdDev", &GCDouble); AddVar(IB, "OnMean", &GCDouble); AddVar(IB, "OnStdDev", &GCDouble); AddFunct(IB, "Init", 4, False, Idf_RndProfInit); //Init(OffMean, OffStdDev, OnMean, OnStdDev) AddFunct(IB, "SetOptions", 2, False, Idf_RndProfOptions); //SetOptions(Gausian, OnFirst, ) AddFunct(IB, "Start", 0, False, Idf_RndProfStart); //Start() AddFunct(IB, "GetVal", 0, False, Idf_RndProfGetVal); //GetVal(Column) } //--------------------------------------------------------------------------- void GCRandomProfiler::Init(pGCClassVar pClassVar) { pClassVar->m_pSubClass = (pvoid)new CRandomProfiler(pClassVar); } //--------------------------------------------------------------------------- void GCRandomProfiler::Done(pGCClassVar pClassVar) { delete (CRandomProfiler*)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCRandomProfiler::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { CRandomProfiler* pRndProf = (CRandomProfiler*)pSubClass; switch (FunctId) { case Idf_RndProfInit: { double d4 = IB.GetDParm(); double d3 = IB.GetDParm(); double d2 = IB.GetDParm(); pRndProf->Init(IB.GetDParm(), d2, d3, d4); return 0.0; break; } case Idf_RndProfOptions: { double d4 = IB.GetDParm(); double d3 = IB.GetDParm(); double d2 = IB.GetDParm(); return 0.0; break; } case Idf_RndProfStart: return pRndProf->Start(IB.m_dIC_Time); break; case Idf_RndProfGetVal: return pRndProf->GetVal(IB.m_dIC_Time); break; default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCRandomProfiler::OnSave(FilingControlBlock &FCB, pvoid pSubClass) { /*if (FCB.SaveAs()) FCB.CopyFile(sFilename()); pCSimpleProfiler pProf = (pCSimpleProfiler)pSubClass; GCFCBAppendRec(FCB, '{', "PROFILER", NULL, 0); // Start Internal Vars SaveVal(FCB, "Filename", sFilename()); SaveVal(FCB, "ColumnCnt", pProf->ColCnt()); for (byte i=0; i<pProf->ColCnt(); i++) { SaveVal(FCB, "Linear", pProf->Linear(i)); SaveVal(FCB, "WrapArround", pProf->WrapArround(i)); SaveVal(FCB, "Started", pProf->Started(i)); SaveVal(FCB, "StartTime", pProf->StartTime(i)); SaveVal(FCB, "LastTime", pProf->LastTime(i)); SaveVal(FCB, "PausedVal", pProf->PausedVal(i)); SaveVal(FCB, "Paused", pProf->Paused(i)); SaveVal(FCB, "CurIndex", pProf->CurIndex(i)); } GCFCBAppendRec(FCB, '}', "PROFILER", NULL, 0); // End Internal Vars*//* } //--------------------------------------------------------------------------- flag GCRandomProfiler::OnLoad(FilingControlBlock &FCB, pvoid pSubClass) { /*pCSimpleProfiler pProf = (pCSimpleProfiler)pSubClass; byte ColCnt; byte CurCol = 0; flag Flag; for (;;) { GCFCBBuff Buff; GCFCBReadBuff(FCB, Buff); //dbgpln("..%5i: %c %3i %s",FCB.SetFilePointer(0, FILE_CURRENT), Buff.Hd.Id, Buff.Hd.nTotalLen, Buff.Name()); switch (Buff.Hd.Id) { case '}': { if (pProf->bLoaded) { for (byte i=0; i<pProf->Data.GetCols(); i++) pProf->pInfo[i].bJustLoaded = 1; } return True; } case '{': break; default: if (Buff.Try("Filename", sFilename)) { Strng s; MakeFullFilename(s, sFilename()); pProf->Load(s()); break; } if (!pProf->bLoaded) break; if (Buff.Try("ColumnCnt", ColCnt)) break; if (CurCol>=pProf->Data.GetCols()) break; if (Buff.Try("Linear", Flag)) { pProf->pInfo[CurCol].bLinear = Flag; break; } if (Buff.Try("WrapArround", Flag)) { pProf->pInfo[CurCol].bWrapArround = Flag; break; } if (Buff.Try("Started", Flag)) { pProf->pInfo[CurCol].bStarted = Flag; break; } if (Buff.Try("StartTime", pProf->pInfo[CurCol].dStartTime)) break; if (Buff.Try("LastTime", pProf->pInfo[CurCol].dLastTime)) break; if (Buff.Try("PausedVal", pProf->pInfo[CurCol].dPausedVal)) break; if (Buff.Try("Paused", Flag)) { pProf->pInfo[CurCol].bPaused = Flag; break; } long l; if (Buff.Try("CurIndex", l)) { pProf->pInfo[CurCol].iCurIndex = (WORD)l; CurCol++; //move to next column break; } break; } }*//* return True; } //--------------------------------------------------------------------------- void GCRandomProfiler::OnRestore(pvoid pOldSubClass, pvoid pNewSubClass) { /*pCSimpleProfiler pOldProf = (pCSimpleProfiler)pOldSubClass; pCSimpleProfiler pNewProf = (pCSimpleProfiler)pNewSubClass; pNewProf->Copy(pOldProf);*//* } */ //=========================================================================== //: Fn(&XYFnClass, "xx", NULL, TOA_Free) /*CBaseProfiler::CBaseProfiler(pGCClassVar pClassVar) : Fn("DataOnly", "xx", NULL, TOA_Free), lFullTime(((pGCWordVar)pClassVar->GetVarByName("FullTime"))->m_var) { }*/ //--------------------------------------------------------------------------- /*CBaseProfiler::CBaseProfiler(pCProfiler pProf) : Fn("DataOnly", "xx", NULL, TOA_Free), dFullTime(pProf->FullTime) { } //--------------------------------------------------------------------------- CBaseProfiler::~CBaseProfiler() { } */ //--------------------------------------------------------------------------- /*int CBaseProfiler::Configure(double FullTime, pchar Filename, UCHAR Column) { dFullTime = fabs(FullTime); CVMLoadHelper H; strcpy(H.FName, Filename); CDMatrix M; if (!M.Load(H)) return 1; //cannot open/load the file long Rows = M.GetRows(); if (Rows==0) return 2; //are no rows if (Column>=M.GetCols()) return 3; //column specified is invalid int Warning = 0; if (dFullTime<0.0001) dFullTime = M[0][Rows-1]; if (M[0][0]>dFullTime) return 4; //first time is greater than maximum allowed for (long i=0; i<Rows-1; i++) { if (M[i+1][0]>FullTime) { Warning = -1; Rows = i+1; M.SetSize(Rows, M.GetCols()); break; } if (M[i][0]>M[i+1][0]) return 5; //time column is not incrementing } Fn.SetLength(Rows()); Fn.Y = M.GetCol(0); Fn.X.SetCol(0, M.GetCol(Column)); return Warning; } //--------------------------------------------------------------------------- double CBaseProfiler::Start(double Time, double StartAt) { return 0.0; } //--------------------------------------------------------------------------- double CBaseProfiler::GetVal(double Time) { return 0.0; }*/ //--------------------------------------------------------------------------- //=========================================================================== /*CProfiler::CProfiler() : CBaseProfiler(this) { }*/ //--------------------------------------------------------------------------- //===========================================================================
[ [ [ 1, 24 ], [ 27, 151 ], [ 153, 162 ], [ 164, 173 ], [ 175, 177 ], [ 179, 181 ], [ 183, 187 ], [ 193, 198 ], [ 200, 200 ], [ 206, 208 ], [ 225, 232 ], [ 234, 254 ], [ 256, 265 ], [ 268, 271 ], [ 278, 284 ], [ 287, 290 ], [ 293, 307 ], [ 309, 311 ], [ 315, 356 ], [ 358, 367 ], [ 371, 372 ], [ 375, 380 ], [ 383, 402 ], [ 404, 409 ], [ 411, 423 ], [ 425, 471 ], [ 473, 473 ], [ 475, 991 ] ], [ [ 25, 26 ], [ 152, 152 ], [ 163, 163 ], [ 174, 174 ], [ 178, 178 ], [ 182, 182 ], [ 188, 192 ], [ 199, 199 ], [ 201, 205 ], [ 211, 215 ], [ 217, 217 ], [ 219, 223 ], [ 233, 233 ], [ 255, 255 ], [ 266, 267 ], [ 272, 277 ], [ 285, 286 ], [ 308, 308 ], [ 312, 314 ], [ 357, 357 ], [ 368, 370 ], [ 373, 374 ], [ 381, 382 ], [ 403, 403 ], [ 410, 410 ], [ 424, 424 ], [ 472, 472 ], [ 474, 474 ] ], [ [ 209, 210 ], [ 216, 216 ], [ 218, 218 ], [ 224, 224 ], [ 291, 292 ] ] ]
c3727798c1c85686bc378482fea497a52a5dddaf
1d8403226cdaf1c54b55cf78d25c6f2910698ef2
/MoveGen.h
00b2e190a2a5850a679dbe76b3cf3758de700d83
[]
no_license
wooce/jkcudachess
d4eac3a2f742843da117b7b1a27d77c848e46efd
08ac2245a12c4a6fb79dd0810cd34842c3bec2f6
refs/heads/master
2021-01-10T02:22:09.003869
2009-07-20T11:42:48
2009-07-20T11:42:48
53,324,029
0
0
null
null
null
null
BIG5
C++
false
false
4,640
h
//////////////////////////////////////////////////////////////////////////////////////////////////////////// // 頭文件︰MoveGen.h // // *******************************************************************************************************// // 中國象棋通用引擎----兵河五四,支持《中國象棋通用引擎協議》(Universal Chinese Chess Protocol,簡稱ucci) // // 作者︰ 范 德 軍 // // 單位︰ 中國原子能科學研究院 // // 郵箱︰ [email protected] // // QQ ︰ 83021504 // // *******************************************************************************************************// // 功能︰ // // 1. 基礎類型CMoveGen, CSearch子類繼承之。棋盤、棋子、位行、位列、著法等數據在這個類中被定義。 // // 2. 通用移動產生器 // // 3. 吃子移動產生器 // // 4. 將軍逃避移動產生器 // // 5. 殺手移動合法性檢驗 // // 6. 將軍檢測Checked(Player), Checking(1-Player) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "FenBoard.h" #pragma once // 棋盤數組和棋子數組 extern int Board[256]; // 棋盤數組,表示棋子序號︰0∼15,無子; 16∼31,黑子; 32∼47, 紅子; extern int Piece[48]; // 棋子數組,表示棋盤位置︰0, 不在棋盤上; 0x33∼0xCC, 對應棋盤位置; // 位行與位列棋盤數組 extern unsigned int xBitBoard[16]; // 16個位行,產生車炮的橫向移動,前12位有效 extern unsigned int yBitBoard[16]; // 16個位列,產生車炮的縱向移動,前13位有效 // 位行與位列棋盤的模 extern const int xBitMask[256]; extern const int yBitMask[256]; // 車炮橫向與縱向移動的16位棋盤,只用于殺手移動合法性檢驗、將軍檢測和將軍逃避 extern unsigned short xBitRookMove[12][512]; // 12288 Bytes, 車的位行棋盤 extern unsigned short yBitRookMove[13][1024]; // 26624 Bytes 車的位列棋盤 extern unsigned short xBitCannonMove[12][512]; // 12288 Bytes 炮的位行棋盤 extern unsigned short yBitCannonMove[13][1024]; // 26624 Bytes 炮的位列棋盤 // Total: // 77824 Bytes = 76K extern unsigned short HistoryRecord[65535]; // 歷史啟發,數組下標為: move = (nSrc<<8)|nDst; extern const char nHorseLegTab[512]; extern const char nDirection[512]; class CMoveGen { public: CMoveGen(void); ~CMoveGen(void); //unsigned short HistoryRecord[65535]; // 歷史啟發,數組下標為: move = (nSrc<<8)|nDst; // 調試訊息 public: unsigned int nCheckCounts; unsigned int nNonCheckCounts; unsigned int nCheckEvasions; // 方法 public: // 更新歷史記錄,清零或者衰減 void UpdateHistoryRecord(unsigned int nMode=0); // 通用移動產生器 int MoveGenerator(const int player, CChessMove* pGenMove); // 吃子移動產生器 int CapMoveGen(const int player, CChessMove* pGenMove); // 將軍逃避移動產生器 int CheckEvasionGen(const int Player, int checkers, CChessMove* pGenMove); // 殺手移動合法性檢驗 int IsLegalKillerMove(int Player, const CChessMove KillerMove); // 將軍檢測,立即返回是否,用于我方是否被將軍 int Checked(int player); // 將軍檢測,返回將軍類型,用于對方是否被將軍 int Checking(int Player); // 保護判斷 int Protected(int Player, int from, int nDst); private: // 檢驗棋子piece是否能夠從nSrc移動到nDst,若成功加入到走法隊列ChessMove中 int AddLegalMove(const int piece, const int nSrc, const int nDst, CChessMove *ChessMove); };
[ "jkinhsnu@4468e6cd-8486-a261-2a9c-65c5dd0b73f5" ]
[ [ [ 1, 89 ] ] ]
efd2090d23c5c2ed96a2de0d5dcba05f0aef2e99
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Graphics/WS/Ordinal/Ordinal.cpp
e0034e81decc80f9e1939dc5d0c9d785c056903a
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
13,584
cpp
// Ordinal.CPP // // Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved. // #include <w32std.h> #include "Base.h" #include "Ordinal.h" _LIT(KString1,"1"); _LIT(KString2,"2"); _LIT(KString3,"3"); _LIT(KString4,"4"); _LIT(KString5,"5"); ////////////////////////////////////////////////////////////////////////////// // CNumberedWindow implementation ////////////////////////////////////////////////////////////////////////////// /****************************************************************************\ | Function: Constructor/Destructor for CNumberedWindow | Input: aClient Client application that owns the window \****************************************************************************/ CNumberedWindow::CNumberedWindow(CWsClient* aClient, TInt aNum) : CWindow(aClient), iNumber(aNum), iOldPos(0, 0) { } CNumberedWindow::~CNumberedWindow() { } /****************************************************************************\ | Function: CNumberedWindow::Draw | Purpose: Redraws the contents of CNumberedWindow within a given | rectangle. CNumberedWindow displays a number in the window. | Input: aRect Rectangle that needs redrawing | Output: None \****************************************************************************/ void CNumberedWindow::Draw(const TRect& aRect) { const TBufC<1> strings[5] = { *&KString1, *&KString2, *&KString3, *&KString4, *&KString5 }; CWindowGc* gc = SystemGc(); // get a graphics context gc->SetClippingRect(aRect); // clip outside the redraw area gc->Clear(aRect); // clear the redraw area TSize size = iWindow.Size(); TInt height = size.iHeight; // Need window height to calculate vertical text offset TInt ascent = Font()->AscentInPixels(); TInt descent = Font()->DescentInPixels(); TInt offset = (height + (ascent + descent)) / 2; // Calculate vertical text offset gc->SetPenColor(TRgb(0, 0, 0)); // Set pen to black gc->UseFont(Font()); gc->DrawText(strings[iNumber], TRect(TPoint(0, 0), size), offset, CGraphicsContext::ECenter); gc->DiscardFont(); } /****************************************************************************\ | Function: CNumberedWindow::HandlePointerEvent | Purpose: Handles pointer events for CNumberedWindow. | Input: aPointerEvent The pointer event | Output: None \****************************************************************************/ void CNumberedWindow::HandlePointerEvent(TPointerEvent& aPointerEvent) { switch (aPointerEvent.iType) { case TPointerEvent::EDrag: { // Move the window position as the pointer is dragged. TPoint point = aPointerEvent.iParentPosition; TPoint distToMove = point - iOldPos; TPoint position = Window().Position(); Window().SetPosition(position + distToMove); iOldPos = point; break; } case TPointerEvent::EButton1Down: { // Move window to front Window().SetOrdinalPosition(0); // Request drag events Window().PointerFilter(EPointerFilterDrag, 0); // Initialize starting point for dragging iOldPos = aPointerEvent.iParentPosition; break; } case TPointerEvent::EButton1Up: { // Cancel the request for drag events. Window().PointerFilter(EPointerFilterDrag, EPointerFilterDrag); break; } case TPointerEvent::EButton3Down: { // Cascade windows in top left corner. // Window at the front should be cascaded last. // The window at the front (ordinal position 0) is given by Child(), and // each window behind it is given by NextSibling(). We need to go down // the sibling list till we get to the last sibling, and move this to // the top left corner. Then go back up the list and move each previous // sibling on top of the last, displaced by an offset (of TPoint(10,10)). TPoint point(0, 0); TUint32 nextSib, prevSib; CWindow* childWindow; TInt numChildren = 0; TUint32 child = Window().Child(); if (child) { childWindow = (CWindow*) child; numChildren++; nextSib = childWindow->Window().NextSibling(); while (nextSib) { numChildren++; childWindow = (CWindow*) nextSib; nextSib = childWindow->Window().NextSibling(); } for (TInt i = numChildren; i > 0; i--) { childWindow->Window().SetPosition(point); prevSib = childWindow->Window().PrevSibling(); if (prevSib) { childWindow = (CWindow*) prevSib; point += TPoint(10, 10); } } } break; } default: break; } } ////////////////////////////////////////////////////////////////////////////// // CMainWindow implementation ////////////////////////////////////////////////////////////////////////////// /****************************************************************************\ | Function: Constructor/Destructor for CMainWindow | Input: aClient Client application that owns the window \****************************************************************************/ CMainWindow::CMainWindow(CWsClient* aClient) : CWindow(aClient) { } CMainWindow::~CMainWindow() { iWindow.Close(); } /****************************************************************************\ | Function: CMainWindow::Draw | Purpose: Redraws the contents of CMainWindow within a given | rectangle. | Input: aRect Rectangle that needs redrawing | Output: None \****************************************************************************/ void CMainWindow::Draw(const TRect& aRect) { CWindowGc* gc = SystemGc(); // get a gc gc->SetClippingRect(aRect); // clip outside this rect gc->Clear(aRect); // clear } /****************************************************************************\ | Function: CMainWindow::HandlePointerEvent | Purpose: Handles pointer events for CMainWindow. | Input: aPointerEvent The pointer event! | Output: None \****************************************************************************/ void CMainWindow::HandlePointerEvent(TPointerEvent& aPointerEvent) { switch (aPointerEvent.iType) { case TPointerEvent::EButton3Down: { // Cascade windows in top left corner // Window at the front should be cascaded last. // The window at the front (ordinal position 0) is given by Child(), and // each window behind it is given by NextSibling(). We need to go down // the sibling list till we get to the last sibling, and move this to // the top left corner. Then go back up the list and move each previous // sibling on top of the last, displaced by an offset (of TPoint(10,10)). TPoint point(0, 0); TUint32 nextSib, prevSib; CWindow* childWindow; TInt numChildren = 0; TUint32 child = Window().Child(); if (child) { childWindow = (CWindow*) child; numChildren++; nextSib = childWindow->Window().NextSibling(); while (nextSib) { numChildren++; childWindow = (CWindow*) nextSib; nextSib = childWindow->Window().NextSibling(); } for (TInt i = numChildren; i > 0; i--) { childWindow->Window().SetPosition(point); prevSib = childWindow->Window().PrevSibling(); if (prevSib) { childWindow = (CWindow*) prevSib; point += TPoint(10, 10); } } } break; } default: break; } } ////////////////////////////////////////////////////////////////////////////// // CExampleWsClient implementation ////////////////////////////////////////////////////////////////////////////// CExampleWsClient* CExampleWsClient::NewL(const TRect& aRect) { // make new client CExampleWsClient* client = new (ELeave) CExampleWsClient(aRect); CleanupStack::PushL(client); // push, just in case client->ConstructL(); // construct and run CleanupStack::Pop(); return client; } /****************************************************************************\ | Function: Constructor/Destructor for CExampleWsClient | Destructor deletes everything that was allocated by | ConstructMainWindowL() \****************************************************************************/ CExampleWsClient::CExampleWsClient(const TRect& aRect) : iRect(aRect) { } CExampleWsClient::~CExampleWsClient() { delete iWindow1; delete iWindow2; delete iWindow3; delete iWindow4; delete iWindow5; delete iMainWindow; } /****************************************************************************\ | Function: CExampleWsClient::ConstructMainWindowL() | Called by base class's ConstructL | Purpose: Allocates and creates all the windows owned by this client | (See list of windows in CExampleWsCLient declaration). \****************************************************************************/ void CExampleWsClient::ConstructMainWindowL() { // Resources allocated in this function are freed in the CExampleWsClient destructor iMainWindow = new (ELeave) CMainWindow(this); iMainWindow->ConstructL(iRect, TRgb(255, 255, 255)); TInt count = 0; TRect rect(TPoint(100, 0), TSize(100, 100)); iWindow1 = new (ELeave) CNumberedWindow(this, count++); iWindow1->ConstructL(rect, TRgb(50, 50, 50), iMainWindow); iWindow2 = new (ELeave) CNumberedWindow(this, count++); iWindow2->ConstructL(rect, TRgb(100, 100, 100), iMainWindow); iWindow3 = new (ELeave) CNumberedWindow(this, count++); iWindow3->ConstructL(rect, TRgb(150, 150, 150), iMainWindow); iWindow4 = new (ELeave) CNumberedWindow(this, count++); rect.Shrink(10, 10); iWindow4->ConstructL(rect, TRgb(200, 200, 200), iWindow1); iWindow5 = new (ELeave) CNumberedWindow(this, count++); iWindow5->ConstructL(rect, TRgb(150, 150, 150), iWindow1); } /****************************************************************************\ | Function: CExampleWsClient::RunL() | Called by active scheduler when an even occurs | Purpose: Processes events according to their type | For key events: calls HandleKeyEventL() (global to client) | For pointer event: calls HandlePointerEvent() for window | event occurred in. \****************************************************************************/ void CExampleWsClient::RunL() { // get the event iWs.GetEvent(iWsEvent); TInt eventType = iWsEvent.Type(); // take action on it switch (eventType) { // events global within window group case EEventNull: break; case EEventKey: { TKeyEvent& keyEvent = *iWsEvent.Key(); // get key event HandleKeyEventL(keyEvent); break; } case EEventKeyUp: case EEventModifiersChanged: case EEventKeyDown: case EEventFocusLost: case EEventFocusGained: case EEventSwitchOn: case EEventPassword: case EEventWindowGroupsChanged: case EEventErrorMessage: break; // events local to specific windows case EEventPointer: { CWindow* window = (CWindow*) (iWsEvent.Handle()); // get window TPointerEvent& pointerEvent = *iWsEvent.Pointer(); window->HandlePointerEvent(pointerEvent); break; } case EEventPointerExit: case EEventPointerEnter: case EEventPointerBufferReady: break; case EEventDragDrop: break; default: break; } IssueRequest(); // maintain outstanding request } /****************************************************************************\ | Function: CExampleWsClient::HandleKeyEventL() | Purpose: Processes key events for CExampleWsClient | Gets the key code from the key event. Exits on 'Escape' \****************************************************************************/ void CExampleWsClient::HandleKeyEventL(TKeyEvent& /*aKeyEvent*/) { }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 353 ] ] ]
6f7086c09ff33638bfa90d058efb7f50396a5350
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/MyGUIEngine/include/MyGUI_Instance.h
9d50505893548012b5efd58c18987888bca84ee0
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
UTF-8
C++
false
false
843
h
/*! @file @author Albert Semenov @date 11/2007 @module */ #ifndef __MYGUI_INSTANCE_H__ #define __MYGUI_INSTANCE_H__ #define INSTANCE_HEADER(type) \ private: \ static type* msInstance; \ bool mIsInitialise; \ public: \ type();\ ~type();\ static type& getInstance(void); \ static type* getInstancePtr(void); #define INSTANCE_IMPLEMENT(type) \ type* type::msInstance = 0; \ type* type::getInstancePtr(void) {return msInstance;} \ type& type::getInstance(void) {MYGUI_ASSERT(0 != msInstance, "instance " << #type << " was not created");return (*msInstance);} \ type::type() : mIsInitialise(false) {MYGUI_ASSERT(0 == msInstance, "instance " << #type << " is exsist");msInstance=this;} \ type::~type() {msInstance=0;} \ const std::string INSTANCE_TYPE_NAME(#type); #endif // __MYGUI_INSTANCE_H__
[ [ [ 1, 29 ] ] ]