void ConsoleListener::PixelSpace(int Left, int Top, int Width, int Height, bool Resize)
{
#ifdef _WIN32
	// Check size
	if (Width < 8 || Height < 12) return;

	bool DBef = true;
	bool DAft = true;
	std::string SLog = "";

	const HWND hWnd = GetConsoleWindow();
	const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	// Get console info
	CONSOLE_SCREEN_BUFFER_INFO ConInfo;
	GetConsoleScreenBufferInfo(hConsole, &ConInfo);
	DWORD BufferSize = ConInfo.dwSize.X * ConInfo.dwSize.Y;

	// ---------------------------------------------------------------------
	//  Save the current text
	// ------------------------
	DWORD cCharsRead = 0;
	COORD coordScreen = { 0, 0 };

	static const int MAX_BYTES = 1024 * 16;

	std::vector<std::array<CHAR, MAX_BYTES>> Str;
	std::vector<std::array<WORD, MAX_BYTES>> Attr;

	// ReadConsoleOutputAttribute seems to have a limit at this level
	static const int ReadBufferSize = MAX_BYTES - 32;

	DWORD cAttrRead = ReadBufferSize;
	DWORD BytesRead = 0;
	while (BytesRead < BufferSize)
	{
		Str.resize(Str.size() + 1);
		if (!ReadConsoleOutputCharacter(hConsole, Str.back().data(), ReadBufferSize, coordScreen, &cCharsRead))
			SLog += StringFromFormat("WriteConsoleOutputCharacter error");

		Attr.resize(Attr.size() + 1);
		if (!ReadConsoleOutputAttribute(hConsole, Attr.back().data(), ReadBufferSize, coordScreen, &cAttrRead))
			SLog += StringFromFormat("WriteConsoleOutputAttribute error");

		// Break on error
		if (cAttrRead == 0) break;
		BytesRead += cAttrRead;
		coordScreen = GetCoordinates(BytesRead, ConInfo.dwSize.X);
	}
	// Letter space
	int LWidth = (int)(floor((float)Width / 8.0f) - 1.0f);
	int LHeight = (int)(floor((float)Height / 12.0f) - 1.0f);
	int LBufWidth = LWidth + 1;
	int LBufHeight = (int)floor((float)BufferSize / (float)LBufWidth);
	// Change screen buffer size
	LetterSpace(LBufWidth, LBufHeight);


	ClearScreen(true);	
	coordScreen.Y = 0;
	coordScreen.X = 0;
	DWORD cCharsWritten = 0;

	int BytesWritten = 0;
	DWORD cAttrWritten = 0;
	for (size_t i = 0; i < Attr.size(); i++)
	{
		if (!WriteConsoleOutputCharacter(hConsole, Str[i].data(), ReadBufferSize, coordScreen, &cCharsWritten))
			SLog += StringFromFormat("WriteConsoleOutputCharacter error");
		if (!WriteConsoleOutputAttribute(hConsole, Attr[i].data(), ReadBufferSize, coordScreen, &cAttrWritten))
			SLog += StringFromFormat("WriteConsoleOutputAttribute error");

		BytesWritten += cAttrWritten;
		coordScreen = GetCoordinates(BytesWritten, LBufWidth);
	}	

	const int OldCursor = ConInfo.dwCursorPosition.Y * ConInfo.dwSize.X + ConInfo.dwCursorPosition.X;
	COORD Coo = GetCoordinates(OldCursor, LBufWidth);
	SetConsoleCursorPosition(hConsole, Coo);

	if (SLog.length() > 0) Log(LogTypes::LNOTICE, SLog.c_str());

	// Resize the window too
	if (Resize) MoveWindow(GetConsoleWindow(), Left,Top, (Width + 100),Height, true);
#endif
}
Exemple #2
0
/**
 *  Erstellt das Fenster mit entsprechenden Werten.
 *
 *  @param[in] width      Breite des Fensters
 *  @param[in] height     Höhe des Fensters
 *  @param[in] fullscreen Vollbildmodus ja oder nein
 *
 *  @return @p true bei Erfolg, @p false bei Fehler
 *
 *  @bug Hardwarecursor ist bei Fenstermodus sichtbar,
 *       Cursor deaktivieren ist fehlerhaft
 *
 *  @author FloSoft
 */
