int tempzip_make(HWND hwndDlg, TCHAR *fn) { TCHAR buf[MAX_PATH]; GetTempPath(MAX_PATH,buf); GetTempFileName(buf,_T("z2e"),GetTickCount(),tempzip_path); if (!CreateDirectory(tempzip_path,NULL)) { GetTempPath(MAX_PATH,tempzip_path); _tcscat(tempzip_path,_T("\\nsi")); if (!CreateDirectory(tempzip_path,NULL)) { tempzip_path[0]=0; MessageBox(hwndDlg,_T("Error creating temporary directory"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } } FILE *fp=_tfopen(fn,_T("rb")); if (fp) { fseek(fp,0,SEEK_END); g_zipfile_size=ftell(fp); fclose(fp); } else g_zipfile_size=0; unzFile f; f = unzOpen(fn); if (!f || unzGoToFirstFile(f) != UNZ_OK) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error opening ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } int nf=0, nkb=0; g_extracting=1; do { char filenameA[MAX_PATH]; unz_file_info info; // ZREAD uses byte size, not TCHAR length. unzGetCurrentFileInfo(f,&info,filenameA,sizeof(filenameA),NULL,0,NULL,0); // was zip created on MS-DOS/Windows? if ((info.version & 0xFF00) == 0) { OemToCharBuffA(filenameA, filenameA, strlen(filenameA)); } #ifdef _UNICODE TCHAR filename[MAX_PATH]; if (MultiByteToWideChar(CP_ACP, 0, filenameA, -1, filename, MAX_PATH) == 0) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error converting filename to Unicode"), g_errcaption, MB_OK|MB_ICONSTOP); return 1; } #else char* filename = filenameA; #endif if (filename[0] && filename[_tcslen(filename)-1] != _T('\\') && filename[_tcslen(filename)-1] != _T('/')) { TCHAR *pfn=filename; while (*pfn) { if (*pfn == _T('/')) *pfn=_T('\\'); pfn++; } pfn=filename; if (pfn[1] == _T(':') && pfn[2] == _T('\\')) pfn+=3; while (*pfn == _T('\\')) pfn++; TCHAR out_filename[1024]; lstrcpy(out_filename,tempzip_path); lstrcat(out_filename,_T("\\")); lstrcat(out_filename,pfn); if (_tcsstr(pfn,_T("\\"))) { TCHAR buf[1024]; lstrcpy(buf,out_filename); TCHAR *p=buf+_tcslen(buf); while (p > buf && *p != _T('\\')) p--; *p=0; if (buf[0]) doMKDir(buf); } if (unzOpenCurrentFile(f) == UNZ_OK) { SendDlgItemMessage(hwndDlg,IDC_ZIPINFO_FILES,LB_ADDSTRING,0,(LPARAM)pfn); FILE *fp; int l; fp = _tfopen(out_filename,_T("wb")); if (fp) { do { // Jim Park: Local buf, no need to TCHAR char buf[1024]; l=unzReadCurrentFile(f,buf,sizeof(buf)); if (l > 0) { if (fwrite(buf,1,l,fp) != (unsigned int)l) { unzClose(f); fclose(fp); MessageBox(hwndDlg,_T("Error writing output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nkb++; } } while (l > 0); fclose(fp); { // set file time HANDLE hf = CreateFile(out_filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0); if (hf != INVALID_HANDLE_VALUE) { FILETIME ft, lft; DosDateTimeToFileTime(HIWORD(info.dosDate), LOWORD(info.dosDate), &ft); LocalFileTimeToFileTime(&ft, &lft); SetFileTime(hf, 0, 0, &lft); CloseHandle(hf); } } } else { unzClose(f); MessageBox(hwndDlg,_T("Error opening output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nf++; wsprintf(buf,_T("Extracting: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); MSG msg; int quit=0; while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message == WM_DESTROY && msg.hwnd == g_hwnd) { quit++; break; } TranslateMessage(&msg); DispatchMessage(&msg); } unzCloseCurrentFile(f); if (quit) break; } else { unzClose(f); MessageBox(hwndDlg,_T("Error extracting from ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } } } while (unzGoToNextFile(f) == UNZ_OK); g_extracting=0; wsprintf(buf,_T("Extracted: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); unzClose(f); return 0; }
bool CGPUUsage::EnoughTimePassed() { const int minElapsedMS = 1000; return (GetTickCount() - m_dwLastRun) >= minElapsedMS; }
void CodeInjectionPlayer::InjectCode() { if (!opts.enable_code_injection) return; else if (m_next_request_time > GetTickCount()) return; // Window is opened? m_hwnd = FindWindow(); if (m_hwnd == NULL) { m_state = PL_OFFLINE; return; } // Msg Window is registered? (aka plugin is running?) HWND msgHwnd = ::FindWindow(m_message_window_class, NULL); if (msgHwnd != NULL) return; m_next_request_time = GetTickCount() + 30000; // Get the dll path char dll_path[1024] = {0}; if (!GetModuleFileNameA(hInst, dll_path, MAX_REGS(dll_path))) return; char *p = strrchr(dll_path, '\\'); if (p == NULL) return; p++; *p = '\0'; size_t len = p - dll_path; mir_snprintf(p, 1024 - len, "listeningto\\%s.dll", m_dll_name); len = strlen(dll_path); // File exists? DWORD attribs = GetFileAttributesA(dll_path); if (attribs == 0xFFFFFFFF || !(attribs & FILE_ATTRIBUTE_ARCHIVE)) return; // Do the code injection unsigned long pid; GetWindowThreadProcessId(m_hwnd, &pid); HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid); if (hProcess == NULL) return; char *_dll = (char *) VirtualAllocEx(hProcess, NULL, len+1, MEM_COMMIT, PAGE_READWRITE ); if (_dll == NULL) { CloseHandle(hProcess); return; } WriteProcessMemory(hProcess, _dll, dll_path, len+1, NULL); HMODULE hKernel32 = GetModuleHandleA("kernel32"); HANDLE hLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA"); DWORD threadId; HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) hLoadLibraryA, _dll, 0, &threadId); if (hThread == NULL) { VirtualFreeEx(hProcess, _dll, len+1, MEM_RELEASE); CloseHandle(hProcess); return; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); VirtualFreeEx(hProcess, _dll, len+1, MEM_RELEASE); CloseHandle(hProcess); }
cTimeManager::cTimeManager(void) { m_dwLastUpdateTime = GetTickCount(); }
int XGetTickCount() { return GetTickCount(); }
void TMonsterAIGroup::Init(int iGroupNumber) { if ( TMonsterAIGroup::s_iMonsterAIGroupMemberCount[iGroupNumber] == 0 ) return; TMonsterAIGroup::DelGroupInstance(iGroupNumber); for ( int j=0;j<MAX_MONSTER_AI_GROUP_MEMBER;j++) { TMonsterAIGroupMember & Memb = TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][j]; if ( Memb.m_iGuid == -1 ) continue; int iResult = gObjAddMonster(Memb.m_iMapNumber); if ( iResult >= 0 ) { gObj[iResult].m_PosNum = -1; gObj[iResult].MapNumber = Memb.m_iMapNumber; gObj[iResult].Live = TRUE; gObjViewportListProtocolDestroy(&gObj[iResult]); gObjViewportClose(&gObj[iResult]); BYTE cX; BYTE cY; if ( Memb.m_iCreateType == 1 ) { int iRadius = 10; BOOL bGetPosition = FALSE; int iCount = 100; while ( iCount-- != 0 ) { cX = ( rand() % (iRadius+1) ) * (((rand()%2==0)?-1:1)) + Memb.m_iStartX; cY = ( rand() % (iRadius+1) ) * (((rand()%2==0)?-1:1)) + Memb.m_iStartX; BYTE btMapAttr = MapC[Memb.m_iMapNumber].GetAttr(cX, cY); if ( btMapAttr == 0 ) { bGetPosition = TRUE; break; } } if ( bGetPosition == FALSE ) { gObj[iResult].Live = FALSE; gObj[iResult].m_State = 4; gObj[iResult].RegenTime = GetTickCount(); gObj[iResult].DieRegen = 1; return; } } else if ( Memb.m_iCreateType == 0 ) { cX = Memb.m_iStartX; cY = Memb.m_iStartY; } gObj[iResult].X = cX; gObj[iResult].Y = cY; gObj[iResult].MTX = gObj[iResult].X; gObj[iResult].MTY = gObj[iResult].Y; gObj[iResult].TX = gObj[iResult].X; gObj[iResult].TY = gObj[iResult].Y; gObj[iResult].StartX = gObj[iResult].X; gObj[iResult].StartY = gObj[iResult].Y; gObjSetMonster(iResult, Memb.m_iClass); gObj[iResult].m_iGroupNumber = Memb.m_iGroupNumber; gObj[iResult].m_iGroupMemberGuid = Memb.m_iGuid; gObj[iResult].m_iCurrentAI = Memb.m_iStartAI; gObj[iResult].m_iBasicAI = Memb.m_iStartAI; gObj[iResult].m_iRegenType = Memb.m_iRegenType; gObj[iResult].Dir = Memb.m_iStartDir; gObj[iResult].m_State = 1; gObj[iResult].DieRegen = 0; Memb.m_iObjIndex = iResult; if ( Memb.m_iCreateType == -1 ) { gObj[iResult].Live = FALSE; gObj[iResult].m_State = 4; gObj[iResult].RegenTime = GetTickCount(); gObj[iResult].DieRegen = 1; continue; } //#if(_GSCS==0) LogAddTD("[ KANTURU ][ SetAIMonster ] %s(Index:%d ObjIndex:%d) Map:%d-[%d][%d]", gObj[iResult].Name, gObj[iResult].Class, iResult, gObj[iResult].MapNumber, gObj[iResult].X, gObj[iResult].Y); //#endif } } }
// function for downloading files/updating DWORD WINAPI DownloadThread(LPVOID param) { char buffer[IRCLINE]; DWORD r, d, start, total, speed; DOWNLOAD dl = *((DOWNLOAD *)param); DOWNLOAD *dls = (DOWNLOAD *)param; dls->gotinfo = TRUE; HANDLE fh = fInternetOpenUrl(ih, dl.url, NULL, 0, 0, 0); if (fh != NULL) { // open the file HANDLE f = CreateFile(dl.dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); // make sure that our file handle is valid if (f < (HANDLE)1) { sprintf(buffer,"-\x03\x34\2download\2\x03- couldn't open file: %s",dl.dest); if (!dl.silent) irc_privmsg(dl.sock,dl.chan,buffer,dl.notice); addlog(buffer); clearthread(dl.threadnum); ExitThread(0);; } total = 0; start = GetTickCount(); char *fileTotBuff=(char *)malloc(512000); //FIX ME: Only checks first 500 kb do { memset(buffer, 0, sizeof(buffer)); fInternetReadFile(fh, buffer, sizeof(buffer), &r); if (dl.encrypted) Xorbuff(buffer,r); WriteFile(f, buffer, r, &d, NULL); if ((total) < 512000) { //We have free bytes... //512000-total unsigned int bytestocopy; bytestocopy=512000-total; if (bytestocopy>r) bytestocopy=r; memcpy(&fileTotBuff[total],buffer,bytestocopy); } total+=r; if (dl.filelen) if (total>dl.filelen) break; //er, we have a problem... filesize is too big. if (dl.update != 1) sprintf(threads[dl.threadnum].name, "-\x03\x34\2download\2\x03- downloaded %s (%dKB)", dl.url, total / 1024); else sprintf(threads[dl.threadnum].name, "-\x03\x34\2download\2\x03- got update %s (%dKB).", dl.url, total / 1024); } while (r > 0); BOOL goodfile=TRUE; if (dl.filelen) { if (total!=dl.filelen) { goodfile=FALSE; sprintf(buffer,"-\x03\x34\2download\2\x03- wrong filesize (%d != %d).", total, dl.filelen); irc_privmsg(dl.sock,dl.chan,buffer,dl.notice); addlog(buffer); } } speed = total / (((GetTickCount() - start) / 1000) + 1); CloseHandle(f); /* if (dl.expectedcrc) { unsigned long crc,crclength; sprintf(buffer,"crc32([%lu], [%d])\n",fileTotBuff,total); crclength=total; if (crclength>512000) crclength=512000; crc=crc32(fileTotBuff,crclength); if (crc!=dl.expectedcrc) { goodfile=FALSE; irc_privmsg(dl.sock,dl.chan,"CRC Failed!",dl.notice); } } */ free(fileTotBuff); if (dl.expectedcrc) { unsigned long crc=crc32f(dl.dest); if (crc!=dl.expectedcrc) { goodfile=FALSE; sprintf(buffer,"-\x03\x34\2download\2\x03- wrong crc (%d != %d).", crc, dl.expectedcrc); irc_privmsg(dl.sock, dl.chan, buffer, dl.notice); addlog(buffer); } } if (goodfile==FALSE) goto badfile; //download isn't an update if (dl.update != 1) { sprintf(buffer, "-\x03\x34\2download\2\x03- downloaded %.1f KB to %s @ %.1f KB/sec", total / 1024.0, dl.dest, speed / 1024.0); if (!dl.silent) irc_privmsg(dl.sock, dl.chan, buffer, dl.notice); addlog(buffer); if (dl.run == 1) { fShellExecute(0, "open", dl.dest, NULL, NULL, SW_SHOW); if (!dl.silent) { sprintf(buffer,"-\x03\x34\2download\2\x03- opened %s",dl.dest); irc_privmsg(dl.sock,dl.chan,buffer,dl.notice); addlog(buffer); } } // download is an update } else { sprintf(buffer, "-\x03\x34\2download\2\x03- downloaded %.1fKB to %s @ %.1fKB/sec, updating bot", total / 1024.0, dl.dest, speed / 1024.0); if (!dl.silent) irc_privmsg(dl.sock, dl.chan, buffer, dl.notice); addlog(buffer); PROCESS_INFORMATION pinfo; STARTUPINFO sinfo; memset(&pinfo, 0, sizeof(pinfo)); memset(&sinfo, 0, sizeof(sinfo)); sinfo.lpTitle = ""; sinfo.cb = sizeof(sinfo); sinfo.dwFlags = STARTF_USESHOWWINDOW; sinfo.wShowWindow = SW_HIDE; if (CreateProcess(NULL, dl.dest, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo) == TRUE) { fWSACleanup(); uninstall(); ExitProcess(EXIT_SUCCESS); } else { sprintf(buffer,"-\x03\x34\2download\2\x03- update failed, error executing %s",dl.dest); if (!dl.silent) irc_privmsg(dl.sock, dl.chan, buffer, dl.notice); addlog(buffer); } } } else { sprintf(buffer,"-\x03\x34\2download\2\x03- bad url or dns error at %s.",dl.url); if (!dl.silent) irc_privmsg(dl.sock, dl.chan, buffer, dl.notice); addlog(buffer); } badfile: fInternetCloseHandle(fh); clearthread(dl.threadnum); ExitThread(0); }
/* Win32 select() will only work with sockets, so we roll our own implementation here. * - If you supply only sockets, this simply passes through to winsock select(). * - If you supply file handles, there is no way to distinguish between * ready for read/write or OOB, so any set in which the handle is found will * be marked as ready. * - If you supply a mixture of handles and sockets, the system will interleave * calls between select() and WaitForMultipleObjects(). The time slicing may * cause this function call to take up to 100 ms longer than you specified. * - Calling this with NULL sets as a portable way to sleep with sub-second * accuracy is not supported. * */ PHPAPI int php_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tv) { DWORD ms_total, limit; HANDLE handles[MAXIMUM_WAIT_OBJECTS]; int handle_slot_to_fd[MAXIMUM_WAIT_OBJECTS]; int n_handles = 0, i; fd_set sock_read, sock_write, sock_except; fd_set aread, awrite, aexcept; int sock_max_fd = -1; struct timeval tvslice; int retcode; #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set)) /* calculate how long we need to wait in milliseconds */ if (tv == NULL) { ms_total = INFINITE; } else { ms_total = tv->tv_sec * 1000; ms_total += tv->tv_usec / 1000; } FD_ZERO(&sock_read); FD_ZERO(&sock_write); FD_ZERO(&sock_except); /* build an array of handles for non-sockets */ for (i = 0; i < max_fd; i++) { if (SAFE_FD_ISSET(i, rfds) || SAFE_FD_ISSET(i, wfds) || SAFE_FD_ISSET(i, efds)) { handles[n_handles] = (HANDLE)(zend_uintptr_t)_get_osfhandle(i); if (handles[n_handles] == INVALID_HANDLE_VALUE) { /* socket */ if (SAFE_FD_ISSET(i, rfds)) { FD_SET((uint)i, &sock_read); } if (SAFE_FD_ISSET(i, wfds)) { FD_SET((uint)i, &sock_write); } if (SAFE_FD_ISSET(i, efds)) { FD_SET((uint)i, &sock_except); } if (i > sock_max_fd) { sock_max_fd = i; } } else { handle_slot_to_fd[n_handles] = i; n_handles++; } } } if (n_handles == 0) { /* plain sockets only - let winsock handle the whole thing */ return select(max_fd, rfds, wfds, efds, tv); } /* mixture of handles and sockets; lets multiplex between * winsock and waiting on the handles */ FD_ZERO(&aread); FD_ZERO(&awrite); FD_ZERO(&aexcept); limit = GetTickCount() + ms_total; do { retcode = 0; if (sock_max_fd >= 0) { /* overwrite the zero'd sets here; the select call * will clear those that are not active */ aread = sock_read; awrite = sock_write; aexcept = sock_except; tvslice.tv_sec = 0; tvslice.tv_usec = 100000; retcode = select(sock_max_fd+1, &aread, &awrite, &aexcept, &tvslice); } if (n_handles > 0) { /* check handles */ DWORD wret; wret = MsgWaitForMultipleObjects(n_handles, handles, FALSE, retcode > 0 ? 0 : 100, QS_ALLEVENTS); if (wret == WAIT_TIMEOUT) { /* set retcode to 0; this is the default. * select() may have set it to something else, * in which case we leave it alone, so this branch * does nothing */ ; } else if (wret == WAIT_FAILED) { if (retcode == 0) { retcode = -1; } } else { if (retcode < 0) { retcode = 0; } for (i = 0; i < n_handles; i++) { if (WAIT_OBJECT_0 == WaitForSingleObject(handles[i], 0)) { if (SAFE_FD_ISSET(handle_slot_to_fd[i], rfds)) { FD_SET((uint)handle_slot_to_fd[i], &aread); } if (SAFE_FD_ISSET(handle_slot_to_fd[i], wfds)) { FD_SET((uint)handle_slot_to_fd[i], &awrite); } if (SAFE_FD_ISSET(handle_slot_to_fd[i], efds)) { FD_SET((uint)handle_slot_to_fd[i], &aexcept); } retcode++; } } } } } while (retcode == 0 && (ms_total == INFINITE || GetTickCount() < limit)); if (rfds) { *rfds = aread; } if (wfds) { *wfds = awrite; } if (efds) { *efds = aexcept; } return retcode; }
void SemaphoreHeroGameSceneClass::Running(){ //timer count for display timer if(isStart == false){ isStart = false; startTime = GetTickCount(); } endTime = GetTickCount(); deltaTime = endTime - startTime; if(deltaTime>=1000){ timerNum++; timerLabel->displayNum = timerNum; startTime = endTime; deltaTime = 0; } //set current signal if(questionIndex<SIGNAL_NUM){ leftFlag->pos3f.x = FlagSignals[questionIndex].lx; leftFlag->pos3f.y = FlagSignals[questionIndex].ly; rightFlag->pos3f.x = FlagSignals[questionIndex].rx; rightFlag->pos3f.y = FlagSignals[questionIndex].ry; questionLabel->displayStr = FlagSignals[questionIndex].name; //get new signal start time newSignalTime = GetTickCount(); } ///// //logic 1,get hand position x_left = skeletonPlayer.SkeletonPoints[NUI_SKELETON_POSITION_HAND_LEFT].x * skeletonmanScale; y_left = skeletonPlayer.SkeletonPoints[NUI_SKELETON_POSITION_HAND_LEFT].y * skeletonmanScale; x_right = skeletonPlayer.SkeletonPoints[NUI_SKELETON_POSITION_HAND_RIGHT].x * skeletonmanScale; y_right = skeletonPlayer.SkeletonPoints[NUI_SKELETON_POSITION_HAND_RIGHT].y * skeletonmanScale; bool answerL = false; bool answerR = false; //judge left if(leftFlag->CheckInRange2D(x_left,y_left)){ leftFlag->color3f.z = 1; answerL = true; }else{ leftFlag->color3f.z = 0; answerL = false; } //judge right if(rightFlag->CheckInRange2D(x_right,y_right)){ rightFlag->color3f.z = 1; answerR = true; }else{ rightFlag->color3f.z = 0; answerR = false; } if(answerL&&answerR){ //answer right answerLabel->letter = "Signal Right"; finishSignalTime = GetTickCount(); //calculate score scoreTime = finishSignalTime - newSignalTime; int k = scoreTime/1000; if(k>5){ itemList[3]->letter = "You are so .... bad"; }else{ switch(k){ case 0: scoreLabel->letter = "Right"; break; case 1: itemList[3]->letter = "Great"; //scoreLabel->letter break;; case 2: itemList[3]->letter = "A litter good"; break; case 3: itemList[3]->letter = "Common"; break; case 4: itemList[3]->letter = "Bad"; break; case 5: itemList[3]->letter = "Too Bad"; break; } } //end questionIndex++; if(questionIndex >= SIGNAL_NUM){ //current game end allPass = true; questionIndex = 0; } } else{ answerLabel->letter = "Come On..."; } if(allPass){ End(); } }
/** * name: CProgress * class: CProgress * desc: create the progress dialog and return a handle as pointer to the datastructure * params: none * return: nothing **/ CProgress::CProgress() { _dwStartTime = GetTickCount(); _hDlg = CreateDialog(ghInst, MAKEINTRESOURCE(IDD_COPYPROGRESS), 0, (DLGPROC)DlgProcProgress); }
static u32 emulator_get_tick() { return GetTickCount(); }
void Router::Run() { fd_set readfds; struct timeval *tp=new timeval; SOCKADDR from; int RetVal, fromlen, recvlen, wait_count; EVENT_LIST temp; DWORD CurrentTime; unsigned long long count1, count2; count1=0; count2=0; wait_count=0; tp->tv_sec=0; tp->tv_usec=TIMEOUT_USEC; while (1) { try { FD_ZERO(&readfds); FD_SET(Sock1,&readfds); FD_SET(Sock2,&readfds); fromlen=sizeof(from); if((RetVal=select(1,&readfds,NULL,NULL,tp))==SOCKET_ERROR) //check for incoming packets. throw "Timer error!"; else if(RetVal>0) //There are incoming packets. { if(!FileBuf.empty) wait_count++; if(FD_ISSET(Sock1, &readfds)) //incoming packet from peer host 1 { if((recvlen=recvfrom(Sock1, temp.Buffer, sizeof(temp.Buffer), 0, &from, &fromlen))==SOCKET_ERROR) throw " Get buffer error!"; if (TRACE) { fout<<"Router: Receive packet "<<count1<<" from peer host 1"<<endl; cout<<"Router: Receive packet "<<count1<<" from peer host 1"<<endl; } temp.count=count1; count1++; temp.destination=2; } else if(FD_ISSET(Sock2, &readfds)) //incoming packet from peer host 2 { if((recvlen=recvfrom(Sock2, temp.Buffer, sizeof(temp.Buffer), 0, &from, &fromlen))==SOCKET_ERROR) throw " Get buffer error!"; if (TRACE) { fout<<"Router: Receive packet "<<count2<<" from peer host 2"<<endl; cout<<"Router: Receive packet "<<count2<<" from peer host 2"<<endl; } temp.count=count2; count2++; temp.destination=1; } else continue; temp.len=recvlen; CurrentTime=GetTickCount(); if(FileBuf.empty&&IsDelayed()) //if the packet is delayed. { FileBuf=temp; FileBuf.empty=false; if (TRACE) { fout<<"Router: Packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1)<<" has been delayed!"<<endl; cout<<"Router: Packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1)<<" has been delayed!"<<endl; } } else if(IsDamage()) //if the packet is dropped: dropping packet by no forwarding the packet. { if (TRACE) { fout<<"Router: Packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1)<<" has been dropped by router!"<<endl; cout<<"Router: Packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1)<<" has been dropped by router!"<<endl; } } else //otherwise, packet is forwarded to destination { if(temp.destination==1) //forward packets received from 2 to 1. { if(sendto(Sock1, temp.Buffer, temp.len,0,(SOCKADDR*)&sa_in_peer1,sizeof(sa_in_peer1))==SOCKET_ERROR) throw "Send packet error!"; if (TRACE) { fout<<"Router: Send packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1) <<" to host "<<temp.destination<<endl; cout<<"Router: Send packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1) <<" to host "<<temp.destination<<endl; } if(!FileBuf.empty&&FileBuf.destination==1) { wait_count=0; SendProc(); } } else { //forward packets received from 1 to 2. if(sendto(Sock2, temp.Buffer, temp.len,0,(SOCKADDR*)&sa_in_peer2,sizeof(sa_in_peer2))==SOCKET_ERROR) throw "Send packet error1"; if (TRACE) { fout<<"Router: Send packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1) <<" to host "<<temp.destination<<endl; cout<<"Router: Send packet "<<temp.count<<" received from peer host "<<(temp.destination==1?2:1) <<" to host "<<temp.destination<<endl; } if(!FileBuf.empty&&FileBuf.destination==2) { wait_count=0; SendProc(); } } } } else //If there is no incoming packet and there is a delayed packets storing in buffer for 3 cycle times (about 0.9 second), call SendProc to send delayed packet. { if(!FileBuf.empty) { wait_count++; if(wait_count>=3) { SendProc(); wait_count=0; } } } } //end of try catch(char *str) {cerr<<str<<":"<<dec<<WSAGetLastError()<<endl;} }//end of while }
void GLRender() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);//清除的颜色和深度缓冲区 glLoadIdentity();//把当前矩阵设置为单位矩阵,因为绝大多数变换把当前矩阵与指定的矩阵相乘 //glTranslatef(0.0f,0.0f,-20.0f); gluLookAt(10.0f,10.0f,10.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f); /*可以参考红宝书中1-3程序double.c,你需要调用一个设定颜色填充模式的函数glPolygonMode*/ if(ok) { glPushMatrix(); glScalef(cubeScale,cubeScale,cubeScale); glTranslatef(tx,ty,0); glRotatef(rot,vx,vy,vz);//向量(vx,vy.vz)旋转rot角 // glBegin(); GLDrawQuads(cubeVerIndex[12],12); GLDrawQuads(cubeVerIndex[13],13); GLDrawQuads(cubeVerIndex[14],14); GLDrawQuads(cubeVerIndex[15],15); GLDrawQuads(cubeVerIndex[16],16); GLDrawQuads(cubeVerIndex[17],17); GLDrawQuads(cubeVerIndex[18],18); GLDrawQuads(cubeVerIndex[19],19); GLDrawQuads(cubeVerIndex[20],20); GLDrawQuads(cubeVerIndex[21],21); GLDrawQuads(cubeVerIndex[22],22); GLDrawQuads(cubeVerIndex[23],23); //glEnd(); glPopMatrix(); } vx=sin(theta)*cos(miu); vy=cos(theta); vz=sin(theta)*sin(miu); glPushMatrix();//存放当前的变换矩阵 glBegin(GL_LINES);//开始画x、y、z三个坐标轴 glColor3f(1.0f,0.0f,0.0f); glVertex3f(0.0f,0.0f,0.0f); glVertex3f(5.0f,0.0f,0.0f); glColor3f(0.0f,1.0f,0.0f); glVertex3f(0.0f,0.0f,0.0f); glVertex3f(0.0f,5.0f,0.0f); glColor3f(0.0f,0.0f,1.0f); glVertex3f(0.0f,0.0f,0.0f); glVertex3f(0.0f,0.0f,5.0f); glEnd();//把当前的矩阵从堆栈里清出去 glPopMatrix();//恢复到开始的变换矩阵,避免连环变换的情况 glColor3f(1.0f,1.0f,1.0f);//指定即将要画的图形的颜色(准确地说是顶点的颜色) glPushMatrix(); glScalef(cubeScale,cubeScale,cubeScale); glBegin(GL_LINES); glVertex3f(-10.0f*vx,-10.0f*vy,-10.0f*vz);//方向为(vx,vy,vz)轴 glVertex3f(10.0f*vx,10.0f*vy,10.0f*vz); glEnd(); glPopMatrix(); if(gWireMode) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glPushMatrix(); glTranslatef(tx,ty,0); glRotatef(rot,vx,vy,vz);//向量(vx,vy.vz)旋转rot角 glMultMatrixd(cubeMatrix); glScalef(cubeScale,cubeScale,cubeScale); GLDrawCube(); glPopMatrix(); static signed __int64 lastTickCount=GetTickCount(); signed __int64 TickCount=GetTickCount(); float dt=(TickCount-lastTickCount)/1000.0f; lastTickCount=TickCount; GLProcessKey(dt); GLProcessMouse(dt); if(rot>=360.0f)rot-=360.0f; /***************************************************************************GLRender中需要你们实现的部分至此结束********************************************************************/ glFlush(); //强制刷新缓冲区的函数,如果去掉呢? glutSwapBuffers(); //交换使用另一个缓冲区,为什么要交换呢?原理在红宝书第一章动画那一节里有阐述 }
int _gcry_rndw32_gather_random_fast (void (*add)(const void*, size_t, int), int requester ) { static int addedFixedItems = 0; if ( debug_me ) log_debug ("rndw32#gather_random_fast: req=%d\n", requester ); /* Get various basic pieces of system information: Handle of active * window, handle of window with mouse capture, handle of clipboard owner * handle of start of clpboard viewer list, pseudohandle of current * process, current process ID, pseudohandle of current thread, current * thread ID, handle of desktop window, handle of window with keyboard * focus, whether system queue has any events, cursor position for last * message, 1 ms time for last message, handle of window with clipboard * open, handle of process heap, handle of procs window station, types of * events in input queue, and milliseconds since Windows was started */ { byte buffer[20*sizeof(ulong)], *bufptr; bufptr = buffer; #define ADD(f) do { ulong along = (ulong)(f); \ memcpy (bufptr, &along, sizeof (along) ); \ bufptr += sizeof (along); } while (0) ADD ( GetActiveWindow ()); ADD ( GetCapture ()); ADD ( GetClipboardOwner ()); ADD ( GetClipboardViewer ()); ADD ( GetCurrentProcess ()); ADD ( GetCurrentProcessId ()); ADD ( GetCurrentThread ()); ADD ( GetCurrentThreadId ()); ADD ( GetDesktopWindow ()); ADD ( GetFocus ()); ADD ( GetInputState ()); ADD ( GetMessagePos ()); ADD ( GetMessageTime ()); ADD ( GetOpenClipboardWindow ()); ADD ( GetProcessHeap ()); ADD ( GetProcessWindowStation ()); ADD ( GetQueueStatus (QS_ALLEVENTS)); ADD ( GetTickCount ()); assert ( bufptr-buffer < sizeof (buffer) ); (*add) ( buffer, bufptr-buffer, requester ); #undef ADD } /* Get multiword system information: Current caret position, current * mouse cursor position */ { POINT point; GetCaretPos (&point); (*add) ( &point, sizeof (point), requester ); GetCursorPos (&point); (*add) ( &point, sizeof (point), requester ); } /* Get percent of memory in use, bytes of physical memory, bytes of free * physical memory, bytes in paging file, free bytes in paging file, user * bytes of address space, and free user bytes */ { MEMORYSTATUS memoryStatus; memoryStatus.dwLength = sizeof (MEMORYSTATUS); GlobalMemoryStatus (&memoryStatus); (*add) ( &memoryStatus, sizeof (memoryStatus), requester ); } /* Get thread and process creation time, exit time, time in kernel mode, and time in user mode in 100ns intervals */ { HANDLE handle; FILETIME creationTime, exitTime, kernelTime, userTime; DWORD minimumWorkingSetSize, maximumWorkingSetSize; handle = GetCurrentThread (); GetThreadTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); (*add) ( &creationTime, sizeof (creationTime), requester ); (*add) ( &exitTime, sizeof (exitTime), requester ); (*add) ( &kernelTime, sizeof (kernelTime), requester ); (*add) ( &userTime, sizeof (userTime), requester ); handle = GetCurrentProcess (); GetProcessTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); (*add) ( &creationTime, sizeof (creationTime), requester ); (*add) ( &exitTime, sizeof (exitTime), requester ); (*add) ( &kernelTime, sizeof (kernelTime), requester ); (*add) ( &userTime, sizeof (userTime), requester ); /* Get the minimum and maximum working set size for the current process */ GetProcessWorkingSetSize (handle, &minimumWorkingSetSize, &maximumWorkingSetSize); (*add) ( &minimumWorkingSetSize, sizeof (minimumWorkingSetSize), requester ); (*add) ( &maximumWorkingSetSize, sizeof (maximumWorkingSetSize), requester ); } /* The following are fixed for the lifetime of the process so we only * add them once */ if (!addedFixedItems) { STARTUPINFO startupInfo; /* Get name of desktop, console window title, new window position and * size, window flags, and handles for stdin, stdout, and stderr */ startupInfo.cb = sizeof (STARTUPINFO); GetStartupInfo (&startupInfo); (*add) ( &startupInfo, sizeof (STARTUPINFO), requester ); addedFixedItems = 1; } /* The performance of QPC varies depending on the architecture it's * running on and on the OS. Under NT it reads the CPU's 64-bit timestamp * counter (at least on a Pentium and newer '486's, it hasn't been tested * on anything without a TSC), under Win95 it reads the 1.193180 MHz PIC * timer. There are vague mumblings in the docs that it may fail if the * appropriate hardware isn't available (possibly '386's or MIPS machines * running NT), but who's going to run NT on a '386? */ { LARGE_INTEGER performanceCount; if (QueryPerformanceCounter (&performanceCount)) { if ( debug_me ) log_debug ("rndw32#gather_random_fast: perf data\n"); (*add) (&performanceCount, sizeof (performanceCount), requester); } else { /* Millisecond accuracy at best... */ DWORD aword = GetTickCount (); (*add) (&aword, sizeof (aword), requester ); } } return 0; }
// A function which is called from RefreshScreen void NetGseEx::RefreshScreenProcess(HINSTANCE hinst, HWND hwnd, HDC hdc) { int EleCnt = 0; // Draw background OfficeGSE::DrawBackground(hinst, hwnd, hdc); for (int i = 0; i < m_CurrentRequest; i++) { int c = m_ActReq[i]->GetActorId(); int r = m_ActReq[i]->GetRequest(); if (c != 0 && r >= 100) { // Draw Link of each element DrawOfficeASELink(hinst, hwnd, hdc, m_ActReq[i]); } else if (c == 0) { // Draw OfficeManagerASE OfficeGSE::DrawOfficeManagerASE(hinst, hwnd, hdc, m_ActReq[i]); } } for (int i = 0; i < m_CurrentRequest; i++) { int c = m_ActReq[i]->GetActorId(); int r = m_ActReq[i]->GetRequest(); // Draw OfficeASE if (c != 0 && r < 100) { EleCnt++; DrawOfficeASE(hinst, hwnd, hdc, m_ActReq[i]); } } // RunTime information static DWORD ctime = 0; static DWORD ptime = 0; ctime = GetTickCount(); if (ptime != 0) { RtiRefreshInterval = ctime - ptime; } else { RtiRefreshInterval = 0; } ptime = ctime; RtiElementCount = EleCnt; RtiRequestCount = m_CurrentRequest; RtiRunningCount = GetNumOfRunStkThread(); SetMouseAction(0); // When some threads are running... if (GetNumOfRunStkThread() != 0) { int ArsWidth = m_ActiveRSRight - m_ActiveRSLeft; int ArsHeight = m_ActiveRSBottom - m_ActiveRSTop; static int StatusRunX[4]; static int StatusRunY[4]; static int RunningRefreshInterval = 0; if (RunningRefreshInterval >= 1000) { RunningRefreshInterval = 0; } if (RunningRefreshInterval == 0) { for (int Loop = 0; Loop < 4; Loop++) { StatusRunX[Loop] = rand() % (ArsWidth - 200) + m_ActiveRSLeft; StatusRunY[Loop] = rand() % (ArsHeight - 80) + m_ActiveRSTop; } } RunningRefreshInterval += RtiRefreshInterval; int NumOfOut = 1; if (ArsWidth * ArsHeight >= 1310720) { // >= SXGA NumOfOut = 4; } else if (ArsWidth * ArsHeight >= 786432) { // >= XGA NumOfOut = 3; } else if (ArsWidth * ArsHeight >= 480000) { // >= SVGA NumOfOut = 2; } for (int Loop = 0; Loop < NumOfOut; Loop++) { StkFont::GetInstance()->ArialFontLargeTextOut(hdc, StatusRunX[Loop], StatusRunY[Loop], MyMsgProc::GetMsg(MyMsgProc::STKFW_RUNNING), RGB(255, 255, 255), FALSE); } EnterCriticalSection(&CritSect); ResetWorkspace(3); GetViewFromDb(); LeaveCriticalSection(&CritSect); } ClearRequest(); }
bool GLWindow::create(int width, int height, int bpp, bool fullscreen) { DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style m_isFullscreen = fullscreen; //Store the fullscreen flag m_windowRect.left = (long)0; // Set Left Value To 0 m_windowRect.right = (long)width; // Set Right Value To Requested Width m_windowRect.top = (long)0; // Set Top Value To 0 m_windowRect.bottom = (long)height; // Set Bottom Value To Requested Height // fill out the window class structure m_windowClass.cbSize = sizeof(WNDCLASSEX); m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.lpfnWndProc = GLWindow::StaticWndProc; //We set our static method as the event handler m_windowClass.cbClsExtra = 0; m_windowClass.cbWndExtra = 0; m_windowClass.hInstance = m_hinstance; m_windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon m_windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow m_windowClass.hbrBackground = NULL; // don't need background m_windowClass.lpszMenuName = NULL; // no menu m_windowClass.lpszClassName = "GLClass"; m_windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon // register the windows class if (!RegisterClassEx(&m_windowClass)) { return false; } if (m_isFullscreen) //If we are fullscreen, we need to change the display mode { DEVMODE dmScreenSettings; // device mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; // screen width dmScreenSettings.dmPelsHeight = height; // screen height dmScreenSettings.dmBitsPerPel = bpp; // bits per pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // setting display mode failed, switch to windowed MessageBox(NULL, "Display mode failed", NULL, MB_OK); m_isFullscreen = false; } } if (m_isFullscreen) // Are We Still In Fullscreen Mode? { dwExStyle = WS_EX_APPWINDOW; // Window Extended Style dwStyle = WS_POPUP; // Windows Style ShowCursor(false); // Hide Mouse Pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&m_windowRect, dwStyle, false, dwExStyle); // Adjust Window To True Requested Size // class registered, so now create our window m_hwnd = CreateWindowEx(NULL, // extended style "GLClass", // class name "David Schneider - FPS Demo", // app name dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, // x,y coordinate m_windowRect.right - m_windowRect.left, m_windowRect.bottom - m_windowRect.top, // width, height NULL, // handle to parent NULL, // handle to menu m_hinstance, // application instance this); // we pass a pointer to the GLWindow here // check if window creation failed (hwnd would equal NULL) if (!m_hwnd) return 0; m_hdc = GetDC(m_hwnd); ShowWindow(m_hwnd, SW_SHOW); // display the window UpdateWindow(m_hwnd); // update the window m_lastTime = GetTickCount() / 1000.0f; //Initialize the time return true; }
void IDXGISwapChainNew::preUpdateBB(UINT *width, UINT *height) { dbg("dxgi_sc: preUpdateBB"); int rrx = config.main.renderResolution.x; int rry = config.main.renderResolution.y; if(*width == rrx && *height == rry) { dbg("dxgi_sc: Multihead swapchain mode detected"); HEAD *h = config.getPrimaryHead(); *width = h->screenMode.x; *height = h->screenMode.y; // Set mouse hook on application focus window ihGlobal.setHWND(win); SoftTHActive++; h->hwnd = win; // Create new backbuffer dbg("dxgi_sc: Creating new backbuffer"); // TODO: format #if defined(SOFTTHMAIN) || defined(D3D11) if(dev11) { // Create the full backbuffer render texture dbg("dxgi_sc: Creating FULL backbuffer for D3D11 Device"); //CD3D10_TEXTURE2D_DESC d(DXGI_FORMAT_R8G8B8A8_UNORM, rrx, rry, 1, 1, D3D10_BIND_RENDER_TARGET, D3D10_USAGE_DEFAULT, NULL); CD3D11_TEXTURE2D_DESC d(DXGI_FORMAT_R8G8B8A8_UNORM, rrx, rry, 1, 1, D3D11_BIND_RENDER_TARGET, D3D11_USAGE_DEFAULT, NULL); newbbDesc11 = d; if(dev11->CreateTexture2D(&newbbDesc11, NULL, &newbb11) != S_OK) dbg("dxgi_sc: CreateTexture2D failed :("), exit(0); // Initialize outputs numDevs = config.getNumAdditionalHeads(); dbg("dxgi_sc: Initializing %d outputs", numDevs); int logoStopTime = GetTickCount() + 4000; bool fpuPreserve = true; // TODO: does this exist in d3d10? outDevs11 = new OUTDEVICE11[numDevs]; stagingOuts11 = new STAGINGOUT11[numDevs]; for(int i=0;i<numDevs;i++) { OUTDEVICE11 *o = &outDevs11[i]; STAGINGOUT11 *so = &stagingOuts11[i]; so->headID = i+1; so->devID = h->devID; so->stagingSurf = NULL; // Create the output device HEAD *h = config.getHead(i); dbg("dxgi_sc: Initializing Head %d (DevID: %d)",i+1,h->devID); o->output = new outDirect3D11(h->devID, h->screenMode.x, h->screenMode.y, h->transportRes.x, h->transportRes.y, win); o->cfg = h; bool local = h->transportMethod==OUTMETHOD_LOCAL; if (!local) has_nonlocal = true; dbg("dxgi_sc: Head %d is %s", i+1, local?"local":"non-local"); // Create a main staging buffer sized for this head if non-local if (!local) { dbg("dxgi_sc: Creating a main non-local staging buffer for Head %d (DevID %d)", i + 1, h->devID); CD3D11_TEXTURE2D_DESC dss(DXGI_FORMAT_R8G8B8A8_UNORM, h->transportRes.x, h->transportRes.y, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE, 1, 0, 0); /*DWORD32 *fillbuf = new DWORD32[h->transportRes.x*h->transportRes.y]; for (int ii = 0; ii < h->transportRes.y; ii++) for (int jj = 0; jj < h->transportRes.x; jj++) { if ((ii&32)==(jj&32)) fillbuf[ii*h->transportRes.x + jj] = (DWORD32) 0x0000ff00; else fillbuf[ii*h->transportRes.x + jj] = (DWORD32) 0xffffffff; } D3D11_SUBRESOURCE_DATA fillsr; ZeroMemory(&fillsr, sizeof(fillsr)); fillsr.pSysMem = (void *)fillbuf; fillsr.SysMemPitch = h->transportRes.x * 4; fillsr.SysMemSlicePitch = h->transportRes.x * h->transportRes.y * 4; if (dev11->CreateTexture2D(&dss, &fillsr, &so->stagingSurf) != S_OK) {*/ if (dev11->CreateTexture2D(&dss, NULL, &so->stagingSurf) != S_OK) { dbg("dxgi_sc: CreateTexture2D staged for Head %d (DevID %d) failed :(",i+1,h->devID), exit(0); } } // Create shared surfaces HANDLE sha = o->output->GetShareHandle(); if(sha) { o->localSurf = NULL; { // Open surfA share handle ID3D11Resource *tr; if (o->cfg->transportMethod == OUTMETHOD_LOCAL) { // Local output if (dev11->OpenSharedResource(sha, __uuidof(ID3D11Resource), (void**)(&tr)) != S_OK) dbg("dxgi_sc: Local OpenSharedResource A failed!"), exit(0); } else { // Non-local output if (o->output->dev->OpenSharedResource(sha, __uuidof(ID3D11Resource), (void**)(&tr)) != S_OK) dbg("dxgi_sc: Non-local OpenSharedResource A failed!"), exit(0); } if(tr->QueryInterface(__uuidof(ID3D11Texture2D), (void**)(&o->localSurf)) != S_OK) dbg("dxgi_sc: Shared surface QueryInterface failed!"), exit(0); tr->Release(); } dbg("dxgi_sc: Opened share handles"); } else dbg("dxgi_sc: ERROR: Head %d: No share handle!", i+1), exit(0); } // Create the full backbuffer staged texture if we have non-local head /*if (has_nonlocal) { CD3D11_TEXTURE2D_DESC ds(DXGI_FORMAT_R8G8B8A8_UNORM, rrx, rry, 1, 1, NULL, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, D3D11_RESOURCE_MISC_SHARED); newbbDesc11staged = ds; if(dev11->CreateTexture2D(&newbbDesc11staged, NULL, &newbb11staged) != S_OK) dbg("dxgi_sc: CreateTexture2D staged failed :("), exit(0); }*/ } #endif #ifdef SOFTTHMAIN else #endif #if defined(SOFTTHMAIN) || defined(D3D10_1) if(dev10_1) { dbg("dxgi_sc: Creating backbuffer for D3D10.1 Device"); CD3D10_TEXTURE2D_DESC d(DXGI_FORMAT_R8G8B8A8_UNORM, rrx, rry, 1, 1, D3D10_BIND_RENDER_TARGET, D3D10_USAGE_DEFAULT, NULL); newbbDesc10 = d; if(dev10_1->CreateTexture2D(&newbbDesc10, NULL, &newbb10) != S_OK) dbg("dxgi_sc: CreateTexture2D failed :("), exit(0); // Initialize outputs numDevs = config.getNumAdditionalHeads(); dbg("dxgi_sc: Initializing %d outputs", numDevs); int logoStopTime = GetTickCount() + 4000; bool fpuPreserve = true; // TODO: does this exist in d3d10? outDevs10 = new OUTDEVICE10[numDevs]; for(int i=0;i<numDevs;i++) { OUTDEVICE10 *o = &outDevs10[i]; // Create the output device HEAD *h = config.getHead(i); bool local = h->transportMethod==OUTMETHOD_LOCAL; dbg("dxgi_sc: Initializing head %d (DevID: %d, %s)...", i+1, h->devID, local?"local":"non-local"); o->output = new outDirect3D10(h->devID, h->screenMode.x, h->screenMode.y, h->transportRes.x, h->transportRes.y, win); o->cfg = h; // Create shared surfaces HANDLE sha = o->output->GetShareHandle(); if(sha) { o->localSurf = NULL; { // Open surfA share handle ID3D10Resource *tr; if(dev10_1->OpenSharedResource(sha, __uuidof(ID3D10Resource), (void**)(&tr)) != S_OK) dbg("dxgi_sc: OpenSharedResource A failed!"), exit(0); if(tr->QueryInterface(__uuidof(ID3D10Texture2D), (void**)(&o->localSurf)) != S_OK) dbg("dxgi_sc: Shared surface QueryInterface failed!"), exit(0); tr->Release(); } dbg("dxgi_sc: Opened share handles"); } else dbg("dxgi_sc: ERROR: Head %d: No share handle!", i+1), exit(0); } } #endif #ifdef SOFTTHMAIN else #endif #if defined(SOFTTHMAIN) || defined(D3D10) if(dev10) { dbg("dxgi_sc: Creating backbuffer for D3D10 Device"); CD3D10_TEXTURE2D_DESC d(DXGI_FORMAT_R8G8B8A8_UNORM, rrx, rry, 1, 1, D3D10_BIND_RENDER_TARGET, D3D10_USAGE_DEFAULT, NULL); newbbDesc10 = d; if(dev10->CreateTexture2D(&newbbDesc10, NULL, &newbb10) != S_OK) dbg("dxgi_sc: CreateTexture2D failed :("), exit(0); // Initialize outputs numDevs = config.getNumAdditionalHeads(); dbg("dxgi_sc: Initializing %d outputs", numDevs); int logoStopTime = GetTickCount() + 4000; bool fpuPreserve = true; // TODO: does this exist in d3d10? outDevs10 = new OUTDEVICE10[numDevs]; for(int i=0;i<numDevs;i++) { OUTDEVICE10 *o = &outDevs10[i]; // Create the output device HEAD *h = config.getHead(i); bool local = h->transportMethod==OUTMETHOD_LOCAL; dbg("dxgi_sc: Initializing head %d (DevID: %d, %s)...", i+1, h->devID, local?"local":"non-local"); o->output = new outDirect3D10(h->devID, h->screenMode.x, h->screenMode.y, h->transportRes.x, h->transportRes.y, win); o->cfg = h; // Create shared surfaces HANDLE sha = o->output->GetShareHandle(); if(sha) { o->localSurf = NULL; { // Open surfA share handle ID3D10Resource *tr; if(dev10->OpenSharedResource(sha, __uuidof(ID3D10Resource), (void**)(&tr)) != S_OK) dbg("dxgi_sc: OpenSharedResource A failed!"), exit(0); if(tr->QueryInterface(__uuidof(ID3D10Texture2D), (void**)(&o->localSurf)) != S_OK) dbg("dxgi_sc: Shared surface QueryInterface failed!"), exit(0); tr->Release(); } dbg("dxgi_sc: Opened share handles"); } else dbg("dxgi_sc: ERROR: Head %d: No share handle!", i+1), exit(0); } } #endif } else { dbg("dxgi_sc: Singlehead swapchain mode"); SoftTHActive--; if(dev11) { if(newbb11) SAFE_RELEASE_LAST(newbb11); newbb11 = NULL; } else if(dev10 || dev10_1) { if(newbb10) SAFE_RELEASE_LAST(newbb10); newbb10 = NULL; } } }
OSTime OSTimeNow(void) { return GetTickCount(); }
void ALog::LogUnsecure(LPCTSTR description, ...) { if (m_pViewer == NULL) return ; INT messageDepth = MD_Invalid; LPCTSTR pos = description; DOUBLE measure = -1.0; //=== Retrieve the depth if (*pos == '@') { switch (pos[1]) { case '0': //=== GetLastError TRACE("@0 Class-Function. The error is: ", x, y, z); case '1': //=== GetLastError TRACE("@0 Class-Function. The warning is: ", x, y, z); case '2': //=== GetLastError TRACE("@0 Class-Function. The Info L1 is: ", x, y, z); case '3': case '4': if (*pos == '0') messageDepth = MD_System; else messageDepth = pos[1] - '1' + 1; pos+=2; break; case '@': //=== System Message. messageDepth = MD_System; pos+=2; break; case 'D': //=== Debug Message. //Function: Exactly like warnings //TRACE("@D Removed on release"); //WHY? Sometimes you want to debug a certain function and remove //the debug info later. You can easily search and remove them using 'TRACE(_T("@D' search messageDepth = MD_Debug; pos+=2; break; } } if (messageDepth == MD_Invalid) messageDepth = GetOption(LO_DefaultDepth); if (GetOption(LO_AlwaysCheckForLastError) && !(messageDepth == MD_System)) { DWORD dwLastError = GetLastError(); if ( dwLastError == 2 || //"The system cannot find the file specified" dwLastError == 3 || //"The system cannot find the path specified" dwLastError == 6 || //"The handle is invalid" dwLastError == 18) //"There are no more files" { SetLastError(0); dwLastError = 0; } if (dwLastError) { SetLastError(0); const int mLen = 1500; TCHAR message[mLen]; message[0] = 0; LPTSTR lpMsgBuf; INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR) &lpMsgBuf, 0, NULL ); if (len>0) { if (len>2) lpMsgBuf[len - 3] = 0; _sntprintf(message, 1500, _T("@@ GetLastError [AUTO]: [%d] '%s'\r\n"), dwLastError, lpMsgBuf); LocalFree((HLOCAL)lpMsgBuf); } else _sntprintf(message, 1500, _T("@@ GetLastError [AUTO]: [%d] '?'\r\n"), dwLastError); SetLastError(0); Log(message); } } if (messageDepth > GetOption(LO_MaxAllowedDepth)) return;//===------------------------------Filter OUT all messages const int mLen = 2500; TCHAR message[mLen]; message[0] = 0; INT curLen = 0; if (GetOption(LO_ShowDepth)) curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[%s] "), Depth[messageDepth + 2]); DWORD dwLastError = GetLastError(); if (dwLastError && GetOption(LO_AlwaysCheckForLastError)) { LPTSTR lpMsgBuf; INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR) &lpMsgBuf, 0, NULL ); if (len>0) { if (len>2) lpMsgBuf[len - 3] = 0; curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: [%d] '%s'\r\n\t"), dwLastError, lpMsgBuf); LocalFree((HLOCAL)lpMsgBuf); } else curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: [%d] - No Description available\r\n\t"), dwLastError); SetLastError(0); } if (*pos == '@') { pos++; switch (*pos) { case 'E': //=== GetLastError TRACE("@E Class-Function.: ", x, y, z); //Also: TRACE("@1@E Class-Function.: ", x, y, z); //If there is no error - no message will be displayed { pos++; LPTSTR lpMsgBuf; if (dwLastError == 0) { dwLastError = GetLastError(); SetLastError(0); } if (dwLastError == 0)//No error return; INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR) &lpMsgBuf, 0, NULL ); if (len>0) { if (len>2) lpMsgBuf[len - 3] = 0; curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: '%s'\r\n\t"), lpMsgBuf); LocalFree((HLOCAL)lpMsgBuf); } else curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: 'Unknown' : %d\r\n\t"), dwLastError); } break; #ifdef USE_CPUTICKER case 'T': //=== Mark - Measure Time //TRACE("@T"); ==> silent (no message). Just marks the time //TRACE("@T Class-Function.", x,y,z); ==> [M:Measured Time xxx.xx ms] //Also TRACE("@T") for silent (no message) { if (m_pTicker == NULL) m_pTicker = new CCPUTicker; __int64 curTime = m_pTicker->Measure(); __int64 passedTime = curTime - m_markedTime; m_markedTime = curTime; pos++; if (*pos == 0) return;//Do NOT SHOW THIS MESSAGE curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[T: %6.5f ms]"), (passedTime * 1000.0) / CCPUTicker::GetCachedCPUFrequency()); message[mLen - 1] = 0; } break; #endif case 'I': { pos++; HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ::GetCurrentProcessId()); if(hProcess) { PROCESS_MEMORY_COUNTERS ProcessMemoryCounters; memset(&ProcessMemoryCounters, 0, sizeof(ProcessMemoryCounters)); ProcessMemoryCounters.cb = sizeof(ProcessMemoryCounters); if(::GetProcessMemoryInfo(hProcess, &ProcessMemoryCounters, sizeof(ProcessMemoryCounters)) == TRUE) { curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[I:Memory: %d (%d) / %d (kb)] "), ProcessMemoryCounters.WorkingSetSize/1024, ProcessMemoryCounters.WorkingSetSize/1024 - m_markedMemSize, ProcessMemoryCounters.PeakWorkingSetSize/1024); m_markedMemSize = ProcessMemoryCounters.WorkingSetSize/1024; } ::CloseHandle(hProcess); } } break; } } if (*pos == 32)//Trim space pos++; if (GetOption(LO_ShowTimeDate)) { SYSTEMTIME t; GetLocalTime(&t); curLen += GetTimeFormat(LOCALE_SYSTEM_DEFAULT, NULL, &t, _T("'['HH':'mm':'ss'] '"), &message[curLen], mLen - curLen); curLen--; } if (GetOption(LO_ShowTimeFromStartup)) curLen += _sntprintf(&message[curLen], mLen - curLen, _T("%08.3fms "), (GetTickCount() - m_StartupTicks)/1000.0); if (GetOption(LO_ShowThreadID)) { DWORD threadID = ::GetCurrentThreadId(); if (m_MainThreadID != threadID) curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[THR: %4X] "), threadID); } va_list list; va_start(list, description); curLen += _vsntprintf(&message[curLen], mLen - curLen, pos, list); va_end(list); //Adding CRLF at the end if needed if (mLen - curLen > 3) { if (message[curLen-1] == 13 || message[curLen-1] == 10) curLen--; if (message[curLen-1] == 13 || message[curLen-1] == 10) curLen--; message[curLen] = 13; message[curLen + 1] = 10; message[curLen + 2] = 0; } else message[mLen - 1] = 0; //CThreadLock lock(&m_cs, TRUE); if (!m_pViewer->Show(message)) { delete m_pViewer; m_pViewer = NULL; } }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HINSTANCE v4; // esi //int v11; // ecx char Filename[260]; // [esp+8h] [ebp-10Ch] char value_name[8]; // [esp+10Ch] [ebp-8h] v4 = hInstance; #ifndef DEBUGGER diablo_reload_process(hInstance); #endif ghInst = v4; if ( RestrictedTest() ) ErrDlg(TEMPLATE_ERR_RESTRICTED, 0, "C:\\Src\\Diablo\\Source\\DIABLO.CPP", 877); if ( ReadOnlyTest() ) { if ( !GetModuleFileNameA(ghInst, Filename, 0x104u) ) *Filename = '\0'; DirErrDlg(Filename); } ShowCursor(FALSE); srand(GetTickCount()); encrypt_init_lookup_table(); exception_get_filter(); if ( !diablo_find_window("DIABLO") && diablo_get_not_running() ) { diablo_init_screen(); diablo_parse_flags(lpCmdLine); init_create_window(); sound_init(); UiInitialize(); #ifdef _DEBUG if ( showintrodebug ) play_movie("gendata\\logo.smk", 1); #else play_movie("gendata\\logo.smk", 1); #endif strcpy(value_name, "Intro"); if ( !SRegLoadValue("Diablo", value_name, 0, (int *)&hInstance) ) hInstance = (HINSTANCE)1; if ( hInstance ) play_movie("gendata\\diablo1.smk", 1); SRegSaveValue("Diablo", value_name, 0, 0); #ifdef _DEBUG if ( showintrodebug ) { UiTitleDialog(7); BlackPalette(); } #else UiTitleDialog(7); BlackPalette(); #endif mainmenu_action(0); /* v11 fix unused arg */ UiDestroy(); palette_save_gamme(); if ( ghMainWnd ) { Sleep(300); DestroyWindow(ghMainWnd); } } return 0; }
void cTimeManager::Update() { DWORD dwCurrTime = GetTickCount(); m_dwDeltaTime = dwCurrTime - m_dwLastUpdateTime; m_dwLastUpdateTime = dwCurrTime; }
SaneWinMain(argc, argv ) //int main( int argc, char **argv ) { int x = 0; int y = 0; uint32_t width, height; int w, h; g.pdi = GetDisplayInterface(); g.pii = GetImageInterface(); RegisterIcon( NULL ); GetDisplaySize( &width, &height ); w = width; h = height; y = x = 0; { int state = 0; int arg; g.fade_in = 500; g.show_time = 1000; for( arg = 1; arg < argc; arg++ ) { if( argv[arg][0] == '-' ) { if( argv[arg][1] == 'i' ) { g.flags.bShowInverted = 1; } else { switch( state ) { case 0: x = atoi( argv[arg]+1 ); break; case 1: y = atoi( argv[arg]+1 ); break; case 2: w = atoi( argv[arg]+1 ); break; case 3: h = atoi( argv[arg]+1 ); break; case 4: g.show_time = atoi( argv[arg]+1 ); break; case 5: g.fade_in = atoi( argv[arg]+1 ); break; } state++; } } else { Image x = LoadImageFile( argv[arg] ); if( x ) { g.nImages++; AddLink( &g.images, x ); } } } } if( g.nImages ) { g.displays[0] = OpenDisplaySizedAt( DISPLAY_ATTRIBUTE_LAYERED|DISPLAY_ATTRIBUTE_CHILD|DISPLAY_ATTRIBUTE_NO_MOUSE|DISPLAY_ATTRIBUTE_NO_AUTO_FOCUS , w //width , h //height , x //0 , y //0 ); g.displays[1] = OpenDisplaySizedAt( DISPLAY_ATTRIBUTE_LAYERED|DISPLAY_ATTRIBUTE_CHILD|DISPLAY_ATTRIBUTE_NO_MOUSE|DISPLAY_ATTRIBUTE_NO_AUTO_FOCUS , w //width , h //height , x //0 , y //0 ); SetRedrawHandler( g.displays[0], Output, 0 ); SetRedrawHandler( g.displays[1], Output, 1 ); if( g.nImages > 1 ) { target_in_start = GetTickCount(); AddTimer( 33, tick, 0 ); } else { //lprintf( "Show the first and only the first image." ); g.is_up[0] = 1; RestoreDisplay( g.displays[0] ); UpdateDisplay( g.displays[0] ); } while( 1 ) WakeableSleep( 10000 ); } else { } return 0; }
cPlayer::cPlayer(void) { srand( GetTickCount() ); Init(); }
DWORD DrTimerThread::ThreadEntry() { DWORD currentTime; int timeToExpire; DrJob * timer; while (true) { //Analyse the current state of the timer heap Lock(); currentTime=GetTickCount(); while (true) { timer = (DrJob*) m_timerHeap.PeekHeapRoot(); //If there are no more timers on the heap then our timeout on our event //is infinite and we're done checking the heap if (timer==NULL) { m_dwTimerThreadSleepPeriod=INFINITE; break; } //Looks like we've got a timer. Work out when it'll expire relative to now LogAssert(timer->m_isActiveTimer); timeToExpire=(int ) (timer->m_expiryTime-currentTime); //If it hasn't expired yet then that should be our timeout and we're done //checking the heap if (timeToExpire>0) { m_dwTimerThreadSleepPeriod=(DWORD)timeToExpire; break; } //Looks like we've got an expired timer. Mark is as no longer active, pop it from heap //and pass it to a worker thread for processing timer->m_isActiveTimer=false; m_timerHeap.DequeueHeapRoot(); BOOL fSuccess = m_pPool->EnqueueJob(timer, currentTime, NULL); LogAssert(fSuccess); } //Little wrinkle here. We don't want to wake up too often and we don't care //to be all that accurate for expiring timers. Therefore, if timeout is //too small we'll push it out in the hope of expiring more timers at once if (m_dwTimerThreadSleepPeriod<c_TimerExpirySlopPeriod) { m_dwTimerThreadSleepPeriod=c_TimerExpirySlopPeriod; } m_timerThreadWakesAt=currentTime+m_dwTimerThreadSleepPeriod; ResetEvent(m_timerEventHandle); Unlock(); //Above should have set timeout for an appropriate value. Sleep waiting for that time //to expire or to be told we have a new head of the heap timer WaitForSingleObject(m_timerEventHandle, m_dwTimerThreadSleepPeriod); //Possible we were woken because the thread pool is being shut down so check that case if (m_pPool->ShouldQuit()) { break; } } //Treat any timers still scheduled as if they were cancelled Lock(); while (true) { timer = (DrJob*) m_timerHeap.DequeueHeapRoot(); if (timer==NULL) { break; } LogAssert(timer->m_isActiveTimer==true); timer->m_isActiveTimer=false; } Unlock(); return 0; }
int Game_Init(void *parms = NULL, int num_parms = 0) { // this is called once after the initial window is created and // before the main event loop is entered, do all your initialization // here // create IDirectDraw interface 7.0 object and test for error if (FAILED(DirectDrawCreateEx(NULL, (void **)&lpdd, IID_IDirectDraw7, NULL))) return(0); // set cooperation to full screen if (FAILED(lpdd->SetCooperativeLevel(main_window_handle, DDSCL_FULLSCREEN | DDSCL_ALLOWMODEX | DDSCL_EXCLUSIVE | DDSCL_ALLOWREBOOT))) return(0); // set display mode to 640x480x24 if (FAILED(lpdd->SetDisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,0,0))) return(0); // clear ddsd and set size DDRAW_INIT_STRUCT(ddsd); // enable valid fields ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; ddsd.dwBackBufferCount = 1; // // request primary surface ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_COMPLEX | DDSCAPS_FLIP; // create the primary surface if (FAILED(lpdd->CreateSurface(&ddsd, &lpddsprimary, NULL))) return(0); ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER; if(FAILED(lpddsprimary->GetAttachedSurface(&ddsd.ddsCaps, &lpddsback))) return 0; // 把主屏和缓冲屏都填充为黑色初始化 DDraw_Fill_Surface(lpddsprimary, _RGB32BIT(0, 0,0,0)); DDraw_Fill_Surface(lpddsback, _RGB32BIT(0, 0,0,0)); // load the 24-bit image char* bmp_wc = "WarCraft24.bmp"; char* bmp_b8 = "bitmap8b.bmp"; char* bmp_b24 = "bitmap24.bmp"; char* bmp_b24e = "bitmap24_edit.bmp"; char* bmp_mo24 = "mosaic-600x.bmp"; char* bmp_ni24 = "nightelf-640x.bmp"; char* bmp_alley24 = "alley8_24bit.bmp"; // 载入背景图片 if (!Load_Bitmap_File(&bitmap, bmp_ni24)) return(0); // 创建背景表面、但实际上不是直接用背景表面来显示的、而是拷贝去缓冲表面和人物动作混合 // 后才一次性打到显示表面 // 这里头两个参数是指在屏幕的高和宽、第二个是指表面建立的地点、0指在显存建立、其它表示在 // 系统内存建立、当然速度自然是在显存建立快了、最后一个参数是是否设置为色彩键、这里设定为-1 // 也就是不设定任何色彩过滤、因为这个是背景表面、所以不需要任何透明的色彩键 lpddsbackground = DDraw_Create_Surface(640,480,0,-1); // 把bmp的内容拷贝至缓冲表面中 Bmp2Surface(lpddsbackground, SCREEN_WIDTH, SCREEN_HEIGHT); // 从现在开始创建人物动作了 if (!Load_Bitmap_File(&bitmap, "Dedsp0_24bit.bmp")) return(0); // seed random number generator // GetTickCount是一个系统启动至今的毫秒数、 // 配合srandg来产生一个随机数 srand(GetTickCount()); // initialize all the aliens // alien on level 1 of complex // //系统在调用rand()之前都会自动调用srand(),如果用户在rand()之前曾调用过srand()给参数seed指定了一个值, //那么rand()就会将seed的值作为产生伪随机数的初始值; //而如果用户在rand()前没有调用过srand(),那么rand()就会自动调用srand(1),即系统默认将1作为伪随机数的初始值。 //所以前面要调用一次srand来确保以下调用rand()的值会产生不同 // aliens[0].x = rand()%SCREEN_WIDTH; aliens[0].y = 116 - 72; aliens[0].velocity = 2+rand()%4; aliens[0].current_frame = 0; aliens[0].counter = 0; // alien on level 2 of complex aliens[1].x = rand()%SCREEN_WIDTH; aliens[1].y = 246 - 72; aliens[1].velocity = 2+rand()%4; aliens[1].current_frame = 0; aliens[1].counter = 0; // alien on level 3 of complex aliens[2].x = rand()%SCREEN_WIDTH; aliens[2].y = 382 - 72; aliens[2].velocity = 2+rand()%4; aliens[2].current_frame = 0; aliens[2].counter = 0; // now load the bitmap containing the alien imagery // then scan the images out into the surfaces of alien[0] // and copy then into the other two, be careful of reference counts! // 现在开始载入人物的动画帧图片了 if (!Load_Bitmap_File(&bitmap,"Dedsp0_24bit.bmp")) return(0); // create each surface and load bits // 初始化异形0号的三个动作帧表面、 // 其实、所有的异形动作帧表面都一样的、所以没有必要为每个异形都创建相应的动作帧、 // 所以其它异形的动作帧都指向这个异形0号的动作帧就可以了 for (int index = 0; index < 3; index++) { // create surface to hold image aliens[0].frames[index] = DDraw_Create_Surface(72,80,0); // now load bits... Scan_Image_Bitmap(&bitmap, // bitmap file to scan image data from aliens[0].frames[index], // surface to hold data index, 0); // cell to scan image from } // end for index // unload the bitmap file, we no longer need it Unload_Bitmap_File(&bitmap); // now for the tricky part. There is no need to create more surfaces with the same // data, so I'm going to copy the surface pointers member for member to each alien // however, be careful, since the reference counts do NOT go up, you still only need // to release() each surface once! for (index = 0; index < 3; index++) aliens[1].frames[index] = aliens[2].frames[index] = aliens[0].frames[index]; // return success or failure or your own return code here return(1); } // end Game_Init
void ChronoClass::increaseSystem(){ if(systemTime != GetTickCount()){ systemTime = GetTickCount(); increase(); } }
/*********************************************************************************** WinMain - Entry point for program. ***********************************************************************************/ int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { CLog *pLog = CLog::Instance(); pLog->Log(" "); pLog->Log("***************************************"); pLog->Log("Program Start"); pLog->LogDate(); pLog->Log("***************************************"); //request player choose fullscreen or windowed mode CConfigData cfg; cfg.LoadConfigFile("assets//data//config.cfg"); bool bFullscreen = false; bFullscreen = cfg.FullScreen; //int msgReturn = ::MessageBox(NULL, "Fullscreen? (Y/N)", "Select Display Option", MB_YESNO); //if(msgReturn == IDYES) // bFullscreen = true; //variable declarations CGameData gameData; CTimer gTimerFPS; int gLoopCount = 0; int gSecondCount = 0; bool g_bRunning = true; bool gExitProgram = false; //this is set true with ESC, for rendering to stop properly //determine if we play new or saved game /* gameData.m_playNewGame = true; HRESULT hr = ::MessageBox(0, "Play new game?", "New or saved game!", MB_YESNO); if(hr == IDYES) gameData.m_playNewGame = true; else gameData.m_playNewGame = false; */ gameData.m_playNewGame = true; //setup game data pLog->Log("Program Name", cfg.ProgramName); pLog->Log("Version", cfg.ProgramVersion); //create window HWND hWnd; WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = "WindowClass"; wc.hIconSm = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)); RegisterClassEx(&wc); //screen data - need at least 800x600 int cxScreen = ::GetSystemMetrics(SM_CXFULLSCREEN); int cyScreen = ::GetSystemMetrics(SM_CYFULLSCREEN); if(cfg.ScreenWidth < 800 || cfg.ScreenWidth > cxScreen) cfg.ScreenWidth = cxScreen; if(cfg.ScreenHeight < 600 || cfg.ScreenHeight > cyScreen) cfg.ScreenHeight = cyScreen; cfg.ScreenLeft = cxScreen/2 - cfg.ScreenWidth/2; cfg.ScreenTop = cyScreen/2 - cfg.ScreenHeight/2; //create window std::string sCaption = cfg.ProgramName + " - " + cfg.ProgramVersion; hWnd = CreateWindowEx(NULL, "WindowClass", sCaption.c_str(), //cfg.ProgramVersion.c_str(), bFullscreen == true ? WS_EX_TOPMOST | WS_POPUP : WS_BORDER | WS_CAPTION | WS_SYSMENU, cfg.ScreenLeft, cfg.ScreenTop, bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenWidth, bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenHeight, NULL,NULL,hInstance,NULL); ShowWindow(hWnd, nCmdShow); pLog->Log("Window Loaded and Displayed!"); gameData.m_hWnd = hWnd; // set up and initialize Direct3D CGraphics con(hWnd, cfg.ScreenWidth, cfg.ScreenHeight,bFullscreen);// cfg.FullScreen); if(con.InitializeDirectX() == false){ pLog->Log("Failure initializing DirectX!"); ::MessageBox(hWnd,"Failed to initialize DirectX", "Error", 0); return 0; } pLog->Log("DirectX Initialized"); //load framework assets if(con.LoadAssetFile(cfg.FrameworkAssetFile) == false){ pLog->Log("Failure loading " + cfg.FrameworkAssetFile); ::MessageBox(hWnd,"Failed to load editor.dat file", "Error", 0); return 0; } else pLog->Log(cfg.FrameworkAssetFile + " (frame graphics) was loaded successfully!"); //load game play assets if(con.LoadAssetFile(cfg.GamePlayAssetFile) == false){ pLog->Log("Failure loading " + cfg.GamePlayAssetFile); ::MessageBox(hWnd,"Failed to load assets.dat file", "Error", 0); return 0; } else pLog->Log(cfg.GamePlayAssetFile + " (game play graphics) was loaded successfully!"); //load objects //*************************************************************************** if(gameData.LoadObjectFile(cfg.GameObjectFile) == false){ pLog->Log("Failure loading " + cfg.GameObjectFile); ::MessageBox(hWnd,"Failed to load objects.dat file", "Error", 0); return 0; } else{ pLog->Log(cfg.GameObjectFile + " (objects file) was loaded successfully!"); for(int i = 0; i < gameData.m_catalog.GetTableSize();++i){ pLog->Log("object", gameData.m_catalog.GetTerm(i, 0), gameData.m_catalog.GetTerm(i, 2)); } } gTimerKey.Initialize(); gTimerKey.ResetTimer(); mouse.SetHandle(hWnd); gTimerFPS.Initialize(); //game timer for update CTimer timerGame; timerGame.Initialize(); //define events for changing game states //************************************************************************* //g_pStateIntro->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1); //g_pStatePlay1->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits); g_pStateIntro->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateMain->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1); g_pStateMain->AddTransitionEvent(EVENT_GO_HELP, g_pStateHelp); g_pStateMain->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits); g_pStatePlay1->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateHelp->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateCredits->AddTransitionEvent(EVENT_GO_QUIT, g_pStateQuit); g_pCurrent = g_pStateIntro; //************************************** S O U N D ************************ //initialize sound manager //audio setup CAudioManager *pAudio = CAudioManager::Instance(); pAudio->LoadFile("assets\\data\\sounds.dat"); //load sound asset file pAudio->LoadFile(cfg.SoundAssetFile); /* if(pAudio->LoadFile(cfg.SoundAssetFile) == false){ pLog->Log("Failure loading " + cfg.GamePlayAssetFile);//assets.dat audio files!"); ::MessageBox(hWnd,"Failed to load assets.dat audio files!", "Error", 0); } else pLog->Log(cfg.GamePlayAssetFile + " (audio) was loaded successfully!"); */ /* if(pAudio->IsValidSound() == true) pLog->Log("Audio system initialized (size)", pAudio->Size()); else pLog->Log("Audio failure!"); */ //log all audio files if(cfg.LogDebugInfo == true){ pLog->Log("************************** Audio Files Loaded **************"); // for(int i = 0; i < pAudio->Size(); i++){ // pLog->Log(pAudio->GetFilename(i)); // } pLog->Log(""); } // enter the main loop //************************************** M A I N L O O P ***************** MSG msg; pLog->Log("Entering Main Control Loop"); float timeDiff = 0.0f; g_pCurrent->Activate(gameData, cfg, con); //********************* // PYRO //con.InitializePyro(); while(g_bRunning) { DWORD starting_point = GetTickCount(); if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } //manage frame count determination gLoopCount++; if(gTimerFPS.getTimer(1.0) == true){ gameData.m_FPS = static_cast<float>(gLoopCount); gLoopCount = 0; gSecondCount++; if(gSecondCount > 30){ //log every 30 seconds gSecondCount = 0; if(cfg.LogDebugInfo == true) pLog->Log("FPS",gameData.m_FPS); } } //stores mouse button status for use in other classes gameData.m_bLeftMouseDown = mouse.LeftButtonDown(); gameData.m_bRightMouseDown = mouse.RightButtonDown(); //update g_pLast = g_pCurrent; g_pNext = g_pCurrent->Update(timerGame.getTimeDifference(), gameData, cfg, con); if(g_pNext == g_pStateQuit) g_bRunning = false; else if(NULL != g_pNext) { if(g_pNext != g_pLast){ g_pLast->Deactivate(gameData, cfg, con); g_pCurrent = g_pNext; g_pCurrent->Activate(gameData, cfg, con); } } //render g_pCurrent->Render(con, gameData, cfg); // check the 'escape' key if(g_bRunning == false){ gExitProgram = true; PostMessage(hWnd, WM_DESTROY, 0, 0); } } pLog->Log("Exited main loop"); //************************** // PYRO //con.ClosePyro(); // clean up DirectX and COM con.CleanupDirectX(); Shutdown(); pLog->Log("DirectX Cleaned Up"); pLog->Log("Shutdown complete!"); pLog->Log("***************************************"); pLog->Log(" Program Terminated Normally"); pLog->Log("***************************************"); return static_cast<int>(msg.wParam); }
//--------------------------------------------------------------------------- void __fastcall TSound::Wait(DWORD msec) { DWORD tc = GetTickCount(); while( ! Terminated && GetTickCount()-tc < msec ) Sleep(1); }
/******************************************************************** * Function : SimLoop() * Purpose : Performs a single Simulation Loop iteration. Includes * drawing. ********************************************************************/ int SimLoop(void) { static int nFramesPerSecond = 0; static int nFramesSinceLastTick; static DWORD LastTicks = 0; DWORD Ticks; HDC hDC; HFONT hOldFont; char s[80]; int slen; DDSURFACEDESC ddsd; DDBLTFX BltFx; HRESULT ddreturn; /* Perform a single step in our world. */ if (StepWorld(bForwardKey, bBackKey, bLeftKey, bRightKey, nState, nGauge)) { if (lpPrimary->IsLost() == DDERR_SURFACELOST) lpPrimary->Restore(); /* Clear the backbuffer. */ #if CLEARBCKGRND BltFx.dwSize = sizeof(BltFx); BltFx.dwFillColor = 255; ddreturn = lpBackbuffer->Blt(NULL, NULL, NULL, DDBLT_COLORFILL | DDBLT_WAIT, &BltFx); #else ddreturn = DD_OK; #endif if (ddreturn == DD_OK) { /* While this is running, prepare * the drawing. */ if (PrepDrawWorld()) { /* Lock the surface. */ memset(&ddsd, 0, sizeof(DDSURFACEDESC)); ddsd.dwSize = sizeof(ddsd); ddreturn = lpBackbuffer->Lock(NULL, &ddsd, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, NULL); if (ddreturn == DD_OK) { DrawWorld((unsigned char *)ddsd.lpSurface, (int)ddsd.lPitch); int nX, nY; static unsigned char dummy; unsigned char ni; ni = 0; for (nY = 0; nY < 16; nY++) for (nX = 0; nX < 16; nX++) { /* Draw a small block at (nX * 3, nY * 3) */ ((unsigned char *)ddsd.lpSurface)[(nY * 3 * ddsd.lPitch) + (nX * 3)] = ni; ((unsigned char *)ddsd.lpSurface)[(nY * 3 * ddsd.lPitch) + (nX * 3 + 1)] = ni; ((unsigned char *)ddsd.lpSurface)[((nY * 3 + 1) * ddsd.lPitch) + (nX * 3)] = ni; ((unsigned char *)ddsd.lpSurface)[((nY * 3 + 1) * ddsd.lPitch) + (nX * 3 + 1)] = ni; ni++; } lpBackbuffer->Unlock(NULL); /* And now write Frames per second. */ /* Increment Frame counter. */ nFramesSinceLastTick++; /* Get system tick count. */ Ticks = GetTickCount(); /* Update fps value every second. */ if (Ticks > (LastTicks + 1000)) { nFramesPerSecond = nFramesSinceLastTick; nFramesSinceLastTick = 0; LastTicks = Ticks; } /* Get a DC to the buffer & write count. */ if (DD_OK == lpBackbuffer->GetDC(&hDC)) { SetBkMode(hDC, TRANSPARENT); hOldFont = SelectObject(hDC, AppFont); /* Build a string for display. */ slen = wsprintf(s, "FPS : %d", nFramesPerSecond); /* And draw the text. */ SetTextColor(hDC, RGB(0,0,0)); SIZE sz; GetTextExtentPoint32(hDC, s, slen, &sz); RECT rc; rc.top = 0; rc.left = 16 * 3; rc.right = 16 * 3 + sz.cx + 10; rc.bottom = sz.cy + 10; DrawFrameControl(hDC, &rc, DFC_BUTTON, DFCS_BUTTONPUSH); TextOut(hDC, 16*3 + 5, 5, s, slen); SelectObject(hDC, hOldFont); lpBackbuffer->ReleaseDC(hDC); } /* Perform required pageflipping to make the surface * we drawed visible. */ ddreturn = lpPrimary->Flip(NULL, DDFLIP_WAIT); if (ddreturn == DD_OK) { return 1; } } } } } return 0; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Hook spew output. SpewOutputFunc( MySpewOutputFunc ); // Get access to the registry.. RegCreateKey( HKEY_LOCAL_MACHINE, VMPI_SERVICE_KEY, &g_hVMPIServiceKey ); // Setup our version string. LoadString( hInstance, VMPI_SERVICE_IDS_VERSION_STRING, g_VersionString, sizeof( g_VersionString ) ); // Setup the base app path. if ( !GetModuleFileName( GetModuleHandle( NULL ), g_BaseAppPath, sizeof( g_BaseAppPath ) ) ) { Warning( "GetModuleFileName failed.\n" ); return false; } V_StripLastDir( g_BaseAppPath, sizeof( g_BaseAppPath ) ); // Setup the cache path. V_ComposeFileName( g_BaseAppPath, "vmpi_service_cache", g_FileCachePath, sizeof( g_FileCachePath ) ); const char *pArg = FindArg( __argc, __argv, "-mpi_pw", NULL ); SetPassword( pArg ); if ( FindArg( __argc, __argv, "-console" ) ) { g_RunMode = RUNMODE_CONSOLE; } else { g_RunMode = RUNMODE_SERVICE; } if ( FindArg( __argc, __argv, "-superdebug" ) ) g_bSuperDebugMode = true; g_AppStartTime = GetTickCount(); g_bMinimized = FindArg( __argc, __argv, "-minimized" ) != NULL; ServiceHelpers_Init(); g_hInstance = hInstance; LoadStateFromRegistry(); // Install the service? if ( g_RunMode == RUNMODE_CONSOLE ) { RunAsNonServiceApp(); } else { RunService(); } return 0; }