int main(int argc, char *argv[]) #endif { #ifndef LITEAPP_LIBRARY #if defined(_MSC_VER) && defined(_DEBUG) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); #endif #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication app(argc, argv); QStringList arguments = app.arguments(); //init load file or folder list QStringList fileList; //liteide --select-env [system|win32|cross-linux64|...] select init environment id //liteide --reset-setting reset current setting //liteide --local-setting force user local setting //liteide --user-setting force use user setting QString flagSelectEnv = "--select-env"; QString argSelectEnv; QString flagResetSetting = "--reset-setting"; QString flagLocalSetting = "--local-setting"; QString flagUserSetting = "--user-setting"; bool argResetSetting = false; bool argLocalSetting = false; bool argUserSetting = false; for(int i = 1; i < arguments.size(); i++) { QString arg = arguments[i]; if (arg.startsWith("-")) { if (arg.indexOf(flagSelectEnv+"=") == 0) { argSelectEnv = arg.mid(flagSelectEnv.length()+1); } else if (arg == flagSelectEnv) { i++; if (i < arguments.size()) { argSelectEnv = arguments[i]; } } else if (arg == flagResetSetting) { argResetSetting = true; } else if (arg == flagLocalSetting) { argLocalSetting = true; } else if (arg == flagUserSetting) { argUserSetting = true; } continue; } fileList.append(arg); } //save to global if (!argSelectEnv.isEmpty()) { LiteApp::s_cookie.insert(flagSelectEnv,argSelectEnv); } if (argLocalSetting) { LiteApp::s_cookie.insert(flagLocalSetting,true); } if (argUserSetting) { LiteApp::s_cookie.insert(flagUserSetting,true); } #if QT_VERSION >= 0x050100 app.setAttribute(Qt::AA_UseHighDpiPixmaps); #endif //QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); QTranslator translator; QTranslator qtTranslator; QString resPath = LiteApp::getResoucePath(); QString locale = QLocale::system().name(); QString qss; QSettings global(resPath+"/liteapp/config/global.ini",QSettings::IniFormat); bool storeLocal = global.value(LITEIDE_STORELOCAL,false).toBool(); if (argUserSetting) { storeLocal = false; } else if (argLocalSetting) { storeLocal = true; } if (storeLocal) { QSettings settings(resPath+"/liteapp/config/liteide.ini", QSettings::IniFormat); if (argResetSetting) { settings.clear(); } locale = settings.value(LITEAPP_LANGUAGE,locale).toString(); qss = settings.value(LITEAPP_QSS,"default.qss").toString(); } else { QSettings settings(QSettings::IniFormat,QSettings::UserScope,"liteide","liteide"); if (argResetSetting) { settings.clear(); } locale = settings.value(LITEAPP_LANGUAGE,locale).toString(); qss = settings.value(LITEAPP_QSS,"default.qss").toString(); } if (!locale.isEmpty()) { const QString &liteideTrPath = resPath+"/translations"; if (translator.load(QLatin1String("liteide_") + locale, liteideTrPath)) { const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); const QString &qtTrFile = QLatin1String("qt_") + locale; // Binary installer puts Qt tr files into creatorTrPath app.installTranslator(&translator); if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, liteideTrPath)) { app.installTranslator(&qtTranslator); } app.setProperty("liteide_locale", locale); } } if (!qss.isEmpty()) { QFile f(resPath+"/liteapp/qss/"+qss); if (f.open(QFile::ReadOnly)) { QString styleSheet = QLatin1String(f.readAll()); app.setStyleSheet(styleSheet); } } IApplication *liteApp = LiteApp::NewApplication("default",0); foreach(QString file, fileList) { QFileInfo f(file); if (f.isFile()) { liteApp->fileManager()->openEditor(file); } else if (f.isDir()) { liteApp->fileManager()->addFolderList(file); } }
int main(int argc, wchar_t* argv[]) { static_assert(sizeof(void*) == 4, "64-bit code generation is not supported."); SetUnhandledExceptionFilter(UserUnhandledExceptionFilter); std::wcout << L"Type \"q\" to close application." << std::endl; // Set debug mode. #ifdef _DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); #endif // Increase process priotity. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); // Install structured exception handler. caspar::win32_exception::install_handler(); caspar::log::set_log_level(L"debug"); // Increase time precision. This will increase accuracy of function like Sleep(1) from 10 ms to 1 ms. struct inc_prec { inc_prec(){timeBeginPeriod(1);} ~inc_prec(){timeEndPeriod(1);} } inc_prec; // Install unstructured exception handlers into all tbb threads. struct tbb_thread_installer : public tbb::task_scheduler_observer { tbb_thread_installer(){observe(true);} void on_scheduler_entry(bool is_worker) { //caspar::detail::SetThreadName(GetCurrentThreadId(), "tbb-worker-thread"); caspar::win32_exception::install_handler(); } } tbb_thread_installer; tbb::task_scheduler_init init; try { { // Configure environment properties from configuration. caspar::env::configure("casparcg.config"); #ifdef _DEBUG if(caspar::env::properties().get("configuration.debugging.remote", false)) MessageBox(nullptr, TEXT("Now is the time to connect for remote debugging..."), TEXT("Debug"), MB_OK | MB_TOPMOST); #endif // Start logging to file. caspar::log::add_file_sink(caspar::env::log_folder()); std::wcout << L"Logging [info] or higher severity to " << caspar::env::log_folder() << std::endl << std::endl; // Setup console window. setup_console_window(); // Print environment information. print_info(); // Create server object which initializes channels, protocols and controllers. caspar::server caspar_server; // Create a amcp parser for console commands. caspar::protocol::amcp::AMCPProtocolStrategy amcp(caspar_server.get_channels()); // Create a dummy client which prints amcp responses to console. auto console_client = std::make_shared<caspar::IO::ConsoleClientInfo>(); boost::thread input_thread([&] { while(shutdown_event == application_state::running) { std::wstring wcmd; std::getline(std::wcin, wcmd); // TODO: It's blocking... try { if(wcmd == L"exit" || wcmd == L"q") { shutdown_event = application_state::pause_and_shutdown; shutdown_cond.notify_all(); return; } // This is just dummy code for testing. if(wcmd.substr(0, 1) == L"1") wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1"; else if(wcmd.substr(0, 1) == L"2") wcmd = L"MIXER 1-0 VIDEO IS_KEY 1"; else if(wcmd.substr(0, 1) == L"3") wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1"; else if(wcmd.substr(0, 1) == L"4") wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP"; else if(wcmd.substr(0, 1) == L"5") { auto file = wcmd.substr(2, wcmd.length()-1); wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" L"PLAY 1-2 " + file + L" LOOP\r\n" L"PLAY 1-3 " + file + L" LOOP\r\n" L"PLAY 2-1 " + file + L" LOOP\r\n" L"PLAY 2-2 " + file + L" LOOP\r\n" L"PLAY 2-3 " + file + L" LOOP\r\n"; } else if(wcmd.substr(0, 1) == L"X") { int num = 0; std::wstring file; try { num = boost::lexical_cast<int>(wcmd.substr(1, 2)); file = wcmd.substr(4, wcmd.length()-1); } catch(...) { num = boost::lexical_cast<int>(wcmd.substr(1, 1)); file = wcmd.substr(3, wcmd.length()-1); } int n = 0; int num2 = num; while(num2 > 0) { num2 >>= 1; n++; } wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n); for(int i = 1; i <= num; ++i) wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP"; } wcmd += L"\r\n"; amcp.Parse(wcmd.c_str(), wcmd.length(), console_client); } catch(...) { CASPAR_LOG_CURRENT_EXCEPTION(); } } });
int WINAPI WinMain(HINSTANCE inst, HINSTANCE, LPTSTR cmdline, int cmdshow) { MSG msg; BOOL ret; HWND sheet, active; HACCEL accelerators; #ifdef MSVC_MEMLEAK_CHECK _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); //check for memory leaks #endif // These two methods are not the same GetModuleFileName(NULL, global::exedir, MAX_PATH); // works PathRemoveFileSpec(global::exedir); //GetCurrentDirectory(_MAX_PATH, global::exedir); // doesn't work //basic initializations aokts = inst; propdata.p = scen.players; //start pointing to first member ret = setts.load(); if (*setts.logname) { char logpath[_MAX_PATH]; //GetCurrentDirectory(_MAX_PATH, logpath); strcpy(logpath, global::exedir); strcat(logpath, "\\"); strcat(logpath, setts.logname); freopen(logpath, "w", stdout); printf_log("Opened log file %s.\n", logpath); } printf_log("TS Path: %s\n", global::exedir); // Hint about whether to open as AOC or SGWB if (setts.recent_first) { scen.game = (Game)setts.recent_first->game; printf_log("Last game was %s.\n", gameName(scen.game)); } //process any compress/decompress requests if ((*cmdline == '/' || *cmdline == '-') && ProcessCmdline(cmdline)) return 0; //read genie data try { switch (scen.game) { case AOK: case AOC: case AOHD: case AOF: esdata.load(datapath_aok); break; case SWGB: case SWGBCC: esdata.load(datapath_swgb); break; default: esdata.load(datapath_aok); } } catch (std::exception& ex) { printf_log("Could not load data: %s\n", ex.what()); MessageBox(NULL, "Could not read Genie Data from data.xml. Terminating...", "Error", MB_ICONERROR); return 0; } //create the property sheet & init misc data InitCommonControls(); sheet = MakeSheet(inst); propdata.tformat = RegisterClipboardFormat("AOKTS Trigger"); propdata.ecformat = RegisterClipboardFormat("AOKTS EC"); propdata.mcformat = RegisterClipboardFormat("AOKTS Mapcopy"); accelerators = LoadAccelerators(inst, (LPCTSTR)IDA_MAIN); //checked for err later //give the sheet its own DialogProc pproc = (DLGPROC)SetWindowLong(sheet, DWL_DLGPROC, (LONG)&MainDlgProc); //check for errors down here, after we create the sheet if (!accelerators) { MessageBox(sheet, "Keyboard Accelerators failed to load. Keyboard shortcuts will not be available.", "Warning", MB_ICONWARNING); } if (!propdata.tformat | !propdata.ecformat) { MessageBox(sheet, "Could not register clipboard format. Clipboard operations will not function.", "Warning", MB_ICONWARNING); } //if (!ret) // MessageBox(sheet, warnNoAOEII, "Warning", MB_ICONWARNING); //open mapview window propdata.mapview = MakeMapView(sheet, cmdshow || SW_MAXIMIZE); //check for, then open the scenario specified in command string if (*cmdline != '\0') { if (*cmdline == '"') { cmdline++; //increment past first doublequote *strrchr(cmdline, '"') = '\0'; //find last " and replace it } strcpy(setts.ScenPath, cmdline); printf_log("cmdline scenpath: %s\n", setts.ScenPath); FileOpen(sheet, false, -1); } //the message loop while (ret = GetMessage(&msg, NULL, 0, 0)) { if (ret < 0) //did GetMessage() fail? { MessageBox(sheet, "Unable to retrieve messages from queue. Click OK to terminate.", "AOKTS Fatal Error", MB_ICONERROR); break; } // Give first dibs to keyboard accelerators and the propsheet. if (TranslateAccelerator(sheet, accelerators, &msg) || PropSheet_IsDialogMessage(sheet, &msg)) continue; // Usually active is the sheet. If it's not, it's a modeless dialog and // it should get a crack, too. if ((active = GetActiveWindow()) != sheet && IsDialogMessage(active, &msg)) continue; // If we get here, it's just a normal message, so Translate and // Dispatch. TranslateMessage(&msg); DispatchMessage(&msg); } //cleanup if (setts.DelTempOnExit) DeleteFile(setts.TempPath); fclose(stdout); return msg.wParam; }
int APIENTRY WINMAIN(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LLMemType mt1(LLMemType::MTYPE_STARTUP); const S32 MAX_HEAPS = 255; DWORD heap_enable_lfh_error[MAX_HEAPS]; S32 num_heaps = 0; #if WINDOWS_CRT_MEM_CHECKS && !INCLUDE_VLD _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // dump memory leaks on exit #elif 1 // Experimental - enable the low fragmentation heap // This results in a 2-3x improvement in opening a new Inventory window (which uses a large numebr of allocations) // Note: This won't work when running from the debugger unless the _NO_DEBUG_HEAP environment variable is set to 1 _CrtSetDbgFlag(0); // default, just making explicit ULONG ulEnableLFH = 2; HANDLE* hHeaps = new HANDLE[MAX_HEAPS]; num_heaps = GetProcessHeaps(MAX_HEAPS, hHeaps); for(S32 i = 0; i < num_heaps; i++) { bool success = HeapSetInformation(hHeaps[i], HeapCompatibilityInformation, &ulEnableLFH, sizeof(ulEnableLFH)); if (success) heap_enable_lfh_error[i] = 0; else heap_enable_lfh_error[i] = GetLastError(); } #endif // *FIX: global gIconResource = MAKEINTRESOURCE(IDI_LL_ICON); LLAppViewerWin32* viewer_app_ptr = new LLAppViewerWin32(lpCmdLine); LLWinDebug::initExceptionHandler(viewer_windows_exception_handler); viewer_app_ptr->setErrorHandler(LLAppViewer::handleViewerCrash); // Set a debug info flag to indicate if multiple instances are running. bool found_other_instance = !create_app_mutex(); gDebugInfo["FoundOtherInstanceAtStartup"] = LLSD::Boolean(found_other_instance); // do early parsing of command line to check for --portable or --appname parameter { std::string cmdline(lpCmdLine); std::string::size_type pos; pos = cmdline.find("--portable"); if(pos != std::string::npos) { gDebugInfo["EmeraldPortableMode"] = LLSD::Boolean(true); } } bool ok = viewer_app_ptr->init(); if(!ok) { llwarns << "Application init failed." << llendl; return -1; } // Have to wait until after logging is initialized to display LFH info if (num_heaps > 0) { llinfos << "Attempted to enable LFH for " << num_heaps << " heaps." << llendl; for(S32 i = 0; i < num_heaps; i++) { if (heap_enable_lfh_error[i]) { llinfos << " Failed to enable LFH for heap: " << i << " Error: " << heap_enable_lfh_error[i] << llendl; } } } // Run the application main loop if(!LLApp::isQuitting()) { viewer_app_ptr->mainLoop(); } if (!LLApp::isError()) { // // We don't want to do cleanup here if the error handler got called - // the assumption is that the error handler is responsible for doing // app cleanup if there was a problem. // #if WINDOWS_CRT_MEM_CHECKS llinfos << "CRT Checking memory:" << llendflush; if (!_CrtCheckMemory()) { llwarns << "_CrtCheckMemory() failed at prior to cleanup!" << llendflush; } else { llinfos << " No corruption detected." << llendflush; } #endif viewer_app_ptr->cleanup(); #if WINDOWS_CRT_MEM_CHECKS llinfos << "CRT Checking memory:" << llendflush; if (!_CrtCheckMemory()) { llwarns << "_CrtCheckMemory() failed after cleanup!" << llendflush; } else { llinfos << " No corruption detected." << llendflush; } #endif } delete viewer_app_ptr; viewer_app_ptr = NULL; //start updater if(LLAppViewer::sUpdaterInfo) { _spawnl(_P_NOWAIT, LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), LLAppViewer::sUpdaterInfo->mParams.str().c_str(), NULL); delete LLAppViewer::sUpdaterInfo ; LLAppViewer::sUpdaterInfo = NULL ; } return 0; }
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE hi, LPSTR lpCmdLine, INT iMain) { // memory leaks detection _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // NACTI DLL MODULY Z ADRESARE VE KTEREM JE EXE char szExePath[MAX_PATH]; GetModuleFileName(hInst, szExePath, MAX_PATH); for(int i=(int)strlen(szExePath); i > 0; i--) { if (szExePath[i]=='/' || szExePath[i]=='\\') { szExePath[i]=0; break; } } // --------------------------------- I_Initialize(szExePath); // initialize dll module system // --------------------------------- // get game module name char szGame[64]="main"; for(unsigned int i=0;i<=strlen(lpCmdLine);i++) { if (!strnicmp(&lpCmdLine[i], "-game ", 6)) { for(unsigned int ii=i+6;ii<=strlen(lpCmdLine);ii++) { if (lpCmdLine[i]==' ' || lpCmdLine[i]==0) { strncpy(szGame, &lpCmdLine[i+6], ii-i); break; } } break; } } strcat(szGame, ".game"); // Load game module // --------------------------------- I_LoadNewModule(szGame); // load game module IP3DGame *pGame = (IP3DGame *)I_GetClass(IP3DGAME_GAME); if (!pGame) { MessageBox(0, "Can't load main game singleton!", "CAN'T LAUNCH GAME!", MB_ICONSTOP | MB_SYSTEMMODAL); I_Shutdown(); // shutdown module dll system return -1; } // Run game // --------------------------------- DWORD nMinPlayed=0; if (pGame->InitGame(lpCmdLine, false)) { DWORD tickStart = GetTickCount(); pGame->RunGame(); nMinPlayed = (GetTickCount()-tickStart)/60000; } // post-run actions :-P if (!IsDebuggerPresent()) { // get game information GameInfo game; pGame->GetGameInfo(game); // send statistics / show browser window when website is available if (game.szWebsite && game.szWebsite[0]!=0) { // create url char url[512]; sprintf(url, "%s?game=%s&version=%d.%d.%d.%d&time=%d", game.szWebsite, game.szName, game.szVersion[0], game.szVersion[1], game.szVersion[2], game.szVersion[3], nMinPlayed); // send statistics if (game.bSendStats) { HINTERNET hInet = InternetOpen("P3DStats", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET hFile = InternetOpenUrl(hInet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0); if (hInet && hFile) { DWORD size; char dummy[16]; if (InternetReadFile(hFile, dummy, 8, &size)) InternetCloseHandle(hFile); InternetCloseHandle(hInet); } } // open browser window with game information if (game.bOpenBrowser) { ShellExecute(0, "open", url, "", "", 1); } } } // Shutdown // ---------------------------------- I_Shutdown(); // shutdown module dll system return 0; }
// Windows メイン int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #ifdef _DEBUG int newFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) ; newFlag |= _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF ; // | _CRTDBG_DELAY_FREE_MEM_DF ; _CrtSetDbgFlag(newFlag) ; _ASSERTE(_CrtCheckMemory()) ; #endif // スクリーンセーバモードで起動中のものがあれば // その場で終了 HWND win ; win = FindWindow("GLUT", "glclock screen saver") ; if (win) return EXIT_FAILURE ; hInstanceGlClock = hInstance ; // 実行ファイルパスを \Windows\System\glclock.ini ファイルに保存 String glclockExePath, glclockIniPath ; glclockExePath = String(__argv[0]) ; char buf[MAX_PATH + 1] ; int len ; len = GetSystemDirectory(buf, MAX_PATH) ; if (len) glclockIniPath = String(buf) + '\\' + GLCLOCK_INI ; FILE *fpGlClockIni = fopen(glclockIniPath, "w") ; if (fpGlClockIni) { // fprintf(fpGlClockIni, "%s\n", (char *)glclockExePath) ; fprintf(fpGlClockIni, glclockExePath) ; fclose(fpGlClockIni) ; } int ret ; #ifndef GLCLOCK_DLL_EXPORT // dll を使わない場合 ret = glclock(__argc, __argv) ; if (ret) ret = FALSE ; else ret = TRUE ; #else // glclock.dll に明示的にリンクする使用する場合 // glclock.dll から glclock() をリンク // 関数アドレスをゲットできた場合 glclock コール HINSTANCE hLib_glclock = NULL ; hLib_glclock = LoadLibrary(_T(GLCLOCK_DLL)) ; if (hLib_glclock) { // DLL ロードに成功したら // glclock() の エントリポイントを取得 PFNGLCLOCKARGPROC pglclock_arg ; pglclock_arg = (PFNGLCLOCKARGPROC)GetProcAddress(hLib_glclock, _T("_glclock_arg@8")) ; if (!pglclock_arg) { MessageBox(NULL, _T("Failed to get glclock_arg entry point"), _T("GetProcAddress Error"), MB_OK | MB_ICONSTOP) ; ret = EXIT_FAILURE ; } else { #define glclock_arg (*pglclock_arg) ret = glclock_arg(__argc, __argv) ; #undef glclock_arg } // DLL を開放 if (hLib_glclock) FreeLibrary(hLib_glclock) ; if (ret) ret = FALSE ; else ret = TRUE ; } else { // DLL のロードに失敗 MessageBox(NULL, _T("Failed to load glclock.dll"), _T("LoadLibrary Error"), MB_OK | MB_ICONSTOP) ; ret = FALSE ; } #endif // #ifndef GLCLOCK_DLL_EXPORT ... #else return ret ; }
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); int n = 0; _CrtSetBreakAlloc(n); #endif g_hInst = hInstance; // Store instance handle in our global variable LARGE_INTEGER nFrameStartTime; nFrameStartTime.QuadPart = 0; // Initialize global strings LoadString(g_hInst, IDS_APP_TITLE, g_szTitle, MAX_LOADSTRING); LoadString(g_hInst, IDC_NEONBTL, g_szWindowClass, MAX_LOADSTRING); MainWindow_RegisterClass(); // Perform application initialization if (! InitInstance(hInstance, nCmdShow)) return FALSE; HACCEL hAccelTable = ::LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_NEONBTL)); LARGE_INTEGER nPerformanceFrequency; ::QueryPerformanceFrequency(&nPerformanceFrequency); // Main message loop MSG msg; while (true) { ::QueryPerformanceCounter(&nFrameStartTime); if (!g_okEmulatorRunning) ::Sleep(20); else { if (Emulator_IsBreakpoint()) Emulator_Stop(); else { if (Emulator_SystemFrame()) { ScreenView_RedrawScreen(); //MemoryMapView_RedrawMap(); } } } // Process all queue while (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )) { if (msg.message == WM_QUIT) goto endprog; if (::TranslateAccelerator(g_hwnd, hAccelTable, &msg)) continue; ::TranslateMessage(&msg); ::DispatchMessage(&msg); } #if 1 if (g_okEmulatorRunning /*&& Settings_GetRealSpeed()*/) { // Slow down to 25 frames per second LARGE_INTEGER nFrameFinishTime; // Frame start time ::QueryPerformanceCounter(&nFrameFinishTime); LONGLONG nTimeElapsed = (nFrameFinishTime.QuadPart - nFrameStartTime.QuadPart) * 1000 / nPerformanceFrequency.QuadPart; if (nTimeElapsed > 0 && nTimeElapsed < 20) // 1000 millisec / 25 = 40 millisec { LONG nTimeToSleep = (LONG)(20 - nTimeElapsed); ::Sleep((DWORD) nTimeToSleep / 2); ScreenView_ScanKeyboard(); ::Sleep((DWORD) nTimeToSleep / 2); } } #endif } endprog: DoneInstance(); #ifdef _DEBUG if (_CrtDumpMemoryLeaks()) ::MessageBeep(MB_ICONEXCLAMATION); #endif return (int) msg.wParam; }
int WINAPI WinMain_(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { // make vnc last service to stop SetProcessShutdownParameters(0x100,false); // handle dpi on aero HMODULE hUser32 = LoadLibrary(_T("user32.dll")); typedef BOOL (*SetProcessDPIAwareFunc)(); SetProcessDPIAwareFunc setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware"); if (setDPIAware) setDPIAware(); FreeLibrary(hUser32); #ifdef IPP InitIpp(); #endif #ifdef CRASHRPT Install(NULL, _T("*****@*****.**"), _T("")); #endif bool Injected_autoreconnect=false; SPECIAL_SC_EXIT=false; SPECIAL_SC_PROMPT=false; SetOSVersion(); setbuf(stderr, 0); // [v1.0.2-jp1 fix] Load resouce from dll hInstResDLL = NULL; //limit the vnclang.dll searchpath to avoid char szCurrentDir[MAX_PATH]; char szCurrentDir_vnclangdll[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; } strcpy (szCurrentDir_vnclangdll,szCurrentDir); strcat (szCurrentDir_vnclangdll,"\\"); strcat (szCurrentDir_vnclangdll,"vnclang_server.dll"); hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll); if (hInstResDLL == NULL) { hInstResDLL = hInstance; } // RegisterLinkLabel(hInstResDLL); //Load all messages from ressource file Load_Localization(hInstResDLL) ; char WORKDIR[MAX_PATH]; if (GetModuleFileName(NULL, WORKDIR, MAX_PATH)) { char* p = strrchr(WORKDIR, '\\'); if (p == NULL) return 0; *p = '\0'; } char progname[MAX_PATH]; strncpy(progname, WORKDIR, sizeof progname); progname[MAX_PATH - 1] = 0; //strcat(WORKDIR,"\\"); //strcat(WORKDIR,"WinVNC.log"); vnclog.SetFile(); // vnclog.SetMode(2); // vnclog.SetLevel(10); #ifdef _DEBUG { // Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // Save the application instance and main thread id hAppInstance = hInstance; mainthreadId = GetCurrentThreadId(); // Initialise the VSocket system VSocketSystem socksys; if (!socksys.Initialised()) { MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK); return 0; } // look up the current service name in the registry. GetServiceName(progname, service_name); // Make the command-line lowercase and parse it size_t i; for (i = 0; i < strlen(szCmdLine); i++) { szCmdLine[i] = tolower(szCmdLine[i]); } BOOL argfound = FALSE; for (i = 0; i < strlen(szCmdLine); i++) { if (szCmdLine[i] <= ' ') continue; argfound = TRUE; if (strncmp(&szCmdLine[i], winvncSettingshelper, strlen(winvncSettingshelper)) == 0) { Sleep(3000); char mycommand[MAX_PATH]; i+=strlen(winvncSettingshelper); strcpy( mycommand, &(szCmdLine[i+1])); Set_settings_as_admin(mycommand); return 0; } if (strncmp(&szCmdLine[i], winvncStopserviceHelper, strlen(winvncStopserviceHelper)) == 0) { Sleep(3000); Set_stop_service_as_admin(); return 0; } if (strncmp(&szCmdLine[i], winvncKill, strlen(winvncKill)) == 0) { static HANDLE hShutdownEventTmp; hShutdownEventTmp = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Global\\SessionEventUltra"); SetEvent(hShutdownEventTmp); CloseHandle(hShutdownEventTmp); //adzm 2010-02-10 - Finds the appropriate VNC window for any process. Sends this message to all of them! HWND hservwnd = NULL; do { if (hservwnd!=NULL) { PostMessage(hservwnd, WM_COMMAND, 40002, 0); PostMessage(hservwnd, WM_CLOSE, 0, 0); } hservwnd = FindWinVNCWindow(false); } while (hservwnd!=NULL); return 0; } if (strncmp(&szCmdLine[i], winvncopenhomepage, strlen(winvncopenhomepage)) == 0) { Open_homepage(); return 0; } if (strncmp(&szCmdLine[i], winvncopenforum, strlen(winvncopenforum)) == 0) { Open_forum(); return 0; } if (strncmp(&szCmdLine[i], winvncStartserviceHelper, strlen(winvncStartserviceHelper)) == 0) { Sleep(3000); Set_start_service_as_admin(); return 0; } if (strncmp(&szCmdLine[i], winvncInstallServiceHelper, strlen(winvncInstallServiceHelper)) == 0) { //Sleeps are realy needed, else runas fails... Sleep(3000); Set_install_service_as_admin(); return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallServiceHelper, strlen(winvncUnInstallServiceHelper)) == 0) { Sleep(3000); Set_uninstall_service_as_admin(); return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecadHelper, strlen(winvncSoftwarecadHelper)) == 0) { Sleep(3000); Enable_softwareCAD_elevated(); return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecadHelper, strlen(winvncdelSoftwarecadHelper)) == 0) { Sleep(3000); delete_softwareCAD_elevated(); return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafeHelper, strlen(winvncRebootSafeHelper)) == 0) { Sleep(3000); Reboot_in_safemode_elevated(); return 0; } if (strncmp(&szCmdLine[i], winvncRebootForceHelper, strlen(winvncRebootForceHelper)) == 0) { Sleep(3000); Reboot_with_force_reboot_elevated(); return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditorHelper, strlen(winvncSecurityEditorHelper)) == 0) { Sleep(3000); winvncSecurityEditorHelper_as_admin(); return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditor, strlen(winvncSecurityEditor)) == 0) { typedef void (*vncEditSecurityFn) (HWND hwnd, HINSTANCE hInstance); vncEditSecurityFn vncEditSecurity = 0; char szCurrentDir[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; strcat (szCurrentDir,"\\authSSP.dll"); } HMODULE hModule = LoadLibrary(szCurrentDir); if (hModule) { vncEditSecurity = (vncEditSecurityFn) GetProcAddress(hModule, "vncEditSecurity"); HRESULT hr = CoInitialize(NULL); vncEditSecurity(NULL, hAppInstance); CoUninitialize(); FreeLibrary(hModule); } return 0; } if (strncmp(&szCmdLine[i], winvncSettings, strlen(winvncSettings)) == 0) { char mycommand[MAX_PATH]; i+=strlen(winvncSettings); strcpy( mycommand, &(szCmdLine[i+1])); Real_settings(mycommand); return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecad, strlen(winvncSoftwarecad)) == 0) { Enable_softwareCAD(); return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecad, strlen(winvncdelSoftwarecad)) == 0) { delete_softwareCAD(); return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafe, strlen(winvncRebootSafe)) == 0) { Reboot_in_safemode(); return 0; } if (strncmp(&szCmdLine[i], winvncRebootForce, strlen(winvncRebootForce)) == 0) { Reboot_with_force_reboot(); return 0; } if (strncmp(&szCmdLine[i], winvncStopservice, strlen(winvncStopservice)) == 0) { Real_stop_service(); return 0; } if (strncmp(&szCmdLine[i], winvncStartservice, strlen(winvncStartservice)) == 0) { Real_start_service(); return 0; } if (strncmp(&szCmdLine[i], winvncInstallService, strlen(winvncInstallService)) == 0) { // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } // if a service name is supplied, and it differs except in case from // the default, use the supplied service name instead if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } install_service(); Sleep(2000); char command[MAX_PATH + 32]; // 29 January 2008 jdp _snprintf(command, sizeof command, "net start \"%s\"", service_name); WinExec(command,SW_HIDE); return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallService, strlen(winvncUnInstallService)) == 0) { char command[MAX_PATH + 32]; // 29 January 2008 jdp // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } _snprintf(command, sizeof command, "net stop \"%s\"", service_name); WinExec(command,SW_HIDE); uninstall_service(); return 0; } if (strncmp(&szCmdLine[i], winvncRunService, strlen(winvncRunService)) == 0) { //Run as service if (!Myinit(hInstance)) return 0; fRunningFromExternalService = true; vncService::RunningFromExternalService(true); return WinVNCAppMain(); } if (strncmp(&szCmdLine[i], winvncStartService, strlen(winvncStartService)) == 0) { start_service(szCmdLine); return 0; } if (strncmp(&szCmdLine[i], winvncRunAsUserApp, strlen(winvncRunAsUserApp)) == 0) { // WinVNC is being run as a user-level program if (!Myinit(hInstance)) return 0; return WinVNCAppMain(); } if (strncmp(&szCmdLine[i], winvncSCexit, strlen(winvncSCexit)) == 0) { SPECIAL_SC_EXIT=true; i+=strlen(winvncSCexit); continue; } if (strncmp(&szCmdLine[i], winvncSCprompt, strlen(winvncSCprompt)) == 0) { SPECIAL_SC_PROMPT=true; i+=strlen(winvncSCprompt); continue; } if (strncmp(&szCmdLine[i], winvncmulti, strlen(winvncmulti)) == 0) { multi=true; i+=strlen(winvncmulti); continue; } if (strncmp(&szCmdLine[i], winvnchttp, strlen(winvnchttp)) == 0) { G_HTTP=true; i+=strlen(winvnchttp); continue; } if (strncmp(&szCmdLine[i], winvncStopReconnect, strlen(winvncStopReconnect)) == 0) { i+=strlen(winvncStopReconnect); vncService::PostAddStopConnectClientAll(); continue; } if (strncmp(&szCmdLine[i], winvncAutoReconnect, strlen(winvncAutoReconnect)) == 0) { // Note that this "autoreconnect" param MUST be BEFORE the "connect" one // on the command line ! // wa@2005 -- added support for the AutoReconnectId i+=strlen(winvncAutoReconnect); Injected_autoreconnect=true; int start, end; char* pszId = NULL; start = i; // skip any spaces and grab the parameter while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; if ( strncmp( &szCmdLine[start], winvncAutoReconnectId, strlen(winvncAutoReconnectId) ) == 0 ) { end = start; while (szCmdLine[end] > ' ') end++; pszId = new char[ end - start + 1 ]; if (pszId != 0) { strncpy( pszId, &(szCmdLine[start]), end - start ); pszId[ end - start ] = 0; pszId = _strupr( pszId ); } //multiple spaces between autoreconnect and id i = end; }// end of condition we found the ID: parameter // NOTE: id must be NULL or the ID:???? (pointer will get deleted when message is processed) // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started if (!vncService::PostAddAutoConnectClient( pszId )) { PostAddAutoConnectClient_bool=true; if (pszId==NULL) { PostAddAutoConnectClient_bool_null=true; PostAddAutoConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete [] pszId; } } continue; } if ( strncmp( &szCmdLine[i], winvncReconnectId, strlen(winvncReconnectId) ) == 0 ) { i+=strlen("-"); int start, end; char* pszId = NULL; start = i; end = start; while (szCmdLine[end] > ' ') end++; pszId = new char[ end - start + 1 ]; if (pszId != 0) { strncpy( pszId, &(szCmdLine[start]), end - start ); pszId[ end - start ] = 0; pszId = _strupr( pszId ); } i = end; if (!vncService::PostAddConnectClient( pszId )) { PostAddConnectClient_bool=true; if (pszId==NULL) { PostAddConnectClient_bool_null=true; PostAddConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete [] pszId; } } continue; } if (strncmp(&szCmdLine[i], winvncConnect, strlen(winvncConnect)) == 0) { if (!Injected_autoreconnect) { vncService::PostAddStopConnectClient(); } // Add a new client to an existing copy of winvnc i+=strlen(winvncConnect); // First, we have to parse the command line to get the filename to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { char *name = new char[end-start+1]; if (name != 0) { strncpy(name, &(szCmdLine[start]), end-start); name[end-start] = 0; int port = INCOMING_PORT_OFFSET; char *portp = strchr(name, ':'); if (portp) { *portp++ = '\0'; if (*portp == ':') { port = atoi(++portp); // Port number after "::" } else { port = atoi(portp); // Display number after ":" } } vnclog.Print(LL_STATE, VNCLOG("test... %s %d\n"),name,port); strcpy_s(dnsname,name); VCard32 address = VSocket::Resolve(name); delete [] name; if (address != 0) { // Post the IP address to the server // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient III \n")); if (!vncService::PostAddNewClientInit(address, port)) { PostAddNewClient_bool=true; port_int=port; address_vcard=address; } } else { //ask for host,port PostAddNewClient_bool=true; port_int=0; address_vcard=0; Sleep(2000); //Beep(200,1000); return 0; } } i=end; continue; } else { // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } } continue; } //adzm 2009-06-20 if (strncmp(&szCmdLine[i], winvncRepeater, strlen(winvncRepeater)) == 0) { // set the default repeater host i+=strlen(winvncRepeater); // First, we have to parse the command line to get the host to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { if (g_szRepeaterHost) { delete[] g_szRepeaterHost; g_szRepeaterHost = NULL; } g_szRepeaterHost = new char[end-start+1]; if (g_szRepeaterHost != 0) { strncpy(g_szRepeaterHost, &(szCmdLine[start]), end-start); g_szRepeaterHost[end-start] = 0; // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient I\n")); if (!vncService::PostAddNewRepeaterClient()) { PostAddNewRepeaterClient_bool=true; port_int=0; address_vcard=0; } } i=end; continue; } else { /* // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } */ } continue; } // Either the user gave the -help option or there is something odd on the cmd-line! // Show the usage dialog MessageBoxSecure(NULL, winvncUsageText, sz_ID_WINVNC_USAGE, MB_OK | MB_ICONINFORMATION); break; }; // If no arguments were given then just run if (!argfound) { if (!Myinit(hInstance)) return 0; return WinVNCAppMain(); } return 0; }
////////////////////////////////////////////////////////////////////////////// // CDemoApp initialization BOOL CDemoApp::InitInstance() { // <dave> dump memory leaks #ifdef _DEBUG _CrtDumpMemoryLeaks(); _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Standard initialization #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif LoadStdProfileSettings(9); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate( IDR_DEMOTYPE, RUNTIME_CLASS(CDemoDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CDemoView)); demoTemplate = pDocTemplate; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE; m_pMainWnd = pMainFrame; // This code replaces the MFC created menus with // the Ownerdrawn versions pDocTemplate->m_hMenuShared=pMainFrame->NewMenu(); pMainFrame->m_hMenuDefault=pMainFrame->NewDefaultMenu(); // This simulates a window being opened if you don't have // a default window displayed at startup pMainFrame->OnUpdateFrameMenu(pMainFrame->m_hMenuDefault); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; // Alter behaviour to not open window immediately cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; #ifdef VATI_EXTENSIONS // init m_text by a temporary CxImage CxImage *ima = new CxImage; ima->InitTextInfo( &m_text ); delete ima; //recall last used font data for Text tool sprintf( m_text.lfont.lfFaceName, GetProfileString ( "TextTool", "lfFaceName", "Arial") ); m_text.lfont.lfCharSet = GetProfileInt ( "TextTool", "lfCharSet", EASTEUROPE_CHARSET ) ; m_text.lfont.lfWeight = GetProfileInt ( "TextTool", "lfWeight", 0 ); m_text.lfont.lfItalic = GetProfileInt ( "TextTool", "lfItalic", 0 ); m_text.lfont.lfUnderline = GetProfileInt ( "TextTool", "lfUnderline", 0 ); m_text.fcolor = GetProfileInt ( "TextTool", "fcolor", RGB( 255,255,160 )); m_text.bcolor = GetProfileInt ( "TextTool", "bcolor", RGB( 32, 96, 0 )); m_text.opaque = GetProfileInt ( "TextTool", "opaque", 1); m_text.b_opacity = (float)(GetProfileInt( "TextTool", "opacity", 0 ))/(float)100.; m_text.b_round = GetProfileInt ( "TextTool", "roundradius", 25 ); m_optJpegQuality = GetProfileInt("Options","JpegQuality",90); // recall if main window was maximized on last exit if ( GetProfileInt ( "Screen", "maximized", 0 )) m_nCmdShow|=SW_MAXIMIZE; #endif; // The main window has been initialized, so show and update it. pMainFrame -> ShowWindow ( m_nCmdShow ) ; pMainFrame->UpdateWindow(); // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); // Enable open from command line if (*m_lpCmdLine != 0) OpenDocumentFile(m_lpCmdLine); return TRUE; }
void TR() { #if defined(DEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(0); // too expensive #endif const char *HitFileName = RequiredValueOpt("tr"); const char *OutFileName = RequiredValueOpt("out"); const char *CandFileName = ValueOpt("cand"); const char *strMinTrSpacing = ValueOpt("mintrspacing"); const char *strMaxTrSpacing = ValueOpt("maxtrspacing"); const char *strMinTrLength = ValueOpt("mintrlength"); const char *strMaxTrLength = ValueOpt("minspacingratio"); const char *strMinFam = ValueOpt("minfam"); const char *strMinHitRatio = ValueOpt("minhitratio"); const char *strMinDistPairs = ValueOpt("mindistpairs"); if (0 != strMinTrSpacing) MIN_LENGTH_LINE = atoi(strMinTrSpacing); if (0 != strMaxTrSpacing) MAX_LENGTH_LINE = atoi(strMaxTrSpacing); if (0 != strMinTrLength) MIN_LENGTH_LTR = atoi(strMinTrLength); if (0 != strMaxTrLength) MAX_LENGTH_LTR = atoi(strMaxTrLength); if (0 != strMinFam) MIN_FAM_SIZE = atoi(strMinFam); if (0 != strMinHitRatio) MIN_HIT_LENGTH_RATIO = atoi(strMinHitRatio); if (0 != strMinDistPairs) MIN_DIST_EDGE = atoi(strMinDistPairs); FILE *fHit = OpenStdioFile(HitFileName, FILEIO_MODE_ReadOnly); ProgressStart("Index hits"); GLIX HitGlix; HitGlix.Init(); HitGlix.FromGFFFile(fHit); HitGlix.MakeGlobalToLocalIndex(); ProgressDone(); const int GlobalLength = HitGlix.GetGlobalLength(); IIX IntervalIndex; IntervalIndex.Init(GlobalLength); ProgressStart("Find candidate TRs"); Rewind(fHit); GFFRecord Rec; while (GetNextGFFRecord(fHit, Rec)) { HitData Hit; GFFRecordToHit(HitGlix, Rec, Hit); if (IsCandLTR(Hit)) AddCand(Hit, IntervalIndex); } ProgressDone(); Progress("%d candidates", CandCount); if (0 != CandFileName) { ProgressStart("Write candidates"); FILE *fCand = OpenStdioFile(CandFileName, FILEIO_MODE_WriteOnly); WriteCands(fCand, HitGlix); ProgressDone(); } ProgressStart("Make graph"); Rewind(fHit); while (GetNextGFFRecord(fHit, Rec)) { HitData Hit; GFFRecordToHit(HitGlix, Rec, Hit); FindEdges(Hit, HitGlix, IntervalIndex); } fclose(fHit); fHit = 0; ProgressDone(); Progress("%d edges", (int) Edges.size()); ProgressStart("Find families"); FamList Fams; FindConnectedComponents(Edges, Fams, MIN_FAM_SIZE); ProgressDone(); Progress("%d families", (int) Fams.size()); FILE *fOut = OpenStdioFile(OutFileName, FILEIO_MODE_WriteOnly); WriteOutputFile(fOut, HitGlix, Fams); }
int APIENTRY WINMAIN(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LLMemType mt1(LLMemType::MTYPE_STARTUP); #if WINDOWS_CRT_MEM_CHECKS && !INCLUDE_VLD _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // dump memory leaks on exit #endif // *FIX: global gIconResource = MAKEINTRESOURCE(IDI_LL_ICON); LLAppViewerWin32* viewer_app_ptr = new LLAppViewerWin32(lpCmdLine); LLWinDebug::initExceptionHandler(viewer_windows_exception_handler); viewer_app_ptr->setErrorHandler(LLAppViewer::handleViewerCrash); bool ok = viewer_app_ptr->init(); if(!ok) { llwarns << "Application init failed." << llendl; return -1; } // Run the application main loop if(!LLApp::isQuitting()) { viewer_app_ptr->mainLoop(); } if (!LLApp::isError()) { // // We don't want to do cleanup here if the error handler got called - // the assumption is that the error handler is responsible for doing // app cleanup if there was a problem. // #if WINDOWS_CRT_MEM_CHECKS llinfos << "CRT Checking memory:" << llendflush; if (!_CrtCheckMemory()) { llwarns << "_CrtCheckMemory() failed at prior to cleanup!" << llendflush; } else { llinfos << " No corruption detected." << llendflush; } #endif viewer_app_ptr->cleanup(); #if WINDOWS_CRT_MEM_CHECKS llinfos << "CRT Checking memory:" << llendflush; if (!_CrtCheckMemory()) { llwarns << "_CrtCheckMemory() failed after cleanup!" << llendflush; } else { llinfos << " No corruption detected." << llendflush; } #endif } delete viewer_app_ptr; viewer_app_ptr = NULL; return 0; }
int CRYPTOPP_API main(int argc, char *argv[]) { #ifdef _CRTDBG_LEAK_CHECK_DF // Turn on leak-checking int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tempflag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag( tempflag ); #endif #if defined(__MWERKS__) && defined(macintosh) argc = ccommand(&argv); #endif CRYPTOPP_UNUSED(argc), CRYPTOPP_UNUSED(argv); try { RegisterFactories(); std::string seed = IntToString(time(NULL)); seed.resize(16); s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data()); std::string command, executableName, macFilename; if (argc < 2) command = 'h'; else command = argv[1]; if (command == "g") { char seed[1024], privFilename[128], pubFilename[128]; unsigned int keyLength; cout << "Key length in bits: "; cin >> keyLength; cout << "\nSave private key to file: "; cin >> privFilename; cout << "\nSave public key to file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); GenerateRSAKey(keyLength, privFilename, pubFilename, seed); } else if (command == "rs") RSASignFile(argv[2], argv[3], argv[4]); else if (command == "rv") { bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]); cout << (verified ? "valid signature" : "invalid signature") << endl; } else if (command == "r") { char privFilename[128], pubFilename[128]; char seed[1024], message[1024]; cout << "Private key file: "; cin >> privFilename; cout << "\nPublic key file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); cout << "\nMessage: "; cin.getline(message, 1024); string ciphertext = RSAEncryptString(pubFilename, seed, message); cout << "\nCiphertext: " << ciphertext << endl; string decrypted = RSADecryptString(privFilename, ciphertext.c_str()); cout << "\nDecrypted: " << decrypted << endl; }
int main( int argc, char* argv[] ) { #if defined( MSVC ) && !defined( NDEBUG ) // Under Visual Studio setup memory leak detection _CrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) ); #endif /* defined( MSVC ) && !defined( NDEBUG ) */ printf("Copyright (C) 2006-2009 EVEmu Team. http://evemu.mmoforge.org/\n"); printf("This program is free software; you can redistribute it and/or modify it under\n"); printf("the terms of the GNU Lesser General Public License as published by the Free \n"); printf("Software Foundation; either version 2 of the License, or (at your option) any\n"); printf("later version.\n"); printf("\n"); printf("This program is distributed in the hope that it will be useful, but WITHOUT\n"); printf("ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n"); printf("FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n"); printf("details.\n"); printf("\n"); sLog.Log("main", "EVEmu "EVEMU_VERSION ); sLog.Log("server init", "\n" "\tSupported Client: %s\n" "\tVersion %.2f\n" "\tBuild %d\n" "\tMachoNet %u", EVEProjectVersion, EVEVersionNumber, EVEBuildVersion, MachoNetVersion ); //it is important to do this before doing much of anything, in case they use it. Timer::SetCurrentTime(); // Load server configuration sLog.Log("server init", "Loading server configuration..."); if( !sConfig.ParseFile( CONFIG_FILE ) ) { sLog.Error( "server init", "Loading server configuration '%s' failed.", CONFIG_FILE ); return 1; } // Load server log settings ( will be removed ) if( load_log_settings( sConfig.files.logSettings.c_str() ) ) sLog.Success( "server init", "Log settings loaded from %s", sConfig.files.logSettings.c_str() ); else sLog.Warning( "server init", "Unable to read %s (this file is optional)", sConfig.files.logSettings.c_str() ); // open up the log file if specified ( will be removed ) if( !sConfig.files.log.empty() ) { if( log_open_logfile( sConfig.files.log.c_str() ) ) sLog.Success( "server init", "Opened log file %s", sConfig.files.log.c_str() ); else sLog.Warning( "server init", "Unable to open log file '%s', only logging to the screen now.", sConfig.files.log.c_str() ); } //connect to the database... DBerror err; if( !sDatabase.Open( err, sConfig.database.host.c_str(), sConfig.database.username.c_str(), sConfig.database.password.c_str(), sConfig.database.db.c_str(), sConfig.database.port ) ) { sLog.Error( "server init", "Unable to connect to the database: %s", err.c_str() ); return 1; } _sDgmTypeAttrMgr = new dgmtypeattributemgr(); // needs to be after db init as its using it _sDgmTypeAttrMgr = new dgmtypeattributemgr(); // needs to be after db init as its using it //Start up the TCP server EVETCPServer tcps; char errbuf[ TCPCONN_ERRBUF_SIZE ]; if( tcps.Open( sConfig.net.port, errbuf ) ) { sLog.Success( "server init", "TCP listener started on port %u.", sConfig.net.port ); } else { sLog.Error( "server init", "Failed to start TCP listener on port %u: %s.", sConfig.net.port, errbuf ); return 1; } //make the item factory ItemFactory item_factory( sEntityList ); ContractFactory contract_factory( item_factory ); //now, the service manager... PyServiceMgr services( 888444, sEntityList, item_factory, contract_factory ); //setup the command dispatcher CommandDispatcher command_dispatcher( services ); RegisterAllCommands( command_dispatcher ); /* * Service creation and registration. * */ sLog.Log("server init", "Creating services."); services.RegisterService(new ClientStatsMgr(&services)); services.RegisterService(new AgentMgrService(&services)); services.RegisterService(new MissionMgrService(&services)); services.RegisterService(new AccountService(&services)); services.RegisterService(new UserService(&services)); services.RegisterService(new AlertService(&services)); services.RegisterService(new AuthService(&services)); services.RegisterService(new BillMgrService(&services)); services.RegisterService(new BookmarkService(&services)); services.RegisterService(new CertificateMgrService(&services)); services.RegisterService(new CharacterService(&services)); services.RegisterService(new CharMgrService(&services)); services.RegisterService(new ConfigService(&services)); services.RegisterService(new LanguageService(&services)); services.RegisterService(new CorpMgrService(&services)); services.RegisterService(new CorpStationMgrService(&services)); services.RegisterService(new CorporationService(&services)); services.RegisterService(new CorpRegistryService(&services)); services.RegisterService(new LPService(&services)); services.RegisterService(new DogmaIMService(&services)); services.RegisterService(new InvBrokerService(&services)); services.RegisterService(services.lsc_service = new LSCService(&services, &command_dispatcher)); services.RegisterService(services.cache_service = new ObjCacheService(&services, sConfig.files.cacheDir.c_str())); services.RegisterService(new LookupService(&services)); services.RegisterService(new VoiceMgrService(&services)); services.RegisterService(new ShipService(&services)); services.RegisterService(new InsuranceService(&services)); services.RegisterService(new BeyonceService(&services)); services.RegisterService(new MapService(&services)); services.RegisterService(new OnlineStatusService(&services)); services.RegisterService(new Standing2Service(&services)); services.RegisterService(new WarRegistryService(&services)); services.RegisterService(new FactionWarMgrService(&services)); services.RegisterService(new StationService(&services)); services.RegisterService(new StationSvcService(&services)); services.RegisterService(new JumpCloneService(&services)); services.RegisterService(new KeeperService(&services)); services.RegisterService(new DungeonService(&services)); services.RegisterService(new SkillMgrService(&services)); services.RegisterService(new TutorialService(&services)); services.RegisterService(new PetitionerService(&services)); services.RegisterService(new SlashService(&services, &command_dispatcher)); services.RegisterService(new MarketProxyService(&services)); services.RegisterService(new ContractMgrService(&services, &contract_factory)); services.RegisterService(new ReprocessingService(&services)); services.RegisterService(new FactoryService(&services)); services.RegisterService(new RamProxyService(&services)); services.RegisterService(new PosMgrService(&services)); services.RegisterService(new NetService(&services)); services.RegisterService(new TradeService(&services)); services.RegisterService(new RepairService(&services)); sLog.Log("server init", "Priming cached objects."); services.cache_service->PrimeCache(); sLog.Log("server init", "finished priming"); services.serviceDB().SetServerOnlineStatus(true); sLog.Log("server init", "Init done."); /* * THE MAIN LOOP * * Everything except IO should happen in this loop, in this thread context. * */ /* program events system */ SetupSignals(); uint32 start; uint32 etime; uint32 last_time = GetTickCount(); EVETCPConnection* tcpc; while( RunLoops == true ) { Timer::SetCurrentTime(); start = GetTickCount(); //check for timeouts in other threads //timeout_manager.CheckTimeouts(); while( ( tcpc = tcps.PopConnection() ) ) { Client* c = new Client( services, &tcpc ); sEntityList.Add( &c ); } sEntityList.Process(); services.Process(); /* UPDATE */ last_time = GetTickCount(); etime = last_time - start; // do the stuff for thread sleeping if( MAIN_LOOP_DELAY > etime ) Sleep( MAIN_LOOP_DELAY - etime ); } sLog.Log("server shutdown", "Main loop stopped" ); tcps.Close(); sLog.Log("server shutdown", "TCP listener stopped." ); services.serviceDB().SetServerOnlineStatus(false); sLog.Log("server shutdown", "Cleanup db cache" ); delete _sDgmTypeAttrMgr; log_close_logfile(); // win crap. //_CrtDumpMemoryLeaks(); return 0; }
/************************************************************************************************ WinMain (...) ************************************************************************************************/ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Always perform a leak check just before app exits. int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); nDbgFlags |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(nDbgFlags); //instantiate log object and log CLog *pLog = CLog::Instance(); pLog->Log("*********************************************************"); pLog->Log("Program starting.................."); pLog->SetDelimiter(':'); pLog->LogDate(); pLog->LogTime(); pLog->Log("************************ *********************************"); pLog->Log ("***********************************************"); pLog->Log("Game Challenge 6"); pLog->LogDate(); pLog->LogTime(); pLog->Log("***********************************************"); Graphics g_con; CAudioManager *pAudio = CAudioManager::Instance(); //*********************************************************************** //read config.ini file // C O N F I G . I N I //*********************************************************************** pLog->Log("************ Config.ini ************"); CINIReader config; //reads and stores INI file data config.LoadFile("config.ini"); std::string sValue; std::string sParameter; int nParameterValue; //default values g_Global.g_screenWidth = 1024; g_Global.g_screenHeight = 768; if(config.IsValid() == true){ pLog->Log("Valid config.ini file"); pLog->Log("Numbers of lines in config file",config.GetNumberOfLines()); for(int j=0; j< config.GetNumberOfLines();j++){ sParameter = config.GetTerm(config.GetLineFromFile(j),1); sValue = config.GetTerm(config.GetLineFromFile(j),2); nParameterValue = atoi(sValue.c_str()); pLog->Log(sParameter, nParameterValue); //load g_Global object with config.ini data if(sParameter == "WindowedMode" && nParameterValue == 1) g_Global.g_WindowedMode = true; else if(sParameter == "WindowedMode" && nParameterValue == 0) g_Global.g_WindowedMode = false; //else if(sParameter == "ScreenWidth" && nParameterValue > 0) // g_Global.g_screenWidth = nParameterValue; //else if(sParameter == "ScreenHeight" && nParameterValue > 0) // g_Global.g_screenHeight = nParameterValue; //else if(sParameter == "GameLevel" && nParameterValue > 0 && nParameterValue < 6) // g_Global.g_GameLevel = nParameterValue; //else if(sParameter == "GameSnow" && nParameterValue == 1) // g_Global.g_bGameSnow = true; //else if(sParameter == "GameSnow" && nParameterValue == 0) // g_Global.g_bGameSnow = false; else if(sParameter == "GameAudio" && nParameterValue == 1) g_Global.g_bGameAudio = true; else if(sParameter == "GameAudio" && nParameterValue == 0) g_Global.g_bGameAudio = false; else if(sParameter == "FrameRate" && nParameterValue == 1) g_Global.g_bDisplayFramerate = true; else if(sParameter == "FrameRate" && nParameterValue == 0) g_Global.g_bDisplayFramerate = false; } } pLog->Log("Reading Config.ini file is complete!"); // Break on specific memory allocation number //_CrtSetBreakAlloc(175); MSG msg; g_bRunning = true;//Start program running //Make a window and initialize DirectX in windowed mode MakeWindow(hInstance, g_Global.g_WindowedMode, g_con); //map game state information g_pStateIntro->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateMain->addTransitionEvent(EVENT_GO_HISTORY, g_pStateHistory); g_pStateMain->addTransitionEvent(EVENT_GO_RELOAD, g_pStateReload); g_pStateMain->addTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits); g_pStateMain->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStateHistory->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateReload->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStateCredits->addTransitionEvent(EVENT_GO_END, g_pStateEnd); g_pStateSelect->addTransitionEvent(EVENT_GO_AWARDS, g_pStateAwards); g_pStateAwards->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStateSelect->addTransitionEvent(EVENT_GO_PLAY, g_pStatePlay); g_pStateSelect->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain); g_pStatePlay->addTransitionEvent(EVENT_GO_WIN, g_pStateWin); g_pStatePlay->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose); g_pStateWin->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStateLose->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStatePlay->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStatePlay->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); //sonar transitions g_pStateSonar->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar); g_pStateSonar->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl); g_pStateSonar->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus); g_pStateSonar->addTransitionEvent(EVENT_GO_CHART, g_pStateChart); g_pStateSonar->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); //radar transitions g_pStateRadar->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar); g_pStateRadar->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl); g_pStateRadar->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus); g_pStateRadar->addTransitionEvent(EVENT_GO_CHART, g_pStateChart); g_pStateRadar->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); //scope transitions g_pStateScope->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); g_pStateScope->addTransitionEvent(EVENT_GO_WIN, g_pStateWin); g_pStateScope->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose); //conn transitions g_pStateControl->addTransitionEvent(EVENT_GO_PLAY, g_pStatePlay); g_pStateControl->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar); g_pStateControl->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar); g_pStateControl->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl); g_pStateControl->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus); g_pStateControl->addTransitionEvent(EVENT_GO_CHART, g_pStateChart); g_pStateControl->addTransitionEvent(EVENT_GO_SCOPE, g_pStateScope); g_pStateControl->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect); g_pStateControl->addTransitionEvent(EVENT_GO_WIN, g_pStateWin); g_pStateControl->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose); //fire control transitions g_pStateFireControl->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar); g_pStateFireControl->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar); g_pStateFireControl->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus); g_pStateFireControl->addTransitionEvent(EVENT_GO_CHART, g_pStateChart); g_pStateFireControl->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); //status transitions g_pStateStatus->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar); g_pStateStatus->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar); g_pStateStatus->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl); g_pStateStatus->addTransitionEvent(EVENT_GO_CHART, g_pStateChart); g_pStateStatus->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); //chart transitions g_pStateChart->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar); g_pStateChart->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar); g_pStateChart->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl); g_pStateChart->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus); g_pStateChart->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl); g_pStateChart->addTransitionEvent(EVENT_GO_WIN, g_pStateWin); g_pStateChart->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose); g_Timer.initialize(); g_LoopTimer.initialize(); g_FPS_Timer.initialize(); g_con.InitD3D (g_hWnd, g_Global.g_WindowedMode); //*********************************************************************** //load textures from graphics file // G R A P H I C F I L E S . D A T //*********************************************************************** pLog->Log("************ Graphicfiles.dat ************"); CFileReader* cfr = new CFileReader; cfr->LoadFile("data\\graphicfiles.dat"); int fileNumber; std::string fileName; if(cfr->IsValid()== true){ pLog->Log("Numbers of lines in file",cfr->GetNumberOfLines()); for(int j=0; j< cfr->GetNumberOfLines();j++){ sValue =cfr->GetTerm(cfr->GetLineFromFile(j),1); fileNumber = atoi(sValue.c_str()); sValue = cfr->GetTerm(cfr->GetLineFromFile(j),2); fileName = "assets\\artwork\\"; fileName = fileName + sValue; //pLog->Log("Loaded file",fileName); pLog->Log(fileName, fileNumber); g_con.LoadTexture(fileName, fileNumber); } } else{ pLog->Log("ERROR****************** Failure to load textures (graphicfiles.dat)"); delete cfr; g_con.CloseD3D(); pLog->Log("DirectX closed!"); Shutdown(); return 0; } if(g_Sprite.LoadSprites() == true){ pLog->Log("Sprites loaded!"); } else{ pLog->Log("ERROR****************** Failure to sprite data (sprites.dat)"); } //used for framerate display std::ostringstream oss; std::string sFramerate; std::string sText; int nDisplayFPSCount = 0; //initialize audio manager //*************************************************************** if(g_Global.g_bGameAudio == true){ pLog->Log("Loading audio clip..."); if(pAudio->IsValidSound()) pLog->Log("Audio system is okay!"); else pLog->Log("Audio system failure!"); //load sounds pAudio->LoadSample(SOUND_BEEP, "assets\\sounds\\beep-03.wav"); pAudio->LoadSample(SOUND_REMEMBER, "assets\\sounds\\remember.mp3"); pAudio->LoadSample(SOUND_HYMN, "assets\\sounds\\navy_hymn.mp3"); pAudio->LoadSample(SOUND_PERISCOPE, "assets\\sounds\\periscop.wav"); pAudio->LoadSample(SOUND_BUTTON_CLICK, "assets\\sounds\\button_click.wav"); pAudio->LoadSample(SOUND_DEPTH_CHARGE1,"assets\\sounds\\dc1.mp3"); pAudio->LoadSample(SOUND_DEPTH_CHARGE2,"assets\\sounds\\dc2.mp3"); pAudio->LoadSample(SOUND_TORPEDO1,"assets\\sounds\\torpedo3.mp3"); pAudio->LoadSample(SOUND_TORPEDO2,"assets\\sounds\\torpedo4.mp3"); pAudio->LoadSample(SOUND_AMBIENCE1,"assets\\sounds\\ambience1.mp3"); pAudio->LoadSample(SOUND_CLEAR_BRIDGE,"assets\\sounds\\clear_bridge.wav"); pAudio->LoadSample(SOUND_DIVING,"assets\\sounds\\diving.mp3"); pAudio->LoadSample(SOUND_GQ,"assets\\sounds\\general_quarters.wav"); pAudio->LoadSample(SOUND_ANCHORS,"assets\\sounds\\AnchorsAway.mp3"); pAudio->LoadSample(SOUND_TAPS,"assets\\sounds\\Taps.mp3"); pAudio->LoadSample(SOUND_SINKING,"assets\\sounds\\sinking2.mp3"); pAudio->LoadSample(SOUND_ANTHEM,"assets\\sounds\\USA.mp3"); pAudio->LoadSample(SOUND_FUNERAL,"assets\\sounds\\fnrlMrch.wav"); pAudio->LoadSample(SOUND_PING,"assets\\sounds\\sonar1.mp3"); //load stream pAudio->LoadStream(SOUND_BIO, "assets\\sounds\\fish.mp3"); pAudio->AddStreamClip(SOUND_BIO1, SOUND_BIO, 0, 17708); pAudio->AddStreamClip(SOUND_BIO2, SOUND_BIO, 17708, 26434); pAudio->AddStreamClip(SOUND_BIO3, SOUND_BIO, 26434, 42859); pAudio->AddStreamClip(SOUND_BIO4, SOUND_BIO, 42859, 59541); pAudio->AddStreamClip(SOUND_BIO5, SOUND_BIO, 59541, 80073); for(int i = 0; i < pAudio->Size(); i++){ pLog->Log(pAudio->GetFilename(i), i); //write filename and file index to log file } } else{ pLog->Log("Audio disabled"); } pLog->Log("Main game loop entered!"); ::ShowCursor(false); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number g_strFPS = "Game Challenge 6 (Chuck Bolin) - \"Sinking of the Rising Sun\", v0.047 Final Version"; ::SetWindowText(g_hWnd, g_strFPS.c_str()); double timeDelta; g_con.InitializePyro(); //Main application loop //******************************************************* while (g_bRunning) { //Handle messages if (PeekMessage (&msg,NULL,0,0,PM_REMOVE)){ TranslateMessage (&msg); DispatchMessage (&msg); } else{} timeDelta = g_LoopTimer.getTimeDifference(); g_pNext = g_pCurrent->update(timeDelta); if(g_pNext == g_pStateEnd) g_bRunning = false; else if(NULL != g_pNext) { g_pCurrent->deactivate(); g_pCurrent = g_pNext; g_pCurrent->activate(); } // Render our current game object g_pCurrent->render(g_con); //call each second update FPS nDisplayFPSCount++; if(g_FPS_Timer.getTimer(1)){ //g_FPS_Counter++; oss.str(""); //clear oss oss << (int) nDisplayFPSCount; //if(g_FPS_Counter > 60){ //call every 60 seconds // pLog->Log("FPS",oss.str()); // g_FPS_Counter == 0; //} // update our FPS string. // This thing can be rendered inside any of the game objects. g_strFPS = "FPS " + oss.str(); g_Global.g_strFPS = "FPS " + oss.str(); nDisplayFPSCount=0;//reset frame count } }//while(... g_con.ClosePyro(); g_con.CloseD3D(); pLog->Log("DirectX closed!"); Shutdown(); return 0;//(int)msg.wParam; //returns exit code to operating system }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { #if defined _DEBUG _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif MSG msg = {0}; WNDCLASSEX wcl = {0}; wcl.cbSize = sizeof(wcl); wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wcl.lpfnWndProc = WindowProc; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hInstance = g_hInstance = hInstance; wcl.hIcon = LoadIcon(0, IDI_APPLICATION); wcl.hCursor = LoadCursor(0, IDC_ARROW); wcl.hbrBackground = 0; wcl.lpszMenuName = 0; wcl.lpszClassName = "GLWindowClass"; wcl.hIconSm = 0; if (!RegisterClassEx(&wcl)) return 0; g_hWnd = CreateAppWindow(wcl, 0); if (g_hWnd) { InitGL(); ToggleFullScreen(); glDisable(GL_MULTISAMPLE_ARB); ShowWindow(g_hWnd, nShowCmd); UpdateWindow(g_hWnd); while (true) { while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) break; if (keys[VK_ESCAPE]) { msg.message = WM_QUIT ; } if (g_hasFocus) { RenderGL(); SwapBuffers(g_hDC); ProcessKeyboard(); } else { WaitMessage(); } } Cleanup(); UnregisterClass(wcl.lpszClassName, hInstance); } return static_cast<int>(msg.wParam); }
// winvnc.exe will also be used for helper exe // This allow us to minimize the number of seperate exe bool Myinit(HINSTANCE hInstance) { SetOSVersion(); setbuf(stderr, 0); // [v1.0.2-jp1 fix] Load resouce from dll hInstResDLL = NULL; //limit the vnclang.dll searchpath to avoid char szCurrentDir[MAX_PATH]; char szCurrentDir_vnclangdll[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; } strcpy (szCurrentDir_vnclangdll,szCurrentDir); strcat (szCurrentDir_vnclangdll,"\\"); strcat (szCurrentDir_vnclangdll,"vnclang_server.dll"); hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll); if (hInstResDLL == NULL) { hInstResDLL = hInstance; } // RegisterLinkLabel(hInstResDLL); //Load all messages from ressource file Load_Localization(hInstResDLL) ; vnclog.SetFile(); // vnclog.SetMode(2); // vnclog.SetLevel(10); #ifdef _DEBUG { // Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // Save the application instance and main thread id hAppInstance = hInstance; mainthreadId = GetCurrentThreadId(); // Initialise the VSocket system VSocketSystem socksys; if (!socksys.Initialised()) { MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK); return 0; } return 1; }
std::pair<boost::optional<boost::program_options::variables_map>, bool> main( int argc, char** argv, const char* const usage, const char* const notice, boost::program_options::options_description desc_params, const boost::program_options::positional_options_description& positional_options, const std::function<void(const std::string&, bool)> &print, const char *default_log_name, bool log_to_console) { namespace bf = boost::filesystem; namespace po = boost::program_options; #ifdef WIN32 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""}; const command_line::arg_descriptor<std::size_t> arg_max_log_file_size = {"max-log-file-size", "Specify maximum log file size [B]", MAX_LOG_FILE_SIZE}; const command_line::arg_descriptor<std::size_t> arg_max_log_files = {"max-log-files", "Specify maximum number of rotated log files to be saved (no limit by setting to 0)", MAX_LOG_FILES}; const command_line::arg_descriptor<uint32_t> arg_max_concurrency = {"max-concurrency", wallet_args::tr("Max number of threads to use for a parallel job"), DEFAULT_MAX_CONCURRENCY}; const command_line::arg_descriptor<std::string> arg_log_file = {"log-file", wallet_args::tr("Specify log file"), ""}; const command_line::arg_descriptor<std::string> arg_config_file = {"config-file", wallet_args::tr("Config file"), "", true}; std::string lang = i18n_get_language(); tools::on_startup(); #ifdef NDEBUG tools::disable_core_dumps(); #endif tools::set_strict_default_file_permissions(true); epee::string_tools::set_module_name_and_folder(argv[0]); po::options_description desc_general(wallet_args::tr("General options")); command_line::add_arg(desc_general, command_line::arg_help); command_line::add_arg(desc_general, command_line::arg_version); command_line::add_arg(desc_params, arg_log_file); command_line::add_arg(desc_params, arg_log_level); command_line::add_arg(desc_params, arg_max_log_file_size); command_line::add_arg(desc_params, arg_max_log_files); command_line::add_arg(desc_params, arg_max_concurrency); command_line::add_arg(desc_params, arg_config_file); i18n_set_language("translations", "monero", lang); po::options_description desc_all; desc_all.add(desc_general).add(desc_params); po::variables_map vm; bool should_terminate = false; bool r = command_line::handle_error_helper(desc_all, [&]() { auto parser = po::command_line_parser(argc, argv).options(desc_all).positional(positional_options); po::store(parser.run(), vm); if (command_line::get_arg(vm, command_line::arg_help)) { Print(print) << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL; Print(print) << wallet_args::tr("This is the command line monero wallet. It needs to connect to a monero\n" "daemon to work correctly.") << ENDL; Print(print) << wallet_args::tr("Usage:") << ENDL << " " << usage; Print(print) << desc_all; should_terminate = true; return true; } else if (command_line::get_arg(vm, command_line::arg_version)) { Print(print) << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")"; should_terminate = true; return true; } if(command_line::has_arg(vm, arg_config_file)) { std::string config = command_line::get_arg(vm, arg_config_file); bf::path config_path(config); boost::system::error_code ec; if (bf::exists(config_path, ec)) { po::store(po::parse_config_file<char>(config_path.string<std::string>().c_str(), desc_params), vm); } else { MERROR(wallet_args::tr("Can't find config file ") << config); return false; } } po::notify(vm); return true; }); if (!r) return {boost::none, true}; if (should_terminate) return {std::move(vm), should_terminate}; std::string log_path; if (!command_line::is_arg_defaulted(vm, arg_log_file)) log_path = command_line::get_arg(vm, arg_log_file); else log_path = mlog_get_default_log_path(default_log_name); mlog_configure(log_path, log_to_console, command_line::get_arg(vm, arg_max_log_file_size), command_line::get_arg(vm, arg_max_log_files)); if (!command_line::is_arg_defaulted(vm, arg_log_level)) { mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); } else if (!log_to_console) { mlog_set_categories(""); } if (notice) Print(print) << notice << ENDL; if (!command_line::is_arg_defaulted(vm, arg_max_concurrency)) tools::set_max_concurrency(command_line::get_arg(vm, arg_max_concurrency)); Print(print) << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")"; if (!command_line::is_arg_defaulted(vm, arg_log_level)) MINFO("Setting log level = " << command_line::get_arg(vm, arg_log_level)); else MINFO("Setting log levels = " << getenv("MONERO_LOGS")); MINFO(wallet_args::tr("Logging to: ") << log_path); Print(print) << boost::format(wallet_args::tr("Logging to %s")) % log_path; const ssize_t lockable_memory = tools::get_lockable_memory(); if (lockable_memory >= 0 && lockable_memory < 256 * 4096) // 256 pages -> at least 256 secret keys and other such small/medium objects Print(print) << tr("WARNING: You may not have a high enough lockable memory limit") #ifdef ELPP_OS_UNIX << ", " << tr("see ulimit -l") #endif ; return {std::move(vm), should_terminate}; }
void EnableLeakDetection( void ) { #ifdef _DEBUG _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif }
/************************************************************ * main function for Windows * Parse command line arguments for startup options, * to start as service or console mode application in windows. * Invokes appropriate startup functions depending on the * parameters passed *************************************************************/ int __cdecl _tmain(int argc, TCHAR * argv[]) { /* * Define Service Name and Description, which appears in windows SCM */ LPCTSTR lpszServiceName = app_name_long; /* Service Registry Name */ LPCTSTR lpszServiceDisplayName = _T("Net-SNMP Agent"); /* Display Name */ LPCTSTR lpszServiceDescription = #ifdef IFDESCR _T("SNMPv2c / SNMPv3 command responder from Net-SNMP. Supports MIB objects for IP,ICMP,TCP,UDP, and network interface sub-layers."); #else _T("SNMPv2c / SNMPv3 command responder from Net-SNMP"); #endif InputParams InputOptions; int nRunType = RUN_AS_CONSOLE; int quiet = 0; #if 0 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF /*| _CRTDBG_CHECK_ALWAYS_DF*/); #endif nRunType = ParseCmdLineForServiceOption(argc, argv, &quiet); switch (nRunType) { case REGISTER_SERVICE: /* * Register As service */ InputOptions.Argc = argc; InputOptions.Argv = argv; exit (RegisterService(lpszServiceName, lpszServiceDisplayName, lpszServiceDescription, &InputOptions, quiet)); break; case UN_REGISTER_SERVICE: /* * Unregister service */ exit (UnregisterService(lpszServiceName, quiet)); break; case RUN_AS_SERVICE: /* * Run as service */ /* * Register Stop Function */ RegisterStopFunction(StopSnmpAgent); return RunAsService(SnmpDaemonMain); break; default: /* * Run in console mode */ return SnmpDaemonMain(argc, argv); break; } }
int main(int argc, char *argv[]) #endif { #ifdef _CRTDBG_LEAK_CHECK_DF // Turn on leak-checking int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tempflag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag( tempflag ); #endif #if defined(__MWERKS__) && defined(macintosh) argc = ccommand(&argv); #endif try { std::string command, executableName, edcFilename; if (argc < 2) command = 'h'; else command = argv[1]; if (FIPS_140_2_ComplianceEnabled()) { edcFilename = "edc.dat"; #ifdef CRYPTOPP_WIN32_AVAILABLE TCHAR filename[MAX_PATH]; GetModuleFileName(GetModuleHandle(NULL), filename, sizeof(filename)); executableName = filename; std::string::size_type pos = executableName.rfind('\\'); if (pos != std::string::npos) edcFilename = executableName.substr(0, pos+1) + edcFilename; #else executableName = argv[0]; #endif if (command.substr(0, 4) != "fips") { byte expectedModuleDigest[SHA1::DIGESTSIZE]; FileSource(edcFilename.c_str(), true, new HexDecoder(new ArraySink(expectedModuleDigest, sizeof(expectedModuleDigest)))); DoPowerUpSelfTest(executableName.c_str(), expectedModuleDigest); } } switch (command[0]) { case 'g': { char seed[1024], privFilename[128], pubFilename[128]; unsigned int keyLength; cout << "Key length in bits: "; cin >> keyLength; cout << "\nSave private key to file: "; cin >> privFilename; cout << "\nSave public key to file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); GenerateRSAKey(keyLength, privFilename, pubFilename, seed); return 0; } case 'r': { switch (argv[1][1]) { case 's': RSASignFile(argv[2], argv[3], argv[4]); return 0; case 'v': { bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]); cout << (verified ? "valid signature" : "invalid signature") << endl; return 0; } default: { char privFilename[128], pubFilename[128]; char seed[1024], message[1024]; cout << "Private key file: "; cin >> privFilename; cout << "\nPublic key file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); cout << "\nMessage: "; cin.getline(message, 1024); string ciphertext = RSAEncryptString(pubFilename, seed, message); cout << "\nCiphertext: " << ciphertext << endl; string decrypted = RSADecryptString(privFilename, ciphertext.c_str()); cout << "\nDecrypted: " << decrypted << endl; return 0; } } } case 'm': DigestFile(argv[2]); return 0; case 't': { if (command == "tv") { return !RunTestDataFile(argv[2]); } // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024]; cout << "Passphrase: "; cin.getline(passPhrase, MAX_PHRASE_LENGTH); cout << "\nPlaintext: "; cin.getline(plaintext, 1024); string ciphertext = EncryptString(plaintext, passPhrase); cout << "\nCiphertext: " << ciphertext << endl; string decrypted = DecryptString(ciphertext.c_str(), passPhrase); cout << "\nDecrypted: " << decrypted << endl; return 0; } case 'e': case 'd': if (command == "e64") Base64Encode(argv[2], argv[3]); else if (command == "d64") Base64Decode(argv[2], argv[3]); else if (command == "e16") HexEncode(argv[2], argv[3]); else if (command == "d16") HexDecode(argv[2], argv[3]); else { char passPhrase[MAX_PHRASE_LENGTH]; cout << "Passphrase: "; cin.getline(passPhrase, MAX_PHRASE_LENGTH); if (command == "e") EncryptFile(argv[2], argv[3], passPhrase); else DecryptFile(argv[2], argv[3], passPhrase); } return 0; case 's': if (argv[1][1] == 's') { char seed[1024]; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed); } else SecretRecoverFile(argc-3, argv[2], argv+3); return 0; case 'i': if (argv[1][1] == 'd') InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]); else InformationRecoverFile(argc-3, argv[2], argv+3); return 0; case 'v': return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL); case 'b': if (argc<3) BenchMarkAll(); else BenchMarkAll((float)atof(argv[2])); return 0; case 'z': GzipFile(argv[3], argv[4], argv[2][0]-'0'); return 0; case 'u': GunzipFile(argv[2], argv[3]); return 0; case 'f': if (command == "fips") FIPS140_SampleApplication(executableName.c_str(), edcFilename.c_str()); else if (command == "fips-rand") FIPS140_GenerateRandomFiles(); else if (command == "ft") ForwardTcpPort(argv[2], argv[3], argv[4]); return 0; case 'a': if (AdhocTest) return (*AdhocTest)(argc, argv); else return 0; default: FileSource usage("usage.dat", true, new FileSink(cout)); return 1; } } catch(CryptoPP::Exception &e) { cout << "\nCryptoPP::Exception caught: " << e.what() << endl; return -1; } catch(std::exception &e) { cout << "\nstd::exception caught: " << e.what() << endl; return -2; } }
extern "C" DLLEXPORT /*export without name mangling*/ int WinVNCDll_Init(HINSTANCE hInstance) { // handle dpi on aero HMODULE hUser32 = LoadLibrary(_T("user32.dll")); typedef BOOL (*SetProcessDPIAwareFunc)(); SetProcessDPIAwareFunc setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware"); if (setDPIAware) setDPIAware(); FreeLibrary(hUser32); #ifdef IPP InitIpp(); #endif bool Injected_autoreconnect=false; SPECIAL_SC_EXIT=false; SPECIAL_SC_PROMPT=false; SetOSVersion(); setbuf(stderr, 0); // [v1.0.2-jp1 fix] Load resouce from dll hInstResDLL = NULL; //limit the vnclang.dll searchpath to avoid char szCurrentDir[MAX_PATH]; char szCurrentDir_vnclangdll[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; } strcpy (szCurrentDir_vnclangdll,szCurrentDir); strcat (szCurrentDir_vnclangdll,"\\"); strcat (szCurrentDir_vnclangdll,"vnclang_server.dll"); hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll); if (hInstResDLL == NULL) { hInstResDLL = hInstance; } // RegisterLinkLabel(hInstResDLL); //Load all messages from ressource file Load_Localization(hInstResDLL) ; char WORKDIR[MAX_PATH]; if (GetModuleFileName(NULL, WORKDIR, MAX_PATH)) { char* p = strrchr(WORKDIR, '\\'); if (p == NULL) return 1; *p = '\0'; } char progname[MAX_PATH]; strncpy(progname, WORKDIR, sizeof progname); progname[MAX_PATH - 1] = 0; //strcat(WORKDIR,"\\"); //strcat(WORKDIR,"WinVNC.log"); vnclog.SetFile(); // vnclog.SetMode(2); // vnclog.SetLevel(10); #ifdef _DEBUG { // Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // Save the application instance and main thread id hAppInstance = hInstance; mainthreadId = GetCurrentThreadId(); // Initialise the VSocket system VSocketSystem *socksys = new VSocketSystem(); if (!socksys->Initialised()) { MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK); return 2; } //OK m_WinVNCDll_Initialized = true; return 0; }
int main(int argc, char * argv[]) { int ret = -1; QApplication app(argc, argv); GuiSkellyTon gui; #pragma region keyboard controller auto keyBoardController = resourceManager.addScript_src(Script::getScriptComponentTemplate("KeyboardController", //start " self.KeySpeed = 9 \n" " self.MouseSpeed = .5 \n" "", //update " if(Input.getKeyDown(KeyCode.R)) then \n" " local tmp = self.parent.getTrans().pos().getY(); \n" " tmp = tmp + Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setY(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(KeyCode.W)) then \n" " local tmp = self.parent.getTrans().pos().getZ(); \n" " tmp = tmp - Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setZ(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(KeyCode.S)) then \n" " local tmp = self.parent.getTrans().pos().getZ(); \n" " tmp = tmp + Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setZ(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(KeyCode.F)) then \n" " local tmp = self.parent.getTrans().pos().getY(); \n" " tmp = tmp - Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setY(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(KeyCode.D)) then \n" " local tmp = self.parent.getTrans().pos().getX(); \n" " tmp = tmp + Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setX(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(KeyCode.A)) then \n" " local tmp = self.parent.getTrans().pos().getX(); \n" " tmp = tmp - Timer.deltaTime() * self.KeySpeed \n" " self.parent.getTrans().pos().setX(tmp); \n" " end \n" " \n" " if(Input.getKeyDown(18)) then \n" " local x = self.MouseSpeed * Input.getMouse().delta().getY() \n" " local y = self.MouseSpeed * Input.getMouse().delta().getX() \n" " self.parent.getCam().rotate(x,y); \n" " end \n" " \n" " \n" "")); #pragma endregion resourceManager.WorkingDir("./../resources/"); resourceManager.loadNeumontStuff(); auto shader = resourceManager.getDefault<ShaderProgram>(); auto dragon = resourceManager.add2DTexture("dragon","flying_dragon_1.png"); auto texture = resourceManager.add2DTexture("space","space.png"); EditorGame * game = gui.Game(); game->AddEntity("Bob"); auto comp = game->currentEntity.addComponent<RenderableComponent>(); game->currentEntity.getTrans()->pos.z = 20; game->currentEntity.getTrans()->pos.z = -20; comp->Geo(resourceManager.getFirstMesh("NU_Cube")); comp->Shader(shader); comp->material.Diffuse(dragon); comp = game->currentEntity.addComponent<RenderableComponent>(); comp->material.Diffuse(texture); auto sphere = resourceManager.duplicate(resourceManager.getFirstMesh("NU_Sphere")); sphere->scale(2,1,1); comp->Geo(sphere); comp->Shader(shader); game->currentEntity.addComponent<ScriptComponent>()->myScript(resourceManager.addScript_src(Script::getScriptComponentTemplate("rotator",//random " self.rotSpeed = Random.RangeFloat(10,300); \n" " return true \n" "", " local x = self.parent.GetScript('rotator').parent.getTrans().rot().getX(); \n" " local x = self.parent.getTrans().rot().getX(); \n" " x = x + Timer.deltaTime() * self.rotSpeed \n" " self.parent.getTrans().rot().setX(x); \n" //" GameManager.getEntityFromName('Bob').getTrans().rot().setY(50)\n " ""))); (void)keyBoardController; game->AddEntity("Cam"); game->currentEntity.addComponent<CameraComponent>(); game->currentEntity.addComponent<ScriptComponent>()->myScript(keyBoardController); game->AddEntity("Fast Rotator"); game->currentEntity.addComponent<RenderableComponent>(); game->currentEntity.getRenderable()->Geo(resourceManager.getFirstMesh("NU_Sphere")); game->currentEntity.getRenderable()->Shader(shader); game->currentEntity.addComponent<ScriptComponent>()->myScript(resourceManager.getFirstScript("rotator")); game->currentEntity.getTrans()->pos.x = 5; game->currentEntity.Parent("Bob"); game->AddEntity("Swinger"); game->currentEntity.addComponent<RenderableComponent>(); game->currentEntity.getRenderable()->Geo(resourceManager.getFirstMesh("NU_Arrow")); game->currentEntity.getRenderable()->Shader(shader); game->currentEntity.addComponent<ScriptComponent>()->myScript(resourceManager.getFirstScript("rotator")); game->currentEntity.getTrans()->pos.y = 5; game->currentEntity.getTrans()->scale = glm::vec3(.5f,.5f,.5f); game->currentEntity.Parent("Bob"); game->AddEntity("Super Swing"); game->currentEntity.addComponent<RenderableComponent>(); game->currentEntity.getRenderable()->Geo(resourceManager.getFirstMesh("NU_Plane")); game->currentEntity.getRenderable()->Shader(shader); game->currentEntity.addComponent<ScriptComponent>()->myScript(resourceManager.getFirstScript("rotator")); game->currentEntity.getTrans()->pos.y = 2; game->currentEntity.getTrans()->scale = glm::vec3(.2f,.2f,.2f); game->currentEntity.Parent("Swinger"); gui.init(); gui.show(); ret = app.exec(); _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); return ret; }
INT main(INT argc, CHAR* argv[]) { #if defined(__WINDOWS__) SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); _CrtSetDbgFlag(_CrtSetDbgFlag(0) | _CRTDBG_LEAK_CHECK_DF); #endif __ENTER_FUNCTION if( argc>1 ) { for( int i=1; i<argc; i++ ) { if( strcmp(argv[i],"-ignoreassert")==0 ) { g_Command_Assert=1 ; } else if( strcmp(argv[i],"-retryassert")==0 ) { g_Command_Assert=2 ; } if( strcmp(argv[i],"-ignoremessagebox")==0 ) { g_Command_IgnoreMessageBox=TRUE ; } if( strcmp(argv[i],"-singledb")==0 ) { g_SingleDBConnection=1; } } } //时间管理器 g_pTimeManager = new TimeManager; g_pTimeManager->Init(); g_pLog = new Log ; Assert( g_pLog ) ; BOOL ret = g_pLog->Init( ) ; Assert(ret) ; g_pLog->SaveLog(LOGIN_LOGFILE, "\r\n(###) main..." ) ; g_pTimeManager->SetTime( ) ; g_pLog->SaveLog(LOGIN_LOGFILE, "Login Starting... (%.10d)(%d)", g_pTimeManager->Time2DWORD(), g_pTimeManager->StartTime() ) ; srand(g_pTimeManager->CurrentTime()); BOOL bRet = g_Login.Init(); Assert(bRet); bRet = g_Login.Loop(); Assert(bRet); bRet = g_Login.Exit(); Assert(bRet); return 0; __LEAVE_FUNCTION return -1; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: ここにコードを挿入してください。 MSG msg; HACCEL hAccelTable; // グローバル文字列を初期化しています。 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MORPHINFO_CREATE, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // アプリケーションの初期化を実行します: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } int ret; ret = OneTimeSceneInit(); if( ret ){ _ASSERT( 0 ); return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MORPHINFO_CREATE)); // Now we're ready to recieve and process Windows messages. BOOL bGotMsg; //MSG msg; PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE ); while( WM_QUIT != msg.message ) { // Use PeekMessage() if the app is active, so we can use idle time to // render the scene. Else, use GetMessage() to avoid eating CPU time. // if( m_bActive ) bGotMsg = PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ); //else // bGotMsg = GetMessage( &msg, NULL, 0U, 0U ); if( bGotMsg ) { // Translate and dispatch the message if( 0 == TranslateAccelerator(msg.hwnd, hAccelTable, &msg) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } }else{ if( Render3DEnvironment() != 0 ){ SendMessage( msg.hwnd, WM_CLOSE, 0, 0 ); } } } DestroyObjs(); E3DBye(); return (int) msg.wParam; }
int main( int argc, char *argv[] ) { neko_vm *vm; value mload; int r; _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); neko_global_init(); vm = neko_vm_alloc(NULL); neko_vm_select(vm); # ifdef NEKO_STANDALONE neko_standalone_init(); # endif if( !neko_has_embedded_module(vm) ) { int jit = 1; int stats = 0; while( argc > 1 ) { if( strcmp(argv[1],"-interp") == 0 ) { argc--; argv++; jit = 0; continue; } if( strcmp(argv[1],"-stats") == 0 ) { argc--; argv++; stats = 1; neko_vm_set_stats(vm,neko_stats_measure,neko_stats_measure); neko_stats_measure(vm,"total",1); continue; } if( strcmp(argv[1],"-version") == 0 ) { argc--; argv++; printf("%d.%d.%d\n",NEKO_VERSION/100,(NEKO_VERSION/10)%10,NEKO_VERSION%10); return 0; } break; } # ifdef NEKO_POSIX struct sigaction act; act.sa_sigaction = NULL; act.sa_handler = handle_signal; act.sa_flags = 0; sigemptyset(&act.sa_mask); sigaction(SIGPIPE,&act,NULL); if( jit ) sigaction(SIGSEGV,&act,NULL); # endif neko_vm_jit(vm,jit); if( argc == 1 ) { # ifdef NEKO_STANDALONE report(vm,alloc_string("No embedded module in this executable"),0); # else printf("NekoVM %d.%d.%d (c)2005-2015 Haxe Foundation\n Usage : neko <file>\n",NEKO_VERSION/100,(NEKO_VERSION/10)%10,NEKO_VERSION%10); # endif mload = NULL; r = 1; } else { mload = default_loader(argv+2,argc-2); r = execute_file(vm,argv[1],mload); } if( stats ) { value v; neko_stats_measure(vm,"total",0); v = neko_stats_build(vm); val_print(alloc_string("TOT\tTIME\tCOUNT\tNAME\n")); while( v != val_null ) { char buf[256]; value *s = val_array_ptr(v); int errors = val_int(s[4]); sprintf(buf,"%d\t%d\t%d\t%s%c", val_int(s[1]), val_int(s[2]), val_int(s[3]), val_string(s[0]), errors?' ':'\n'); if( errors ) sprintf(buf+strlen(buf),"ERRORS=%d\n",errors); val_print(alloc_string(buf)); v = s[5]; } } } else { mload = default_loader(argv+1,argc-1); r = neko_execute_self(vm,mload); } if( mload != NULL && val_field(mload,val_id("dump_prof")) != val_null ) val_ocall0(mload,val_id("dump_prof")); vm = NULL; mload = NULL; neko_vm_select(NULL); neko_global_free(); return r; }
int main(int argc, char *argv[]) #endif { #if defined(PHP_WIN32) # ifdef PHP_CLI_WIN32_NO_CONSOLE int argc = __argc; char **argv = __argv; # else int num_args; wchar_t **argv_wide; char **argv_save = argv; BOOL using_wide_argv = 0; # endif #endif int c; int exit_status = SUCCESS; int module_started = 0, sapi_started = 0; char *php_optarg = NULL; int php_optind = 1, use_extended_info = 0; char *ini_path_override = NULL; char *ini_entries = NULL; int ini_entries_len = 0; int ini_ignore = 0; sapi_module_struct *sapi_module = &cli_sapi_module; /* * Do not move this initialization. It needs to happen before argv is used * in any way. */ argv = save_ps_args(argc, argv); cli_sapi_module.additional_functions = additional_functions; #if defined(PHP_WIN32) && defined(_DEBUG) && defined(PHP_WIN32_DEBUG_HEAP) { int tmp_flag; _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF; tmp_flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmp_flag); } #endif #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! [email protected] 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); (void)ts_resource(0); ZEND_TSRMLS_CACHE_UPDATE(); #endif zend_signal_startup(); #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) { switch (c) { case 'c': if (ini_path_override) { free(ini_path_override); } ini_path_override = strdup(php_optarg); break; case 'n': ini_ignore = 1; break; case 'd': { /* define ini entries on command line */ int len = (int)strlen(php_optarg); char *val; if ((val = strchr(php_optarg, '='))) { val++; if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\"\"\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, (val - php_optarg)); ini_entries_len += (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"", 1); ini_entries_len++; memcpy(ini_entries + ini_entries_len, val, len - (val - php_optarg)); ini_entries_len += len - (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0")); ini_entries_len += sizeof("\n\0\"") - 2; } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0")); ini_entries_len += len + sizeof("\n\0") - 2; } } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("=1\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0")); ini_entries_len += len + sizeof("=1\n\0") - 2; } break; } #ifndef PHP_CLI_WIN32_NO_CONSOLE case 'S': sapi_module = &cli_server_sapi_module; cli_server_sapi_module.additional_functions = server_additional_functions; break; #endif case 'h': /* help & quit */ case '?': php_cli_usage(argv[0]); goto out; case 'i': case 'v': case 'm': sapi_module = &cli_sapi_module; goto exit_loop; case 'e': /* enable extended info output */ use_extended_info = 1; break; } } exit_loop: sapi_module->ini_defaults = sapi_cli_ini_defaults; sapi_module->php_ini_path_override = ini_path_override; sapi_module->phpinfo_as_text = 1; sapi_module->php_ini_ignore_cwd = 1; sapi_startup(sapi_module); sapi_started = 1; sapi_module->php_ini_ignore = ini_ignore; sapi_module->executable_location = argv[0]; if (sapi_module == &cli_sapi_module) { if (ini_entries) { ini_entries = realloc(ini_entries, ini_entries_len + sizeof(HARDCODED_INI)); memmove(ini_entries + sizeof(HARDCODED_INI) - 2, ini_entries, ini_entries_len + 1); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI) - 2); } else { ini_entries = malloc(sizeof(HARDCODED_INI)); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI)); } ini_entries_len += sizeof(HARDCODED_INI) - 2; } sapi_module->ini_entries = ini_entries; /* startup after we get the above ini override se we get things right */ if (sapi_module->startup(sapi_module) == FAILURE) { /* there is no way to see if we must call zend_ini_deactivate() * since we cannot check if EG(ini_directives) has been initialised * because the executor's constructor does not set initialize it. * Apart from that there seems no need for zend_ini_deactivate() yet. * So we goto out_err.*/ exit_status = 1; goto out; } module_started = 1; #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) php_win32_cp_cli_setup(); orig_cp = (php_win32_cp_get_orig())->id; /* Ignore the delivered argv and argc, read from W API. This place might be too late though, but this is the earliest place ATW we can access the internal charset information from PHP. */ argv_wide = CommandLineToArgvW(GetCommandLineW(), &num_args); PHP_WIN32_CP_W_TO_A_ARRAY(argv_wide, num_args, argv, argc) using_wide_argv = 1; SetConsoleCtrlHandler(php_cli_win32_ctrl_handler, TRUE); #endif /* -e option */ if (use_extended_info) { CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; } zend_first_try { #ifndef PHP_CLI_WIN32_NO_CONSOLE if (sapi_module == &cli_sapi_module) { #endif exit_status = do_cli(argc, argv); #ifndef PHP_CLI_WIN32_NO_CONSOLE } else { exit_status = do_cli_server(argc, argv); } #endif } zend_end_try(); out: if (ini_path_override) { free(ini_path_override); } if (ini_entries) { free(ini_entries); } if (module_started) { php_module_shutdown(); } if (sapi_started) { sapi_shutdown(); } #ifdef ZTS tsrm_shutdown(); #endif #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) (void)php_win32_cp_cli_restore(); if (using_wide_argv) { PHP_WIN32_FREE_ARRAY(argv, argc); LocalFree(argv_wide); } argv = argv_save; #endif /* * Do not move this de-initialization. It needs to happen right before * exiting. */ cleanup_ps_args(argv); exit(exit_status); }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { const HCURSOR hcurSave = ::SetCursor( LoadCursor( 0, IDC_WAIT ) ); Sys_SetPhysicalWorkMemory( 192 << 20, 1024 << 20 ); Sys_GetCurrentMemoryStatus( exeLaunchMemoryStats ); #if 0 DWORD handler = (DWORD)_except_handler; __asm { // Build EXCEPTION_REGISTRATION record: push handler // Address of handler function push FS:[0] // Address of previous handler mov FS:[0],ESP // Install new EXECEPTION_REGISTRATION } #endif win32.hInstance = hInstance; idStr::Copynz( sys_cmdline, lpCmdLine, sizeof( sys_cmdline ) ); // done before Com/Sys_Init since we need this for error output Sys_CreateConsole(); // no abort/retry/fail errors SetErrorMode( SEM_FAILCRITICALERRORS ); for ( int i = 0; i < MAX_CRITICAL_SECTIONS; i++ ) { InitializeCriticalSection( &win32.criticalSections[i] ); } // get the initial time base Sys_Milliseconds(); #ifdef DEBUG // disable the painfully slow MS heap check every 1024 allocs _CrtSetDbgFlag( 0 ); #endif // Sys_FPU_EnableExceptions( TEST_FPU_EXCEPTIONS ); Sys_FPU_SetPrecision( FPU_PRECISION_DOUBLE_EXTENDED ); common->Init( 0, NULL, lpCmdLine ); #if TEST_FPU_EXCEPTIONS != 0 common->Printf( Sys_FPU_GetState() ); #endif #ifndef ID_DEDICATED if ( win32.win_notaskkeys.GetInteger() ) { DisableTaskKeys( TRUE, FALSE, /*( win32.win_notaskkeys.GetInteger() == 2 )*/ FALSE ); } #endif Sys_StartAsyncThread(); // hide or show the early console as necessary if ( win32.win_viewlog.GetInteger() || com_skipRenderer.GetBool() || idAsyncNetwork::serverDedicated.GetInteger() ) { Sys_ShowConsole( 1, true ); } else { Sys_ShowConsole( 0, false ); } #ifdef SET_THREAD_AFFINITY // give the main thread an affinity for the first cpu SetThreadAffinityMask( GetCurrentThread(), 1 ); #endif ::SetCursor( hcurSave ); // Launch the script debugger if ( strstr( lpCmdLine, "+debugger" ) ) { // DebuggerClientInit( lpCmdLine ); return 0; } ::SetFocus( win32.hWnd ); // main game loop while( 1 ) { Win_Frame(); #ifdef DEBUG Sys_MemFrame(); #endif // set exceptions, even if some crappy syscall changes them! Sys_FPU_EnableExceptions( TEST_FPU_EXCEPTIONS ); #ifdef ID_ALLOW_TOOLS if ( com_editors ) { if ( com_editors & EDITOR_GUI ) { // GUI editor GUIEditorRun(); } else if ( com_editors & EDITOR_RADIANT ) { // Level Editor RadiantRun(); } else if (com_editors & EDITOR_MATERIAL ) { //BSM Nerve: Add support for the material editor MaterialEditorRun(); } else { if ( com_editors & EDITOR_LIGHT ) { // in-game Light Editor LightEditorRun(); } if ( com_editors & EDITOR_SOUND ) { // in-game Sound Editor SoundEditorRun(); } if ( com_editors & EDITOR_DECL ) { // in-game Declaration Browser DeclBrowserRun(); } if ( com_editors & EDITOR_AF ) { // in-game Articulated Figure Editor AFEditorRun(); } if ( com_editors & EDITOR_PARTICLE ) { // in-game Particle Editor ParticleEditorRun(); } if ( com_editors & EDITOR_SCRIPT ) { // in-game Script Editor ScriptEditorRun(); } if ( com_editors & EDITOR_PDA ) { // in-game PDA Editor PDAEditorRun(); } } } #endif // run the game common->Frame(); } // never gets here return 0; }
void Network::go(label_ent * label_blk, bool dynam, FILE * fp, bool timereq, _anchor proc_anchor) { Process *this_proc; cnxt_ent *cnxt_tab; proc_ent *proc_tab; label_ent *label_tab; label_ent *label_curr; label_ent *label_new; char file_name[10]; Port *cpp; time_t st_time, end_time; double secs; st_time = time(NULL); Process * mother = (Process *) proc_anchor.reserved; _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF); label_tab = (label_ent *)malloc(sizeof(label_ent)); label_curr = label_tab; label_ent * label_this = label_blk; if (!dynam) { for (;;) { strcpy(label_curr->label, label_this->label); strcpy(label_curr->file, label_this->file); label_curr->cnxt_ptr = label_this->cnxt_ptr; label_curr->proc_ptr = label_this->proc_ptr; label_curr->ent_type = label_this->ent_type; label_this = label_this->succ; if (label_this == 0) break; label_new = (label_ent *)malloc(sizeof(label_ent)); // handle subnets label_curr->succ = label_new; label_curr = label_new; } cnxt_tab = label_tab -> cnxt_ptr; proc_tab = label_tab -> proc_ptr; } else { label_tab->succ = 0; file_name[0] = '\0'; //if (fp == 0) { // printf("File does not exist: %s\n", fp); // exit(4); //} if (thxscan(fp, label_tab, file_name) != 0) { printf("Scan error\n"); exit(4); } } //network = new Appl; //network = this; if (proc_anchor.reserved == NULL) strcpy(name,"APPL"); else strcpy(name,"SUBNET"); //first_ready_proc = 0; first_child_proc = 0; first_child_comp = 0; first_cnxt = 0; dynam = dynam; active = FALSE; possibleDeadlock = FALSE; deadlock = FALSE; thxbnet(label_tab, mother, this, label_tab); // first param is network/subnet, 2nd is "mother" process", 4th is network as a whole int thread_count = 0; this_proc = (Process*) first_child_proc; while (this_proc != 0) { thread_count ++; this_proc = this_proc -> next_proc; } /* Look for processes with no input ports */ latch = new Cdl(thread_count); Cnxt * cnxt_ptr = (Cnxt *) first_cnxt; while (cnxt_ptr != 0) { cnxt_ptr -> closed = FALSE; cnxt_ptr = cnxt_ptr -> succ; } this_proc = (Process*) first_child_proc; while (this_proc != 0) { this_proc -> network = this; this_proc-> self_starting = TRUE; cpp = this_proc -> in_ports; while (cpp != 0) { for (int i = 0; i < cpp -> elem_count; i++) { if (cpp -> elem_list[i].gen.connxn != 0 && ! cpp -> elem_list[i].is_IIP) this_proc->self_starting = FALSE; } cpp = cpp -> succ; } if (this_proc -> self_starting) { // add to ready chain //this_proc -> status = INITIATED; if (this_proc -> trace) printf("%s Initiated\n",this_proc -> procname); this_proc -> activate(); } //thread_count ++; this_proc = this_proc -> next_proc; } active = TRUE; waitForAll(); delete latch; //if (dynam) { -- check this out! // free(cnxt_tab); // free(proc_tab); //} //free (latch); thxfcbs(); //free(label_tab); end_time = time(NULL); secs = difftime(end_time, st_time); if (timereq){ printf("Elapsed time in seconds: %5.3f\n",secs); } if (strcmp(name, "SUBNET") != 0) { //_CrtDumpMemoryLeaks(); //char c; printf("Press enter to terminate\n"); std::cin.get(); // to see console //system("pause"); // to see console exit(0); } }
// STEP1 int WINAPI WinMain(HINSTANCE this_inst, HINSTANCE prev_inst, LPSTR cmdline, int cmdshow) { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); InitLog(CCLOGSTYLE_DEBUGSTRING|CCLOGSTYLE_FILE); g_dwMainThreadID= GetCurrentThreadId(); char szModuleFileName[_MAX_DIR] = {0,}; GetModuleFileName(NULL, szModuleFileName, _MAX_DIR); PathRemoveFileSpec(szModuleFileName); SetCurrentDirectory(szModuleFileName); cclog("-------------------------------------------------------------\n"); cclog("Current working directory: %s\n", szModuleFileName); cclog("-------------------------------------------------------------\n"); srand( (unsigned)time( NULL )); cclog("GUNZ " STRFILEVER " launched. build ("__DATE__" "__TIME__") \n"); char szDateRun[128]=""; char szTimeRun[128]=""; _strdate( szDateRun ); _strtime( szTimeRun ); cclog("Log time (%s %s)\n", szDateRun, szTimeRun); CCSysInfoLog(); g_App.InitFileSystem(); ZGetConfiguration()->Load(); ZStringResManager::MakeInstance(); if( !ZApplication::GetInstance()->InitLocale() ) { CCLog("Locale Init error !!!\n"); return false; } DWORD ver_major = 0; DWORD ver_minor = 0; TCHAR ver_letter = ' '; if(CheckFont()==false) { CCLog("CheckFont() failed.\n"); return 0; } RSetFunction(RF_CREATE , OnCreate); RSetFunction(RF_RENDER , OnRender); RSetFunction(RF_UPDATE , OnUpdate); RSetFunction(RF_DESTROY , OnDestroy); RSetFunction(RF_INVALIDATE, OnInvalidate); RSetFunction(RF_RESTORE, OnRestore); RSetFunction(RF_ACTIVATE, OnActivate); RSetFunction(RF_DEACTIVATE, OnDeActivate); RSetFunction(RF_ERROR, OnError); SetModeParams(); // STEP2 cclog("Entering RMain()\n"); const int nRMainReturn = RMain(APPLICATION_NAME,this_inst,prev_inst,cmdline,cmdshow,&g_ModeParams,WndProc,IDI_ICON1); if( 0 != nRMainReturn ) return nRMainReturn; if( 0 != RInitD3D(&g_ModeParams) ) { MessageBox(g_hWnd, "fail to initialize DirectX", NULL, MB_OK); cclog( "error init RInitD3D\n" ); return 0; } cclog("Entering RRun()\n"); const int nRRunReturn = RRun(); ShowWindow(g_hWnd, SW_MINIMIZE); cclog("========================== DONE ===============================\n"); ZStringResManager::FreeInstance(); return 0;//nRRunReturn; }
//----------------------------------------------------------------------------- // Name: main() // Desc: Entry point for the application. We use just the console window //----------------------------------------------------------------------------- int main(int argc, char* argv[]) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif int nRet = 0; IDirect3DDevice9* pd3dDevice = NULL; SETTINGS settings; ZeroMemory( &settings, sizeof(SETTINGS) ); if( argc < 2 ) { DisplayUsage(); goto LCleanup; } if( !ParseCommandLine( &settings ) ) { nRet = 0; goto LCleanup; } if( settings.bVerbose ) { wprintf( L"Input file: %s\n", settings.strInputFile ); wprintf( L"Output file: %s\n", settings.strOutputFile ); wprintf( L"Overwrite: %d\n", settings.bOverwrite ); switch( settings.outputType ) { case MESH_TYPE_X_TEXT: wprintf( L"Output format: .x text\n" ); break; case MESH_TYPE_X_BINARY: wprintf( L"Output format: .x binary\n" ); break; case MESH_TYPE_SDKMESH: wprintf( L"Output format: sdkmesh\n" ); break; } } // Create NULLREF device pd3dDevice = CreateNULLRefDevice(); if( pd3dDevice == NULL ) { wprintf( L"Error: Can not create NULLREF Direct3D device\n" ); nRet = 1; goto LCleanup; } else { if( settings.bVerbose ) { wprintf( L"NULLREF Direct3D 9 device created\n" ); } // Load the mesh CLoader loader; if( FAILED(loader.Load( settings.strInputFile, FTT_RELATIVE )) ) { wprintf( L"Cannot Load specified input file\n" ); goto LCleanup; nRet = 1; } // Convert to Little Endian loader.GetMesh()->ConvertToLittleEndian(); // Create a decl that reflects our inputs D3DVERTEXELEMENT9 decl[MAX_VERTEX_ELEMENTS]; BuildVertexDecl( decl, &settings ); // Convert the mesh to this decl loader.GetMesh()->ConvertVertexData( pd3dDevice, decl, MAX_VERTEX_ELEMENTS ); // fix up the mesh loader.GetMesh()->FixMesh(); // if we need tangents or binormals, generate them if( settings.bGenTangents || settings.bGenBinormals ) { if( !loader.GetMesh()->GenerateTangents( pd3dDevice ) ) wprintf( L"Warning: Cannot generate tangent frame information for mesh\n" ); } // Save it out if( FAILED( loader.Save( pd3dDevice, settings.strOutputFile, settings.outputType ) ) ) { wprintf( L"Cannot Save specified output file\n" ); goto LCleanup; nRet = 1; } if( settings.bRetainAnimation ) { WCHAR szOutput[MAX_PATH]; StringCchCopy( szOutput, MAX_PATH, settings.strOutputFile ); StringCchCat( szOutput, MAX_PATH, L"_anim" ); if( FAILED( loader.SaveAnimationData( szOutput ) ) ) { wprintf( L"Cannot Save animation data\n" ); } } } LCleanup: wprintf( L"\n" ); #ifdef DEBUG_PRESSKEY wprintf( L"Press ENTER to continue."); _getch(); #endif // Cleanup SAFE_RELEASE( pd3dDevice ); return nRet; }