bool VideoWinAPI::CreateScreen(unsigned short width, unsigned short height, const bool fullscreen)
{
    char title[512];

    if(!initialized)
        return false;

    LPWSTR wTitle;
    AnsiToUtf8(wTitle, GetWindowTitle());

    WNDCLASSW  wc;
    wc.style            = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc      = WindowProc;
    wc.cbClsExtra       = 0;
    wc.cbWndExtra       = 0;
    wc.hInstance        = GetModuleHandle(NULL);
    wc.hIcon            = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_SYMBOL));
    wc.hCursor          = NULL;
    wc.hbrBackground    = NULL;
    wc.lpszMenuName     = NULL;
    wc.lpszClassName    = wTitle;

    // Fensterklasse registrieren
    if (!RegisterClassW(&wc))
        return false;

    DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
    DWORD dwStyle   = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;

    if(fullscreen)
    {
        dwExStyle   = WS_EX_APPWINDOW;
        dwStyle     = WS_POPUP;

        EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &dm_prev);
    }
    else
    {
        // Bei Fensteranwendung die Breiten und Hoehen der Fensterrahmen, Titelleiste draufaddieren
        width += 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
        height += 2 * GetSystemMetrics(SM_CXFIXEDFRAME) + GetSystemMetrics(SM_CYCAPTION);
    }

    // Fenster erstellen
    screen = CreateWindowExW(dwExStyle, wTitle, wTitle, dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);

    delete[] wTitle;

    if(screen == NULL)
        return false;

    SetClipboardViewer(screen);

    sprintf(title, "%s - v%s-%s", GetWindowTitle(), GetWindowVersion(), GetWindowRevision());

    AnsiToUtf8(wTitle, title);

    SetWindowTextW(screen, wTitle);
    SetWindowTextW(GetConsoleWindow(), wTitle);

    delete[] wTitle;

    // Pixelformat zuweisen
    GLuint PixelFormat;
    static PIXELFORMATDESCRIPTOR pfd =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        8, // 8 Bit
        8, // red
        0,
        8, // green
        0,
        8, // blue
        0,
        8, // alpha
        0,
        0,
        0,
        0,
        0,
        0,
        32, // 32 Bit
        0,
        0,
        PFD_MAIN_PLANE,
        0,
        0,
        0,
        0
    };

    screen_dc = GetDC(screen);
    if(screen_dc == NULL)
        return false;

    // Pixelformat auswaehlen
    PixelFormat = ChoosePixelFormat(screen_dc, &pfd);
    if(PixelFormat == 0)
        return false;

    // Pixelformat zuweisen
    if(!SetPixelFormat(screen_dc, PixelFormat, &pfd))
        return false;

    // Renderingkontext erstellen
    screen_rc = wglCreateContext(screen_dc);
    if(screen_rc == NULL)
        return false;

    // Renderingkontext aktivieren
    if(!wglMakeCurrent(screen_dc, screen_rc))
        return false;

    // Mauscursor ausblenden
    ShowCursor(FALSE);

    // Bei Fullscreen Aufloesung umstellen
    if(fullscreen)
    {
        // Aktuelle Framerate holen und die spaeter dann benutzen
        DEVMODE prev;
        EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &prev);

        DEVMODE dm;
        memset(&dm, 0, sizeof(dm));
        dm.dmSize = sizeof(dm);
        dm.dmFields = DM_DISPLAYFREQUENCY | DM_PELSWIDTH | DM_PELSHEIGHT;
        dm.dmDisplayFrequency = prev.dmDisplayFrequency;
        dm.dmPelsWidth = width;
        dm.dmPelsHeight = height;

        ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
    }

    this->screenWidth  = width;
    this->screenHeight = height;
    this->fullscreen = fullscreen;

    // Das Fenster anzeigen
    ShowWindow(screen, SW_SHOW);
    // Das Fenster in den Vordergrund rcken
    SetForegroundWindow(screen);
    // Dem Fenster den Eingabefokus geben
    SetFocus(screen);

    return true;
}
Exemple #3
0
int Main::main(int argc, _TCHAR* argv[])
{
    consoleWindowHandle = GetConsoleWindow();

    /// Initialize time keeping.
    LARGE_INTEGER frequency;
    assert(QueryPerformanceFrequency(&frequency) != 0);
    timeCounterFrequency = static_cast<double>(frequency.QuadPart);
    assert(timeCounterFrequency > 0);
    QueryPerformanceCounter(&startTime);

    /// Register a window class. 
    /// \todo Configure small and large application icons.

    const wchar_t * windowClassName = L"x";
    WNDCLASSEX wcex;
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= GetModuleHandle(NULL);
	wcex.hIcon			= 0; //LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAIN));
	wcex.hCursor		= 0; //LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;  //MAKEINTRESOURCE(IDC_MAIN);
	wcex.lpszClassName	= windowClassName;
	wcex.hIconSm		= 0; //LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
	ATOM windowClass = RegisterClassExW(&wcex);
    assert(windowClass != 0);

    /// Determine size of window border by creating a temporary window.

    applicationWindowHandle = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        windowClassName,
        L"X",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 
        CW_USEDEFAULT, 
		Platform::screenWidth, 
        Platform::screenHeight,
        NULL,
        NULL,
        GetModuleHandle(NULL),
        NULL);
    assert(applicationWindowHandle != NULL);
    RECT clientRect;
	GetClientRect(applicationWindowHandle, &clientRect);
	int clientRectWidth = clientRect.right;
	int clientRectHeight = clientRect.bottom; 
	RECT windowRect;
	GetWindowRect(applicationWindowHandle, &windowRect);
	int windowRectWidth = windowRect.right - windowRect.left;
	int windowRectHeight = windowRect.bottom - windowRect.top;    
	int windowBorderWidth = windowRectWidth - clientRectWidth;
	int windowBorderHeight = windowRectHeight - clientRectHeight;
	assert(DestroyWindow(applicationWindowHandle));
    Core::run = true;  // Temporary window sets this to false when destroyed.

	/// Calculate the window width and height needed to achieve
    /// the application's desired width and height.
	int windowWidth = Platform::screenWidth + windowBorderWidth;
	int windowHeight = Platform::screenHeight + windowBorderHeight;

    /// Create final application window.
	applicationWindowHandle = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        windowClassName,
        L"Project X",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
        CW_USEDEFAULT, 
		windowWidth, 
        windowHeight,
        NULL,
        NULL,
        GetModuleHandle(NULL),
        NULL);
    assert(applicationWindowHandle != NULL);
    ShowWindow(applicationWindowHandle, SW_SHOW);
    UpdateWindow(applicationWindowHandle);

