BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // holds the results after searching for a match HINSTANCE hInstance; // holds the instance of the application WNDCLASS wc; // windows class structure DWORD dwExStyle; // window extended style DWORD dwStyle; // window style RECT WindowRect; // grabs rectangle upper left / lower right values WindowRect.left = (long)0; // set left value to 0 WindowRect.right = (long)width; // set right value to requested width WindowRect.top = (long)0; // set top value to 0 WindowRect.bottom = (long)height; // set bottom value to requested height fullscreen = fullscreenflag; // set the global fullscreen flag hInstance = GetModuleHandle(NULL); // grab an instance for our window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // redraw on size, and own DC for window. wc.lpfnWndProc = (WNDPROC)WndProc; // wndproc handles messages wc.cbClsExtra = 0; // no extra window data wc.cbWndExtra = 0; // no extra window data wc.hInstance = hInstance; // set the instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // load the default icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // load the arrow pointer wc.hbrBackground = NULL; // no background required for GL wc.lpszMenuName = NULL; // we don't want a menu wc.lpszClassName = "EU07"; // nazwa okna do komunikacji zdalnej // // Set The Class Name if (!arbMultisampleSupported) // tylko dla pierwszego okna if (!RegisterClass(&wc)) // Attempt To Register The Window Class { ErrorLog("Fail: window class registeration"); MessageBox(NULL, "Failed to register the window class.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // device mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // makes sure memory's cleared dmScreenSettings.dmSize = sizeof(dmScreenSettings); // size of the devmode structure // tolaris-240403: poprawka na odswiezanie monitora // locate primary monitor... if (Global::bAdjustScreenFreq) { POINT point; point.x = 0; point.y = 0; MONITORINFOEX monitorinfo; monitorinfo.cbSize = sizeof(MONITORINFOEX); ::GetMonitorInfo(::MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY), &monitorinfo); // ..and query for highest supported refresh rate unsigned int refreshrate = 0; int i = 0; while (::EnumDisplaySettings(monitorinfo.szDevice, i, &dmScreenSettings)) { if (i > 0) if (dmScreenSettings.dmPelsWidth == (unsigned int)width) if (dmScreenSettings.dmPelsHeight == (unsigned int)height) if (dmScreenSettings.dmBitsPerPel == (unsigned int)bits) if (dmScreenSettings.dmDisplayFrequency > refreshrate) refreshrate = dmScreenSettings.dmDisplayFrequency; ++i; } // fill refresh rate info for screen mode change dmScreenSettings.dmDisplayFrequency = refreshrate; dmScreenSettings.dmFields = DM_DISPLAYFREQUENCY; } dmScreenSettings.dmPelsWidth = width; // selected screen width dmScreenSettings.dmPelsHeight = height; // selected screen height dmScreenSettings.dmBitsPerPel = bits; // selected bits per pixel dmScreenSettings.dmFields = dmScreenSettings.dmFields | DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Try to set selected mode and get results. NOTE: CDS_FULLSCREEN gets rid of start bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // If the mode fails, offer two options. Quit or use windowed mode. ErrorLog("Fail: full screen"); if (MessageBox(NULL, "The requested fullscreen mode is not supported by\nyour video " "card. Use windowed mode instead?", "EU07", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. Error("Program will now close."); return FALSE; // Return FALSE } } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle = WS_EX_APPWINDOW; // Window Extended Style dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (NULL == (hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window "EU07", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right - WindowRect.left, // Calculate Window Width WindowRect.bottom - WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display ErrorLog("Fail: window creation"); MessageBox(NULL, "Window creation error.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 32Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (NULL == (hDC = GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display ErrorLog("Fail: device context"); MessageBox(NULL, "Can't create a GL device context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } /* Our first pass, Multisampling hasn't been created yet, so we create a window normally If it is supported, then we're on our second pass that means we want to use our pixel format for sampling so set PixelFormat to arbMultiSampleformat instead */ if (!arbMultisampleSupported) { if (NULL == (PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display ErrorLog("Fail: pixelformat"); MessageBox(NULL, "Can't find a suitable pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } } else PixelFormat = arbMultisampleFormat; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display ErrorLog("Fail: pixelformat"); MessageBox(NULL, "Can't set the pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (NULL == (hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display ErrorLog("Fail: OpenGL rendering context creation"); MessageBox(NULL, "Can't create a GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display ErrorLog("Fail: OpenGL rendering context activation"); MessageBox(NULL, "Can't activate the GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } /* Now that our window is created, we want to queary what samples are available we call our InitMultiSample window if we return a valid context, we want to destroy our current window and create a new one using the multisample interface. */ if (Global::iMultisampling) if (!arbMultisampleSupported) if ((Global::iMultisampling = InitMultisample(hInstance, hWnd, pfd, 1 << Global::iMultisampling)) != 0) { // WriteConsoleOnly("Opening second window for multisampling of // "+AnsiString(Global::iMultisampling)+" samples."); KillGLWindow(); // reset the display return CreateGLWindow(title, width, height, bits, fullscreenflag); // rekurencja } ShowWindow(hWnd, SW_SHOW); // show the window SetForegroundWindow(hWnd); // slightly higher priority SetFocus(hWnd); // sets keyboard focus to the window ReSizeGLScene(width, height); // set up our perspective GL screen if (!InitGL()) // initialize our newly created GL Window { KillGLWindow(); // reset the display ErrorLog("Fail: OpenGL initialization"); MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // return FALSE } return TRUE; // success }
const TCHAR *OGL_init (HWND ahwnd, int w_w, int w_h, int t_w, int t_h, int depth) { int PixelFormat; const char *ext1; static TCHAR errmsg[100] = { 0 }; static int init; ogl_enabled = 0; if (currprefs.gfx_filter != UAE_FILTER_OPENGL) { _tcscpy (errmsg, _T("OPENGL: not enabled")); return errmsg; } w_width = w_w; w_height = w_h; t_width = t_w; t_height = t_h; t_depth = depth; hwnd = ahwnd; total_textures = 2; if (isfullscreen() > 0 && WIN32GFX_GetDepth (TRUE) < 15) { _tcscpy (errmsg, _T("OPENGL: display depth must be at least 15 bit")); return errmsg; } for (;;) { memset (&pfd, 0, sizeof (pfd)); pfd.nSize = sizeof (PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA; pfd.cColorBits = depth; pfd.iLayerType = PFD_MAIN_PLANE; openglhdc = GetDC (hwnd); if (!arbMultisampleSupported) { PixelFormat = ChoosePixelFormat (openglhdc, &pfd); // Find A Compatible Pixel Format if (PixelFormat == 0) { // Did We Find A Compatible Format? _tcscpy (errmsg, _T("OPENGL: can't find suitable pixelformat")); return errmsg; } } else { PixelFormat = arbMultisampleFormat; } if (!SetPixelFormat (openglhdc, PixelFormat, &pfd)) { _stprintf (errmsg, _T("OPENGL: can't set pixelformat %x"), PixelFormat); return errmsg; } if (!(hrc = wglCreateContext (openglhdc))) { _tcscpy (errmsg, _T("OPENGL: can't create gl rendering context")); return errmsg; } if (!wglMakeCurrent (openglhdc, hrc)) { _tcscpy (errmsg, _T("OPENGL: can't activate gl rendering context")); return errmsg; } #ifdef FSAA if(!arbMultisampleSupported) { if(InitMultisample(openglhdc, &pfd)) { OGL_free (); _tcscpy (errmsg, "*"); return errmsg; } } #endif break; } glGetIntegerv (GL_MAX_TEXTURE_SIZE, &max_texture_size); required_texture_size = 2 << exact_log2 (t_width > t_height ? t_width : t_height); if (max_texture_size < t_width || max_texture_size < t_height) { _stprintf (errmsg, _T("OPENGL: %d * %d or bigger texture support required\nYour gfx card's maximum texture size is only %d * %d"), required_texture_size, required_texture_size, max_texture_size, max_texture_size); return errmsg; } required_sl_texture_size = 2 << exact_log2 (w_width > w_height ? w_width : w_height); if (currprefs.gfx_filter_scanlines > 0 && (max_texture_size < w_width || max_texture_size < w_height)) { gui_message (_T("OPENGL: %d * %d or bigger texture support required for scanlines (max is only %d * %d)\n") _T("Scanlines disabled."), required_sl_texture_size, required_sl_texture_size, max_texture_size, max_texture_size); changed_prefs.gfx_filter_scanlines = currprefs.gfx_filter_scanlines = 0; } ext1 = glGetString (GL_EXTENSIONS); if (!init) write_log (_T("OpenGL extensions: %s\n"), ext1); if (strstr (ext1, "EXT_packed_pixels")) packed_pixels = 1; if (strstr (ext1, "WGL_EXT_swap_control")) { wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress ("wglSwapIntervalEXT"); wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC)wglGetProcAddress ("wglGetSwapIntervalEXT"); if (!wglGetSwapIntervalEXT || !wglSwapIntervalEXT) { write_log (_T("OPENGL: WGL_EXT_swap_control extension found but no wglGetSwapIntervalEXT or wglSwapIntervalEXT found!?\n")); wglSwapIntervalEXT = 0; wglGetSwapIntervalEXT = 0; } } sl_ti2d_internalformat = GL_RGBA4; sl_ti2d_format = GL_RGBA; sl_ti2d_type = GL_UNSIGNED_SHORT_4_4_4_4_EXT; ti2d_type = -1; if (depth == 15 || depth == 16) { if (!packed_pixels) { _stprintf (errmsg, _T("OPENGL: can't use 15/16 bit screen depths because\n") _T("EXT_packed_pixels extension was not found.")); OGL_free (); return errmsg; } ti2d_internalformat = GL_RGB5_A1; ti2d_format = GL_RGBA; ti2d_type = GL_UNSIGNED_SHORT_5_5_5_1_EXT; } if (depth == 32) { ti2d_internalformat = GL_RGBA; ti2d_format = GL_RGBA; ti2d_type = GL_UNSIGNED_BYTE; if (!packed_pixels) { sl_ti2d_internalformat = GL_RGBA; sl_ti2d_format = GL_RGBA; sl_ti2d_type = GL_UNSIGNED_BYTE; } } if (ti2d_type < 0) { _stprintf (errmsg, _T("OPENGL: Only 15, 16 or 32 bit screen depths supported (was %d)"), depth); OGL_free (); return errmsg; } glGenTextures (total_textures, tex); /* "bitplane" texture */ glBindTexture (GL_TEXTURE_2D, tex [0]); glTexImage2D (GL_TEXTURE_2D, 0, ti2d_internalformat, required_texture_size, required_texture_size,0, ti2d_format, ti2d_type, 0); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); glDisable (GL_DEPTH_TEST); glEnable (GL_TEXTURE_2D); glDisable (GL_LIGHTING); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); ogl_enabled = 1; OGL_resize (w_width, w_height); OGL_refresh (); init = 1; write_log (_T("OPENGL: using texture depth %d texture size %d * %d scanline texture size %d * %d\n"), depth, required_texture_size, required_texture_size, required_sl_texture_size, required_sl_texture_size); return 0; }
BOOL CreateGLWindow(HWND prnt, HINSTANCE hInst, WNDPROC WndProc,LPCSTR title, int width, int height, int bits) { HWND hwnd; GLuint PixelFormat; // Хранит результат после поиска DWORD dwExStyle; // Расширенный стиль окна DWORD dwStyle; // Обычный стиль окна RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Установить левую составляющую в 0 WindowRect.right=(long)width; // Установить правую составляющую в Width WindowRect.top=(long)0; // Установить верхнюю составляющую в 0 WindowRect.bottom=(long)height; // Установить нижнюю составляющую в Height WNDCLASS wc; // Структура класса окна wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Перерисуем при перемещении и создаём скрытый DC wc.lpfnWndProc = WndProc; // Процедура обработки сообщений wc.cbClsExtra = 0; // Нет дополнительной информации для окна wc.cbWndExtra = 0; // Нет дополнительной информации для окна wc.hInstance = hInst; // Устанавливаем дескриптор wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Загружаем иконку по умолчанию wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Загружаем указатель мышки wc.hbrBackground = NULL; // Фон не требуется для GL wc.lpszMenuName = NULL; // Меню в окне не будет wc.lpszClassName = "OpenGL"; // Устанавливаем имя классу //ptC.x=0; //ptC.y=0; dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Расширенный стиль окна dwStyle = WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | WS_VSCROLL; // Обычный стиль окна if( !RegisterClass( &wc ) ) // Пытаемся зарегистрировать класс окна { MessageBox( NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Выход и возвращение функцией значения false } AdjustWindowRectEx( &WindowRect, dwStyle, false, dwExStyle ); // Подбирает окну подходящие размеры if( !( hwnd = CreateWindowEx( dwExStyle, // Расширенный стиль для окна "OpenGL", // Имя класса title, // Заголовок окна WS_CLIPSIBLINGS | // Требуемый стиль для окна WS_CLIPCHILDREN | // Требуемый стиль для окна dwStyle, // Выбираемые стили для окна 0, 0, // Позиция окна width, // Вычисление подходящей ширины height, // Вычисление подходящей высоты prnt, // Parent NULL, // Нет меню hInst, // Дескриптор приложения NULL ) ) ) // Не передаём ничего до WM_CREATE (???) { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } hGWnd=hwnd; hGInst=hInst; static PIXELFORMATDESCRIPTOR pfd= // pfd сообщает Windows каким будет вывод на экран каждого пикселя { sizeof(PIXELFORMATDESCRIPTOR), // Размер дескриптора данного формата пикселей 1, // Номер версии PFD_DRAW_TO_WINDOW | // Формат для Окна PFD_SUPPORT_OPENGL | // Формат для OpenGL PFD_DOUBLEBUFFER, // Формат для двойного буфера PFD_TYPE_RGBA, // Требуется RGBA форма bits, // Выбирается бит глубины цвета 0, 0, 0, 0, 0, 0, // Игнорирование цветовых битов 0, // Нет буфера прозрачности 0, // Сдвиговый бит игнорируется 0, // Нет буфера накопления 0, 0, 0, 0, // Биты накопления игнорируются 32, // 32 битный Z-буфер (буфер глубины) 0, // Нет буфера трафарета 0, // Нет вспомогательных буферов PFD_MAIN_PLANE, // Главный слой рисования 0, // Зарезервировано 0, 0, 0 // Маски слоя игнорируются }; if( !( hGDC = GetDC( hwnd ) ) ) // Можем ли мы получить Контекст Устройства? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } if(!arbMultisampleSupported) { if( !( PixelFormat = ChoosePixelFormat( hGDC, &pfd ) ) ) // Найден ли подходящий формат пикселя? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } } else { PixelFormat = arbMultisampleFormat; } if( !SetPixelFormat( hGDC, PixelFormat, &pfd ) ) // Возможно ли установить Формат Пикселя? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } if( !( hGRC = wglCreateContext( hGDC ) ) ) // Возможно ли установить Контекст Рендеринга? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; // Вернуть false } if( !wglMakeCurrent( hGDC, hGRC ) ) // Попробовать активировать Контекст Рендеринга { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } if(!arbMultisampleSupported && CHECK_FOR_MULTISAMPLE) { if(InitMultisample(wc.hInstance,hwnd,pfd)) { KillGLWindow(); return CreateGLWindow(prnt, hInst, WndProc, title, width, height, 32); } } ShowWindow( hwnd, SW_SHOW ); // Показать окно SetForegroundWindow( hwnd ); // Слегка повысим приоритет SetFocus( hwnd ); // Установить фокус клавиатуры на наше окно ReSizeGLScene( width, height ); // Настроим перспективу для нашего OpenGL экрана. if( !InitGL() ) // Инициализация только что созданного окна { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Вернуть false } return true; // Всё в порядке! }
BOOL CreateWindowGL (GL_Window* window) // This Code Creates Our OpenGL Window { DWORD windowStyle = WS_OVERLAPPEDWINDOW; // Define Our Window Style DWORD windowExtendedStyle = WS_EX_APPWINDOW; // Define The Window's Extended Style PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof (PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format window->init.bitsPerPixel, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 1, // Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; RECT windowRect = {0, 0, window->init.width, window->init.height}; // Define Our Window Coordinates GLuint PixelFormat; // Will Hold The Selected Pixel Format if (window->init.isFullScreen == TRUE) // Fullscreen Requested, Try Changing Video Modes { if (ChangeScreenResolution (window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE) { // Fullscreen Mode Failed. Run In Windowed Mode Instead MessageBox (HWND_DESKTOP, "Mode Switch Failed.\nRunning In Windowed Mode.", "Error", MB_OK | MB_ICONEXCLAMATION); window->init.isFullScreen = FALSE; // Set isFullscreen To False (Windowed Mode) } else // Otherwise (If Fullscreen Mode Was Successful) { ShowCursor (FALSE); // Turn Off The Cursor windowStyle = WS_POPUP; // Set The WindowStyle To WS_POPUP (Popup Window) windowExtendedStyle |= WS_EX_TOPMOST; // Set The Extended Window Style To WS_EX_TOPMOST } // (Top Window Covering Everything Else) } else // If Fullscreen Was Not Selected { // Adjust Window, Account For Window Borders AdjustWindowRectEx (&windowRect, windowStyle, 0, windowExtendedStyle); } // Create The OpenGL Window window->hWnd = CreateWindowEx (windowExtendedStyle, // Extended Style window->init.application->className, // Class Name window->init.title, // Window Title windowStyle, // Window Style 0, 0, // Window X,Y Position windowRect.right - windowRect.left, // Window Width windowRect.bottom - windowRect.top, // Window Height HWND_DESKTOP, // Desktop Is Window's Parent 0, // No Menu window->init.application->hInstance, // Pass The Window Instance window); if (window->hWnd == 0) // Was Window Creation A Success? { return FALSE; // If Not Return False } window->hDC = GetDC (window->hWnd); // Grab A Device Context For This Window if (window->hDC == 0) // Did We Get A Device Context? { // Failed DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } //ROACH /* Our first pass, Multisampling hasn't been created yet, so we create a window normally If it is supported, then we're on our second pass that means we want to use our pixel format for sampling so set PixelFormat to arbMultiSampleformat instead */ if(!arbMultisampleSupported) { PixelFormat = ChoosePixelFormat (window->hDC, &pfd); // Find A Compatible Pixel Format if (PixelFormat == 0) // Did We Find A Compatible Format? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } } else { PixelFormat = arbMultisampleFormat; } //ENDROACH if (SetPixelFormat (window->hDC, PixelFormat, &pfd) == FALSE) // Try To Set The Pixel Format { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } window->hRC = wglCreateContext (window->hDC); // Try To Get A Rendering Context if (window->hRC == 0) // Did We Get A Rendering Context? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent (window->hDC, window->hRC) == FALSE) { // Failed wglDeleteContext (window->hRC); // Delete The Rendering Context window->hRC = 0; // Zero The Rendering Context ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } //ROACH /* Now that our window is created, we want to queary what samples are available we call our InitMultiSample window if we return a valid context, we want to destroy our current window and create a new one using the multisample interface. */ if(!arbMultisampleSupported && CHECK_FOR_MULTISAMPLE) { if(InitMultisample(window->init.application->hInstance,window->hWnd,pfd)) { DestroyWindowGL (window); return CreateWindowGL(window); } } //ENDROACH ShowWindow (window->hWnd, SW_NORMAL); // Make The Window Visible window->isVisible = TRUE; // Set isVisible To True ReshapeGL (window->init.width, window->init.height); // Reshape Our GL Window ZeroMemory (window->keys, sizeof (Keys)); // Clear All Keys window->lastTickCount = GetTickCount (); // Get Tick Count return TRUE; // Window Creating Was A Success // Initialization Will Be Done In WM_CREATE }