#if _DEBUG
    /// When debugging, start thread to read Lua commands from console.
    CreateThread(0, 0, consoleThread, 0, 0, 0);
#else
    /// When not debugging, hide console.
    ShowWindow(consoleWindowHandle, SW_HIDE);
#endif

    deviceContext = GetDC(applicationWindowHandle);
    eglNativeWindowType = (EGLNativeWindowType) applicationWindowHandle;

    // Get the display handle.
	eglDisplay = eglGetDisplay(deviceContext);
    if (eglDisplay == EGL_NO_DISPLAY)
    {
        Platform::fatalError("No EGL Display.");
    }

    // Check OpenGL ES version.    
    EGLint major;
    EGLint minor;
    eglInitialize(eglDisplay, &major, &minor);
    checkEglError("eglInitialize");
    if (major == 1 && minor < 4)
    {
        Platform::fatalError("EGL version 1.4 or later required.");
    }

    memset(&frameBufferConfiguration, 0, sizeof(EGLConfig));  // Not sure this is needed.
    eglChooseConfig(eglDisplay, frameBufferAttributes, &frameBufferConfiguration, 1, &numFrameBufferConfigurations);
    checkEglError("Call to eglChooseConfig failed.");
    if (numFrameBufferConfigurations == 0)
    {
        Platform::fatalError("No EGL frame buffer configurations that match the specified requirements.");
    }

    // Create a window surface.
    EGLint surfaceAttributes[] = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER, EGL_NONE, EGL_NONE };
    eglSurface = eglCreateWindowSurface(eglDisplay, frameBufferConfiguration, eglNativeWindowType, surfaceAttributes);
    checkEglError("eglCreateWindowSurface");
    if (eglSurface == EGL_NO_SURFACE)
    {
        Platform::fatalError("Call to eglCreateWindowSurface failed.");
    }

    createContext();

    Core::init();

    /// Enter message loop.
    while (Core::run)
    {
        MSG Msg;
	    while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) > 0)
	    {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
	    }

        // Core has not yet drawn requested frame.
        LARGE_INTEGER currentTime;
        QueryPerformanceCounter(&currentTime);
        double totalElapsedSeconds = static_cast<double>(currentTime.QuadPart - startTime.QuadPart) / timeCounterFrequency;
        Core::onMessageQueueEmpty(totalElapsedSeconds);

        Core::renderNextFrame();

        // Core has drawn a frame, so let's render it.
        if (EGL_FALSE == eglSwapBuffers(eglDisplay, eglSurface))
        {
            // eglSwapBuffers will fail after a power event.
            // In this case, we need to reinitialize.
            EGLint error = eglGetError();	
            if (error == EGL_CONTEXT_LOST)
            {
                // Power event; need to "... destroy all contexts and reinitialise OpenGL ES state 
                // and objects to continue rendering." 
                destroyContext();
                createContext();
            }
        }
    }

    Core::shutdown();

    destroyContext();
    eglDestroySurface(eglDisplay, eglSurface);
    eglTerminate(eglDisplay);

    while (waitForConsoleToClose)
    {
        // Wait until user presses enter in console window.
    }

	ReleaseDC(Main::applicationWindowHandle, Main::deviceContext);
	return 0;
}
Exemple #4
0
/**
 *  Hauptfunktion von Siedler II.5 Return to the Roots
 *
 *  @param[in] argc Anzahl übergebener Argumente
 *  @param[in] argv Array der übergebenen Argumente
 *
 *  @return Exit Status, 0 bei Erfolg, > 0 bei Fehler
 *
 *  @author FloSoft
 *  @author OLiver
 */
int main(int argc, char* argv[])
{
#if defined _WIN32 && defined _DEBUG && defined _MSC_VER && !defined NOHWETRANS
    _set_se_translator(ExceptionHandler);
#endif // _WIN32 && _DEBUG && !NOHWETRANS

#if defined _WIN32 && defined _DEBUG && defined _MSC_VER && !defined NOCRTDBG
    // Enable Memory-Leak-Detection
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF /*| _CRTDBG_CHECK_CRT_DF*/);
#endif // _WIN32 && _DEBUG && !NOCRTDBG

    // Signal-Handler setzen
#ifdef _WIN32
    SetConsoleCtrlHandler(HandlerRoutine, TRUE);

    // set console window icon
    SendMessage(GetConsoleWindow(), WM_SETICON, (WPARAM)TRUE, (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_SYMBOL)));

    // Set UTF-8 console charset
    SetConsoleOutputCP(CP_UTF8);

#ifndef _MSC_VER
    signal(SIGSEGV, WinExceptionHandler);
#else
    SetUnhandledExceptionFilter(WinExceptionHandler);
#endif
    //AddVectoredExceptionHandler(1, WinExceptionHandler);
#else
    struct sigaction sa;
    sa.sa_handler = HandlerRoutine;
    sa.sa_flags = 0; //SA_RESTART would not allow to interrupt connect call;
    sigemptyset(&sa.sa_mask);

    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGPIPE, &sa, NULL);
    sigaction(SIGALRM, &sa, NULL);

    signal(SIGSEGV, LinExceptionHandler);
#endif // _WIN32

    // diverse dirs anlegen
    const unsigned int dir_count = 7;
    unsigned int dirs[dir_count] = { 94, 47, 48, 51, 85, 98, 99 }; // settingsdir muss zuerst angelegt werden (94)

    std::string oldSettingsDir;
    std::string newSettingsDir = GetFilePath(FILE_PATHS[94]);

#ifdef _WIN32
    oldSettingsDir = GetFilePath("~/Siedler II.5 RttR");
#elif defined(__APPLE__)
    oldSettingsDir = GetFilePath("~/.s25rttr");
#endif
    if(!oldSettingsDir.empty() && boost::filesystem::is_directory(oldSettingsDir))
        boost::filesystem::rename(oldSettingsDir, newSettingsDir);

    for(unsigned int i = 0; i < dir_count; ++i)
    {
        std::string dir = GetFilePath(FILE_PATHS[dirs[i]]);
        boost::system::error_code ec;
        boost::filesystem::create_directories(dir, ec);
        if(ec != boost::system::errc::success)
        {
            error("Directory %s could not be created: ", dir.c_str());
            error("Failed to start the game");
            WaitForEnter();
            return 1;
        }
    }

    libsiedler2::setTextureFormat(libsiedler2::FORMAT_RGBA);
    libsiedler2::setAllocator(new GlAllocator());

    // Zufallsgenerator initialisieren (Achtung: nur für Animationens-Offsets interessant, für alles andere (spielentscheidende) wird unser Generator verwendet)
    srand(static_cast<unsigned int>(std::time(NULL)));

    // Exit-Handler initialisieren
    atexit(&ExitHandler);

    // Socketzeug initialisieren
    if(!Socket::Initialize())
    {
        error("Could not init sockets!");
        error("Failed to start the game");
        WaitForEnter();
        return 1;
    }

    // Spiel starten
    if(!GAMEMANAGER.Start())
    {
        error("Failed to start the game");
        WaitForEnter();
        return 1;
    }

#ifndef NDEBUG
    if (argc > 1)
    {
        CreateServerInfo csi;
        csi.gamename = _("Unlimited Play");
        csi.password = "localgame";
        csi.port = 3665;
        csi.type = NP_LOCAL;
        csi.ipv6 = false;
        csi.use_upnp = false;

        printf("loading game!\n");

        WINDOWMANAGER.Switch(new dskSelectMap(csi));

        if(!GAMESERVER.TryToStart(csi, argv[1], MAPTYPE_SAVEGAME))
        {
            if(!GAMESERVER.TryToStart(csi, argv[1], MAPTYPE_OLDMAP))
            {
                GameWorldViewer* gwv;
                unsigned int error = GAMECLIENT.StartReplay(argv[1], gwv);

                std::string replay_errors[] =
                {
                    _("Error while playing replay!"),
                    _("Error while opening file!"),
                    _("Invalid Replay!"),
                    _("Error: Replay is too old!"),
                    _("Program version is too old to play that replay!"),
                    _("Temporary map file was not found!")
                };

                if (error)
                {
                    printf("ERROR: %s\n", replay_errors[error-1].c_str());
                }
                else
                {
                    WINDOWMANAGER.Switch(new dskGameLoader(gwv));
                }
            }
            else
            {
                WINDOWMANAGER.Draw();
                WINDOWMANAGER.Show(new iwPleaseWait);
            }
        }
        else
        {
            WINDOWMANAGER.Draw();
            WINDOWMANAGER.Show(new iwPleaseWait);
        }
    }
#endif

    // Hauptschleife
    while(GAMEMANAGER.Run())
    {
#ifndef _WIN32
        extern bool killme;
        killme = false;
#endif // !_WIN32
    }

    // Spiel beenden
    GAMEMANAGER.Stop();

    return 0;
}
Exemple #5
0
HWND myGetConsoleWindow()
{
	HWND hConWnd = NULL;

	// If we are in ConEmuHk than gfGetRealConsoleWindow may be set
	if (gfGetRealConsoleWindow)
	{
		hConWnd = gfGetRealConsoleWindow();
		// If the function pointer was set - it must be proper function
		_ASSERTEX(hConWnd==NULL || isConsoleWindow(hConWnd));
		return hConWnd;
	}

	_ASSERTE(ghWorkingModule != 0);
	HMODULE hOurModule = (HMODULE)(DWORD_PTR)ghWorkingModule;

	if (!hConWnd)
	{
		if (!hkFunc.isConEmuHk())
		{
			// Must be already called, but JIC
			hkFunc.Init(L"Unknown", hOurModule);
		}

		hConWnd = GetConsoleWindow();
		// Current process may be GUI and have no console at all
		if (!hConWnd)
			return NULL;

		// RealConsole handle is stored in the Window DATA
		if (!hkFunc.isConEmuHk())
		{
			#ifdef _DEBUG
			wchar_t sClass[64] = L""; GetClassName(hConWnd, sClass, countof(sClass));
			#endif

			// Regardless of GetClassName result, it may be VirtualConsoleClass
			HWND h = (HWND)GetWindowLongPtr(hConWnd, 0);
			if (h && IsWindow(h) && isConsoleWindow(h))
			{
				hConWnd = h;
			}
		}
	}

	return hConWnd;

#if 0
	// Смысла звать GetProcAddress для "GetConsoleWindow" мало, все равно хукается
	typedef HWND (APIENTRY *FGetConsoleWindow)();
	static FGetConsoleWindow fGetConsoleWindow = NULL;

	if (!fGetConsoleWindow)
	{
		HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");

		if (hKernel32)
		{
			fGetConsoleWindow = (FGetConsoleWindow)GetProcAddress(hKernel32, "GetConsoleWindow");
		}
	}

	if (fGetConsoleWindow)
		hConWnd = fGetConsoleWindow();

	return hConWnd;
#endif
}
int PlayerWin::run()
{
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    // set QUICK_V3_ROOT
    const char *QUICK_V3_ROOT = getenv("QUICK_V3_ROOT");
    if (!QUICK_V3_ROOT || strlen(QUICK_V3_ROOT) == 0)
    {
        MessageBox("Please run \"setup_win.bat\", set quick-cocos2d-x root path.", "quick-cocos2d-x player error");
        return 1;
    }
    SimulatorConfig::getInstance()->setQuickCocos2dxRootPath(QUICK_V3_ROOT);

    // load project config from command line args
    vector<string> args;
    for (int i = 0; i < __argc; ++i)
    {
        wstring ws(__wargv[i]);
        string s;
        s.assign(ws.begin(), ws.end());
        args.push_back(s);
    }
    _project.parseCommandLine(args);

    if (_project.getProjectDir().length() <= 0)
    {
        _project.resetToWelcome();
    }

    // set framework path
    if (!_project.isLoadPrecompiledFramework())
    {
        FileUtils::getInstance()->addSearchPath(SimulatorConfig::getInstance()->getQuickCocos2dxRootPath() + "quick/");
    }

    // create the application instance
    _app = new AppDelegate();
    _app->setProjectConfig(_project);

    // set window icon
    HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PLAYER));

    // create console window
    if (_project.isShowConsole())
    {
        AllocConsole();
        _hwndConsole = GetConsoleWindow();
        if (_hwndConsole != NULL)
        {
            SendMessage(_hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
            SendMessage(_hwndConsole, WM_SETICON, ICON_SMALL, (LPARAM)icon);

            ShowWindow(_hwndConsole, SW_SHOW);
            BringWindowToTop(_hwndConsole);
            freopen("CONOUT$", "wt", stdout);
            freopen("CONOUT$", "wt", stderr);

            HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE);
            if (hmenu != NULL) DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND);
        }
    }

    // set environments
    SetCurrentDirectoryA(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setSearchRootPath(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str());

    // check screen DPI
    HDC screen = GetDC(0);
    int dpi = GetDeviceCaps(screen, LOGPIXELSX);
    ReleaseDC(0, screen);

    // set scale with DPI
    //  96 DPI = 100 % scaling
    // 120 DPI = 125 % scaling
    // 144 DPI = 150 % scaling
    // 192 DPI = 200 % scaling
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
    //
    // enable DPI-Aware with DeclareDPIAware.manifest
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness
    float screenScale = 1.0f;
    //if (dpi >= 120 && dpi < 144)
    //{
    //    screenScale = 1.25f;
    //}
    //else if (dpi >= 144 && dpi < 192)
    //{
    //    screenScale = 1.5f;
    //}
    //else if (dpi >= 192)
    //{
    //    screenScale = 2.0f;
    //}
    CCLOG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale);

    // create opengl view
    Size frameSize = _project.getFrameSize();
    float frameScale = 1.0f;
    if (_project.isRetinaDisplay())
    {
        frameSize.width *= screenScale;
        frameSize.height *= screenScale;
    }
    else
    {
        frameScale = screenScale;
    }

    const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height);
    const bool isResize = _project.isResizeWindow();
	auto glview = GLViewImpl::createWithRect("quick-cocos2d-x", frameRect, frameScale, isResize);
	_hwnd = glview->getWin32Window();
    SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
    SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon);
    FreeResource(icon);

    auto director = Director::getInstance();
    director->setOpenGLView(glview);
    //director->setScreenScale(screenScale);

    // set window position
    if (_project.getProjectDir().length())
    {
        setZoom(_project.getFrameScale());
        Vec2 pos = _project.getWindowOffset();
        if (pos.x != 0 && pos.y != 0)
        {
            glfwSetWindowPos(glview->getWindow(), pos.x, pos.y);
        }
    }

    // init player services
    initServices();

    loadLuaConfig();
    registerKeyboardEvent();

    // register event handlers
    auto eventDispatcher = director->getEventDispatcher();
    eventDispatcher->addCustomEventListener("APP.WINDOW_CLOSE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowClose, this));
    eventDispatcher->addCustomEventListener("APP.WINDOW_RESIZE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowResize, this));
    eventDispatcher->addCustomEventListener("APP.VIEW_SCALE", CC_CALLBACK_1(PlayerWin::onWindowScale, this));

    // prepare
    _project.dump();
    auto app = Application::getInstance();
    glfwSetWin32WindowProc(&PlayerWin::windowProc);

    HWND hwnd = _hwnd;
    HWND hwndConsole = _hwndConsole;
    const ProjectConfig &project = _project;
    director->getScheduler()->schedule([hwnd, hwndConsole, project](float dt) {
        CC_UNUSED_PARAM(dt);
        ShowWindow(hwnd, SW_RESTORE);
		GLFWwindow *window = dynamic_cast<GLViewImpl*>(Director::getInstance()->getOpenGLView())->getWindow();
        glfwShowWindow(window);
    }, this, 0.0f, 0, 0.001f, false, "SHOW_WINDOW_CALLBACK");

    if (project.isAppMenu() && GetMenu(hwnd))
    {
        // update window size
        RECT rect;
        GetWindowRect(_hwnd, &rect);
        MoveWindow(_hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top + GetSystemMetrics(SM_CYMENU), FALSE);
    }
    ShowWindow(_hwnd, SW_MINIMIZE);

    // startup message loop
    return app->run();
}
int app::run(void)
{
    loadProjectConfig();

    AllocConsole();
    freopen("CONOUT$", "wt", stdout);
    freopen("CONOUT$", "wt", stderr);

    // disable close console
    HWND hwndConsole = GetConsoleWindow();
    if (hwndConsole != NULL)
    {
        HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
        if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
    }

    do
    {
        m_exit = TRUE;

        if (m_project.isShowConsole())
        {
            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
        else
        {
            ShowWindow(hwndConsole, SW_HIDE);
        }

        // create the application instance
        m_app = new AppDelegate();
        m_app->setStartupScriptFilename(m_project.getScriptFilePath());

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().c_str());

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x >= 0 || windowOffset.y >= 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
        SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    return 0;
}
Exemple #8
0
int main(int argc, char* argv[])
{
	unsigned int width = 0;
	unsigned int height = 0;

	std::locale::global(boost::locale::generator().generate(""));
	boost::filesystem::path::imbue(std::locale());

	if(!parseArgs(argc, argv, &width, &height))
		return 0;

	// only show the console on Windows if HideConsole is false
#ifdef WIN32
	// MSVC has a "SubSystem" option, with two primary options: "WINDOWS" and "CONSOLE".
	// In "WINDOWS" mode, no console is automatically created for us.  This is good, 
	// because we can choose to only create the console window if the user explicitly 
	// asks for it, preventing it from flashing open and then closing.
	// In "CONSOLE" mode, a console is always automatically created for us before we
	// enter main. In this case, we can only hide the console after the fact, which
	// will leave a brief flash.
	// TL;DR: You should compile ES under the "WINDOWS" subsystem.
	// I have no idea how this works with non-MSVC compilers.
	if(!Settings::getInstance()->getBool("HideConsole"))
	{
		// we want to show the console
		// if we're compiled in "CONSOLE" mode, this is already done.
		// if we're compiled in "WINDOWS" mode, no console is created for us automatically;
		// the user asked for one, so make one and then hook stdin/stdout/sterr up to it
		if(AllocConsole()) // should only pass in "WINDOWS" mode
		{
			freopen("CONIN$", "r", stdin);
			freopen("CONOUT$", "wb", stdout);
			freopen("CONOUT$", "wb", stderr);
		}
	}else{
		// we want to hide the console
		// if we're compiled with the "WINDOWS" subsystem, this is already done.
		// if we're compiled with the "CONSOLE" subsystem, a console is already created; 
		// it'll flash open, but we hide it nearly immediately
		if(GetConsoleWindow()) // should only pass in "CONSOLE" mode
			ShowWindow(GetConsoleWindow(), SW_HIDE);
	}
#endif


    if(Settings::getInstance()->getString("ConfigDirectory") == ""){
        if(checkForOldConfigDirectory()){
            std::cerr << "Using old config directory, please migrate your files to \"" << getDefaultConfigDirectory() << "\" and delete the .emulationstation folder.";
            Settings::getInstance()->setString("ConfigDirectory", getHomePath() + "/.emulationstation");
        } else {
            if(!createNewConfigDirectory())
                return 1;
            Settings::getInstance()->setString("ConfigDirectory", getDefaultConfigDirectory());
        }
    }
    if(!Settings::getInstance()->loadFile()){
        std::cerr << "Couldn't load settings from \"" << getConfigDirectory();
        return 1;
    }

	Log::open();
	LOG(LogInfo) << "EmulationStation - v" << PROGRAM_VERSION_STRING << ", built " << PROGRAM_BUILT_STRING;

	//always close the log on exit
	atexit(&onExit);

	Window window;
	ViewController::init(&window);
	window.pushGui(ViewController::get());

	if(!scrape_cmdline)
	{
		if(!window.init(width, height))
		{
			LOG(LogError) << "Window failed to initialize!";
			return 1;
		}

		std::string glExts = (const char*)glGetString(GL_EXTENSIONS);
		LOG(LogInfo) << "Checking available OpenGL extensions...";
		LOG(LogInfo) << " ARB_texture_non_power_of_two: " << (glExts.find("ARB_texture_non_power_of_two") != std::string::npos ? "ok" : "MISSING");
        if(Settings::getInstance()->getBool("SplashScreen"))
            window.renderLoadingScreen();
	}

	const char* errorMsg = NULL;
	if(!loadSystemConfigFile(&errorMsg))
	{
		// something went terribly wrong
		if(errorMsg == NULL)
		{
			LOG(LogError) << "Unknown error occured while parsing system config file.";
			if(!scrape_cmdline)
				Renderer::deinit();
			return 1;
		}

		// we can't handle es_systems.cfg file problems inside ES itself, so display the error message then quit
		window.pushGui(new GuiMsgBox(&window,
			errorMsg,
			"QUIT", [] { 
				SDL_Event* quit = new SDL_Event();
				quit->type = SDL_QUIT;
				SDL_PushEvent(quit);
			}));
	}

	//run the command line scraper then quit
	if(scrape_cmdline)
	{
		return run_scraper_cmdline();
	}

	//dont generate joystick events while we're loading (hopefully fixes "automatically started emulator" bug)
	SDL_JoystickEventState(SDL_DISABLE);

	// preload what we can right away instead of waiting for the user to select it
	// this makes for no delays when accessing content, but a longer startup time
	ViewController::get()->preload();

	//choose which GUI to open depending on if an input configuration already exists
	if(errorMsg == NULL)
	{
		if(fs::exists(InputManager::getConfigPath()) && InputManager::getInstance()->getNumConfiguredDevices() > 0)
		{
			ViewController::get()->goToStart();
		}else{
			window.pushGui(new GuiDetectDevice(&window, true, [] { ViewController::get()->goToStart(); }));
		}
	}

	//generate joystick events since we're done loading
	SDL_JoystickEventState(SDL_ENABLE);

	int lastTime = SDL_GetTicks();
	bool running = true;
	Uint32 CecEventType = InputManager::getInstance()->getCecEventType();

	while(running)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			if(CecEventType != ((Uint32)-1) && event.type == CecEventType)
			{
				InputManager::getInstance()->parseEvent(event, &window);
			}else{
				switch(event.type)
				{
					case SDL_JOYHATMOTION:
					case SDL_JOYBUTTONDOWN:
					case SDL_JOYBUTTONUP:
					case SDL_KEYDOWN:
					case SDL_KEYUP:
					case SDL_JOYAXISMOTION:
					case SDL_TEXTINPUT:
					case SDL_TEXTEDITING:
					case SDL_JOYDEVICEADDED:
					case SDL_JOYDEVICEREMOVED:
						InputManager::getInstance()->parseEvent(event, &window);
						break;
					case SDL_QUIT:
						running = false;
						break;
				}
			}
		}

		if(window.isSleeping())
		{
			lastTime = SDL_GetTicks();
			SDL_Delay(1); // this doesn't need to be accurate, we're just giving up our CPU time until something wakes us up
			continue;
		}

		int curTime = SDL_GetTicks();
		int deltaTime = curTime - lastTime;
		lastTime = curTime;

		// cap deltaTime at 1000
		if(deltaTime > 1000 || deltaTime < 0)
			deltaTime = 1000;

		window.update(deltaTime);
		window.render();
		Renderer::swapBuffers();

		Log::flush();
	}

	while(window.peekGui() != ViewController::get())
		delete window.peekGui();
	window.deinit();

	SystemData::deleteSystems();

	LOG(LogInfo) << "EmulationStation cleanly shutting down.";

	return 0;
}
Exemple #9
0
int App::run(void)
{
    const char *QUICK_COCOS2DX_ROOT = getenv("QUICK_COCOS2DX_ROOT");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QUICK_COCOS2DX_ROOT);

    loadProjectConfig();

    HWND hwndConsole = NULL;
    if (m_project.isShowConsole())
    {
        AllocConsole();
        freopen("CONOUT$", "wt", stdout);
        freopen("CONOUT$", "wt", stderr);

        // disable close console
        hwndConsole = GetConsoleWindow();
        if (hwndConsole != NULL)
        {
            HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
            if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
    }

    m_project.dump();

    if (m_project.isWriteDebugLogToFile())
    {
        const string debugLogFilePath = m_project.getDebugLogFilePath();
        m_writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w");
        if (!m_writeDebugLogFile)
        {
            CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str());
        }
    }

    do
    {
        m_exit = TRUE;

        // create the application instance
        m_app = new AppDelegate();
        m_app->setProjectConfig(m_project);

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setWritablePath(m_project.getWritableRealPath().c_str());

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);
        SetWindowTextA(m_hwnd, "projectgame");

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x != 0 || windowOffset.y != 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);

        if (hwndConsole)
        {
            SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
        }

        // update menu
        createViewMenu();
        updateMenu();

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    if (m_writeDebugLogFile) fclose(m_writeDebugLogFile);
    return 0;
}