const struct video_mode *video_get_mode( ) { static struct video_mode mode; SDL_GetWindowDisplayMode( video_window, (SDL_DisplayMode*)&mode ); return &mode; }
Uint32 PonscripterLabel::getRefreshRateDelay() { SDL_DisplayMode mode; SDL_GetWindowDisplayMode(screen, &mode); if(mode.refresh_rate == 0) return 16; //~60 hz return 1000 / mode.refresh_rate; }
bool Client::SetResolution (const int w, const int h) { SDL_DisplayMode mode; SDL_SetWindowSize (mainWindow, w, h); if (SDL_GetWindowDisplayMode (mainWindow, &mode) < 0) { SetError ("Error getting display mode: %s", SDL_GetError ()); return false; } mode.w = w; mode.h = h; if (SDL_SetWindowDisplayMode (mainWindow, &mode) < 0) { SetError ("Error setting display to %d x %d %s", w, h, SDL_GetError ()); return false; } if (fullscreen) // need to switch to windowed to take effect { if (!SetFullScreen (false)) return false; if (!SetFullScreen (true)) return false; } SaveSetting (settingsPath.c_str (), SCREENWIDTH_SETTING, w); SaveSetting (settingsPath.c_str (), SCREENHEIGHT_SETTING, h); return true; }
/* =============== GLimp_DetectAvailableModes =============== */ static bool GLimp_DetectAvailableModes(void) { int i; char buf[ MAX_STRING_CHARS ] = { 0 }; SDL_Rect modes[ 128 ]; int numModes = 0; int display = SDL_GetWindowDisplayIndex( screen ); SDL_DisplayMode windowMode; if( SDL_GetWindowDisplayMode( screen, &windowMode ) < 0 ) { Com_Printf( "Couldn't get window display mode, no resolutions detected (%s).\n", SDL_GetError() ); return false; } int numDisplayModes = SDL_GetNumDisplayModes( display ); for( i = 0; i < numDisplayModes; i++ ) { SDL_DisplayMode mode; if( SDL_GetDisplayMode( display, i, &mode ) < 0 ) continue; if( !mode.w || !mode.h ) { Com_Printf( "Display supports any resolution\n" ); return true; } if( windowMode.format != mode.format ) continue; modes[ numModes ].w = mode.w; modes[ numModes ].h = mode.h; numModes++; } if( numModes > 1 ) qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes ); for( i = 0; i < numModes; i++ ) { const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h ); if( strlen( newModeString ) < (int)sizeof( buf ) - strlen( buf ) ) Q_strcat( buf, sizeof( buf ), newModeString ); else Com_Printf( "Skipping mode %ux%x, buffer too small\n", modes[ i ].w, modes[ i ].h ); } if( *buf ) { buf[ strlen( buf ) - 1 ] = 0; Com_Printf( "Available modes: '%s'\n", buf ); ri->Cvar_Set( "r_availableModes", buf ); } return true; }
/* =============== GLimp_DetectAvailableModes =============== */ static void GLimp_DetectAvailableModes() { char buf[MAX_STRING_CHARS] = {0}; SDL_Rect modes[128]; int numModes = 0; int i; SDL_DisplayMode windowMode; int display; display = SDL_GetWindowDisplayIndex(window); if (SDL_GetWindowDisplayMode(window, &windowMode) < 0) { ri.Printf(PRINT_WARNING, "Couldn't get window display mode: %s\n", SDL_GetError()); return; } for (i = 0; i < SDL_GetNumDisplayModes(display); i++) { SDL_DisplayMode mode; if (SDL_GetDisplayMode(display, i, &mode) < 0) { continue; } if (!mode.w || !mode.h) { ri.Printf(PRINT_ALL, "Display supports any resolution\n"); return; } if (windowMode.format != mode.format || windowMode.refresh_rate != mode.refresh_rate) { continue; } modes[numModes].w = mode.w; modes[numModes].h = mode.h; numModes++; } if (numModes > 1) { qsort(modes, numModes, sizeof(SDL_Rect), GLimp_CompareModes); } for (i = 0; i < numModes; i++) { const char* newModeString = va("%ux%u ", modes[i].w, modes[i].h); if (strlen(newModeString) < (int) sizeof(buf) - strlen(buf)) { Q_strcat(buf, sizeof(buf), newModeString); } else { ri.Printf(PRINT_WARNING, "Skipping mode %ux%x, buffer too small\n", modes[i].w, modes[i].h); } } if (*buf) { ri.Printf(PRINT_ALL, "Available modes: '%s'\n", buf); ri.Cvar_Set("r_availableModes", buf); } }
int main(int argc, char **argv) { if (argc < 2 || argc > 2) { printf("Usage: %s image.flif\n",argv[0]); return 0; } SDL_Init(SDL_INIT_VIDEO); SDL_EventState(SDL_MOUSEMOTION,SDL_IGNORE); window = SDL_CreateWindow("FLIF Viewer -- Loading...", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 200, 200, SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawColor(renderer, 127, 127, 127, 255); // background color (in case aspect ratio of window doesn't match image) SDL_RenderClear(renderer); SDL_RenderPresent(renderer); if (SDL_GetWindowDisplayMode(window,&dm)) { printf("Error: SDL_GetWindowDisplayMode\n"); return 1; } int result = 0; #ifdef PROGRESSIVE_DECODING printf("Decoding progressively...\n"); SDL_Thread *decode_thread = SDL_CreateThread(decodeThread,"Decode_FLIF",argv); if (!decode_thread) { printf("Error: failed to create decode thread\n"); return 1; } #else printf("Decoding entire image...\n"); result = decodeThread(argv); #endif SDL_Event e; unsigned int current_time; unsigned int begin=SDL_GetTicks(); while (!quit) { if (nb_frames > 1) { current_time = SDL_GetTicks(); draw_image(); int time_passed = SDL_GetTicks()-current_time; int time_to_wait = frame_delay[frame] - time_passed; if (time_to_wait>0) SDL_Delay(time_to_wait); // todo: if the animation has extremely long frame delays, this makes the viewer unresponsive frame++; frame %= nb_frames; } else { SDL_Delay(200); // if it's not an animation, check event queue 5 times per second } while (SDL_PollEvent(&e)) do_event(e); } if (nb_frames > 1) printf("Rendered %i frames in %.2f seconds, %.4f frames per second\n", framecount, 0.001*(SDL_GetTicks()-begin), 1000.0*framecount/(SDL_GetTicks()-begin)); #ifdef PROGRESSIVE_DECODING // make sure the decoding gets properly aborted (in case it was not done yet) while(flif_abort_decoder(d)) SDL_Delay(100); SDL_WaitThread(decode_thread, &result); #endif SDL_DestroyWindow(window); SDL_Quit(); return result; }
void Camera::GetVisionZone(b2AABB& zone, SDL_Window* window) { SDL_DisplayMode displayMode; SDL_GetWindowDisplayMode(window, &displayMode); zone.lowerBound = b2Vec2(m_cameraFollow.x - (displayMode.w / (2.0f * ConversionScale::PIXEL_TO_SIM)) - CameraVisionError::ERROR_IN_METERS, m_cameraFollow.y - (displayMode.h / (2.0f * ConversionScale::PIXEL_TO_SIM)) - CameraVisionError::ERROR_IN_METERS); zone.upperBound = b2Vec2(m_cameraFollow.x + (displayMode.w / (2.0f * ConversionScale::PIXEL_TO_SIM)) + CameraVisionError::ERROR_IN_METERS, m_cameraFollow.y + (displayMode.h / (2.0f * ConversionScale::PIXEL_TO_SIM)) + CameraVisionError::ERROR_IN_METERS); }
int inline Window::getWindowDisplayMode(State & state, SDL_Window * window){ Stack * stack = state.stack; DisplayMode * interfaceDisplayMode = state.getInterface<DisplayMode>("LuaSDL_DisplayMode"); SDL_DisplayMode * displayMode = new SDL_DisplayMode; if (SDL_GetWindowDisplayMode(window, displayMode) == 0){ interfaceDisplayMode->push(displayMode, true); return 1; } else{ delete displayMode; return 0; } }
bool window_init(int width, int height, bool fullscreen) { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("Error initializing SDL: %s\n", SDL_GetError()); return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); window = SDL_CreateWindow("Wolfenstein 3D", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); if (!window) { printf("Error while creating the window: %s\n", SDL_GetError()); return false; } SDL_SetWindowGrab(window, SDL_TRUE); gl = SDL_GL_CreateContext(window); if (!gl) { printf("Error initializing OpenGL: %s\n", SDL_GetError()); return false; } SDL_GL_MakeCurrent(window, gl); SDL_GL_SetSwapInterval(1); if (SDL_GetWindowDisplayMode(window, &mode) < 0) { printf("Error while getting the display mode: %s\n", SDL_GetError()); } SDL_ShowCursor(0); viddef.height = height; viddef.width = width; return true; }
void class_gfx_window::update_window_infos(void) { SDL_DisplayMode mode; if (SDL_GetWindowDisplayMode(this->window, &mode) == 0) { this->window_width = mode.w; this->window_height = mode.h; this->window_ips = mode.refresh_rate; } else { this->window_width = 800; this->window_height = 600; this->window_ips = 59; } }
static Image texify(SDL_Surface* surface, SDL_Renderer* renderer, SDL_Window* win) { static Image img; SDL_DisplayMode mode; SDL_Texture* texture; printf("creating texture from image...\n"); texture = SDL_CreateTextureFromSurface(renderer, surface); printf("done!\n"); SDL_GetWindowDisplayMode(win, &mode); img.tex = texture; img.rect.x = mode.w / 2 - surface->w / 2; img.rect.y = mode.h / 2 - surface->h / 2; img.rect.w = surface->w; img.rect.h = surface->h; return img; }
static qboolean GetWindowSize(int* w, int* h) { if(window == NULL || w == NULL || h == NULL) return false; #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_DisplayMode m; if(SDL_GetWindowDisplayMode(window, &m) != 0) { VID_Printf(PRINT_ALL, "Can't get Displaymode: %s\n", SDL_GetError()); return false; } *w = m.w; *h = m.h; #else *w = window->w; *h = window->h; #endif return true; }
void VideoWrapper::setVideoMode(int width, int height, bool fullscreen, bool windowBorder) { SDL_SetWindowFullscreen(mWindow, 0); if (SDL_GetWindowFlags(mWindow) & SDL_WINDOW_MAXIMIZED) SDL_RestoreWindow(mWindow); if (fullscreen) { SDL_DisplayMode mode; SDL_GetWindowDisplayMode(mWindow, &mode); mode.w = width; mode.h = height; SDL_SetWindowDisplayMode(mWindow, &mode); SDL_SetWindowFullscreen(mWindow, fullscreen); } else { SDL_SetWindowSize(mWindow, width, height); SDL_SetWindowBordered(mWindow, windowBorder ? SDL_TRUE : SDL_FALSE); } }
static void X11_GetDisplaySize(_THIS, SDL_Window * window, int *w, int *h) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; SDL_DisplayData *displaydata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata; XWindowAttributes attr; XGetWindowAttributes(data->display, RootWindow(data->display, displaydata->screen), &attr); if (window->flags & SDL_WINDOW_FULLSCREEN) { /* The bounds when this window is visible is the fullscreen mode */ SDL_DisplayMode fullscreen_mode; if (SDL_GetWindowDisplayMode(window, &fullscreen_mode) == 0) { attr.width = fullscreen_mode.w; attr.height = fullscreen_mode.h; } } if (w) { *w = attr.width; } if (h) { *h = attr.height; } }
SDL_Window* set_video_mode(int w, int h, int flags) { static SDL_Window* wnd = NULL; static SDL_GLContext ctx = NULL; static int wnd_flags = 0; if(wnd) { SDL_DisplayMode mode; if(SDL_GetWindowDisplayMode(wnd, &mode) == 0) { mode.w = w; mode.h = h; if(SDL_SetWindowDisplayMode(wnd, &mode) == 0) { SDL_SetWindowSize(wnd, w, h); SDL_SetWindowFullscreen(wnd, flags&SDL_WINDOW_FULLSCREEN); SDL_SetWindowPosition(wnd, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); return wnd; } else { fprintf(stderr, "ERROR: Failed to set window display mode. Destroying window and creating a new one.\n"); } } else { fprintf(stderr, "ERROR: Failed to get window display mode. Destroying window and creating a new one.\n"); } } wnd_flags = flags; graphics::texture::unbuild_all(); #if defined(USE_SHADERS) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); if(g_msaa > 0) { if(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1) != 0) { std::cerr << "MSAA(" << g_msaa << ") requested but mutlisample buffer couldn't be allocated." << std::endl; } else { size_t msaa = next_pow2(g_msaa); std::cerr << "Requesting MSAA of " << msaa; if(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, msaa) != 0) { std::cerr << " -- Failure, disabled."; } std::cerr << std::endl; } } #endif if(global_renderer) { SDL_DestroyRenderer(global_renderer); global_renderer = NULL; } if(ctx) { SDL_GL_DeleteContext(ctx); ctx = NULL; } if(wnd) { SDL_DestroyWindow(wnd); global_main_window = wnd = NULL; } if(!(flags & CLEANUP_WINDOW_CONTEXT)) { global_main_window = wnd = SDL_CreateWindow(module::get_module_pretty_name().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, flags); ctx = SDL_GL_CreateContext(wnd); global_renderer = SDL_CreateRenderer(wnd, -1, SDL_RENDERER_ACCELERATED); #if defined(__GLEW_H__) GLenum glew_status = glewInit(); ASSERT_EQ(glew_status, GLEW_OK); #endif reset_opengl_state(); graphics::texture::rebuild_all(); texture_frame_buffer::rebuild(); } #if defined(USE_SHADERS) int depth_size, stencil_size; SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth_size); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil_size); std::cerr << "Depth buffer size: " << depth_size << std::endl; std::cerr << "Stenicl buffer size: " << stencil_size << std::endl; int depth; glGetIntegerv(GL_DEPTH_BITS, &depth); std::cerr << "Depth(from GL) buffer size: " << depth << std::endl; if(g_msaa > 0 && SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &g_msaa_set) == 0) { std::cerr << "Actual MSAA: " << g_msaa_set << std::endl; } #endif return wnd; }
// Constructor and destructor c_video_screen::c_video_screen( uint id, const std::string& name, const std::string& color, int view_cols, int view_rows, int pos_x, int pos_y, int width, int height, bool fullscreen ) : // Info m_id(id), m_name(name), m_color(color), // View m_view_cols(view_cols), m_view_rows(view_rows), // Window m_window_pos_x(pos_x), m_window_pos_y(pos_y), m_window_width(width), m_window_height(height), m_window_fullscreen(fullscreen), // Timing m_time(0) { // Debug std::cout << boost::format("Screen (%s): id=%d, pos_x=%d, pos_y=%d, width=%d, height=%d, fullscreen=%s") % m_name % m_id % m_window_pos_x % m_window_pos_y % m_window_width % m_window_height % std::string(m_window_fullscreen ? "true" : "false") << std::endl; // SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) throw c_exception("Screen: Failed to initalize SDL!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) }); // Attributes SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // Create window std::string title = std::string("madj - ") + m_name; Uint32 flags = SDL_WINDOW_OPENGL | (m_window_fullscreen ? (SDL_WINDOW_BORDERLESS | SDL_WINDOW_FULLSCREEN_DESKTOP) : SDL_WINDOW_RESIZABLE); m_window = SDL_CreateWindow(title.c_str(), m_window_pos_x, m_window_pos_y, m_window_width, m_window_height, flags); if (m_window == nullptr) throw c_exception("Screen: Failed to create window!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) }); // OpenGL context m_context = c_global::video->context(m_window); gl_init(); // Window settings SDL_DisableScreenSaver(); if (SDL_GL_SetSwapInterval(-1) != 0) { // 0 = immediate, 1 = vertical retrace sync, -1 = late swap tearing //std::cout << "Screen: Failed to set swap interval to late swap tearing!" << std::endl; if (SDL_GL_SetSwapInterval(1) != 0) std::cout << "Screen: Failed to set swap interval to vsync!" << std::endl; } // Display mode SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 }; if (SDL_GetWindowDisplayMode(m_window, &mode) == 0 && mode.refresh_rate != 0) { std::cout << "Screen: refresh_rate = " << mode.refresh_rate << std::endl; } // Rendering area SDL_GL_GetDrawableSize(m_window, &m_window_width, &m_window_height); CEGUI::Rectf area(CEGUI::Vector2f(0.0f, 0.0f), CEGUI::Sizef(m_window_width, m_window_height)); m_context->cegui_renderer().getDefaultRenderTarget().setArea(area); m_context->cegui_renderer().getDefaultRenderTarget().activate(); // Timing m_time = SDL_GetTicks() / 1000.f; // CEGUI m_cegui = std::unique_ptr<c_cegui>(new c_cegui(m_context)); // Scheme CEGUI::SchemeManager::getSingleton().createFromFile("GWEN.scheme"); // Defaults //m_cegui->context().setDefaultFont("OpenSans-8"); m_cegui->context().setDefaultFont("DroidSansMono-10"); //m_cegui->context().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); //m_cegui->context().setDefaultTooltipType("TaharezLook/Tooltip"); // Root window m_cegui_root = reinterpret_cast<CEGUI::DefaultWindow*>(CEGUI::WindowManager::getSingleton().loadLayoutFromFile("screen.layout")); m_cegui_root->setUsingAutoRenderingSurface(false); //m_cegui_client = dynamic_cast<CEGUI::DefaultWindow*>(m_cegui_root->getChildRecursive("TrackerClient")); m_cegui->context().setRootWindow(m_cegui_root); // Error check g_opengl_check(); // Viewport check if ( m_view_rows < 1 || m_view_cols < 1 || m_view_rows > 10 || m_view_cols > 10 ) { throw c_exception("Screen: Wrong number of view columns/rows specified!", { throw_format("name", m_name) }); } }
SDL_Renderer * D3D_CreateRenderer(SDL_Window * window, Uint32 flags) { SDL_Renderer *renderer; D3D_RenderData *data; SDL_SysWMinfo windowinfo; HRESULT result; D3DPRESENT_PARAMETERS pparams; IDirect3DSwapChain9 *chain; D3DCAPS9 caps; Uint32 window_flags; int w, h; SDL_DisplayMode fullscreen_mode; D3DMATRIX matrix; renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); if (!renderer) { SDL_OutOfMemory(); return NULL; } data = (D3D_RenderData *) SDL_calloc(1, sizeof(*data)); if (!data) { SDL_free(renderer); SDL_OutOfMemory(); return NULL; } data->d3dDLL = SDL_LoadObject("D3D9.DLL"); if (data->d3dDLL) { IDirect3D9 *(WINAPI * D3DCreate) (UINT SDKVersion); D3DCreate = (IDirect3D9 * (WINAPI *) (UINT)) SDL_LoadFunction(data->d3dDLL, "Direct3DCreate9"); if (D3DCreate) { data->d3d = D3DCreate(D3D_SDK_VERSION); } if (!data->d3d) { SDL_UnloadObject(data->d3dDLL); data->d3dDLL = NULL; } } if (!data->d3d) { SDL_free(renderer); SDL_free(data); SDL_SetError("Unable to create Direct3D interface"); return NULL; } renderer->WindowEvent = D3D_WindowEvent; renderer->CreateTexture = D3D_CreateTexture; renderer->UpdateTexture = D3D_UpdateTexture; renderer->LockTexture = D3D_LockTexture; renderer->UnlockTexture = D3D_UnlockTexture; renderer->SetRenderTarget = D3D_SetRenderTarget; renderer->UpdateViewport = D3D_UpdateViewport; renderer->RenderClear = D3D_RenderClear; renderer->RenderDrawPoints = D3D_RenderDrawPoints; renderer->RenderDrawLines = D3D_RenderDrawLines; renderer->RenderFillRects = D3D_RenderFillRects; renderer->RenderCopy = D3D_RenderCopy; renderer->RenderReadPixels = D3D_RenderReadPixels; renderer->RenderPresent = D3D_RenderPresent; renderer->DestroyTexture = D3D_DestroyTexture; renderer->DestroyRenderer = D3D_DestroyRenderer; renderer->info = D3D_RenderDriver.info; renderer->driverdata = data; renderer->info.flags = SDL_RENDERER_ACCELERATED; SDL_VERSION(&windowinfo.version); SDL_GetWindowWMInfo(window, &windowinfo); window_flags = SDL_GetWindowFlags(window); SDL_GetWindowSize(window, &w, &h); SDL_GetWindowDisplayMode(window, &fullscreen_mode); SDL_zero(pparams); pparams.hDeviceWindow = windowinfo.info.win.window; pparams.BackBufferWidth = w; pparams.BackBufferHeight = h; if (window_flags & SDL_WINDOW_FULLSCREEN) { pparams.BackBufferFormat = PixelFormatToD3DFMT(fullscreen_mode.format); } else { pparams.BackBufferFormat = D3DFMT_UNKNOWN; } pparams.BackBufferCount = 1; pparams.SwapEffect = D3DSWAPEFFECT_DISCARD; if (window_flags & SDL_WINDOW_FULLSCREEN) { pparams.Windowed = FALSE; pparams.FullScreen_RefreshRateInHz = fullscreen_mode.refresh_rate; } else { pparams.Windowed = TRUE; pparams.FullScreen_RefreshRateInHz = 0; } if (flags & SDL_RENDERER_PRESENTVSYNC) { pparams.PresentationInterval = D3DPRESENT_INTERVAL_ONE; } else { pparams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; } /* FIXME: Which adapter? */ data->adapter = D3DADAPTER_DEFAULT; IDirect3D9_GetDeviceCaps(data->d3d, data->adapter, D3DDEVTYPE_HAL, &caps); result = IDirect3D9_CreateDevice(data->d3d, data->adapter, D3DDEVTYPE_HAL, pparams.hDeviceWindow, D3DCREATE_FPU_PRESERVE | ((caps. DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) ? D3DCREATE_HARDWARE_VERTEXPROCESSING : D3DCREATE_SOFTWARE_VERTEXPROCESSING), &pparams, &data->device); if (FAILED(result)) { D3D_DestroyRenderer(renderer); D3D_SetError("CreateDevice()", result); return NULL; } data->beginScene = SDL_TRUE; data->scaleMode = D3DTEXF_FORCE_DWORD; /* Get presentation parameters to fill info */ result = IDirect3DDevice9_GetSwapChain(data->device, 0, &chain); if (FAILED(result)) { D3D_DestroyRenderer(renderer); D3D_SetError("GetSwapChain()", result); return NULL; } result = IDirect3DSwapChain9_GetPresentParameters(chain, &pparams); if (FAILED(result)) { IDirect3DSwapChain9_Release(chain); D3D_DestroyRenderer(renderer); D3D_SetError("GetPresentParameters()", result); return NULL; } IDirect3DSwapChain9_Release(chain); if (pparams.PresentationInterval == D3DPRESENT_INTERVAL_ONE) { renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } data->pparams = pparams; IDirect3DDevice9_GetDeviceCaps(data->device, &caps); renderer->info.max_texture_width = caps.MaxTextureWidth; renderer->info.max_texture_height = caps.MaxTextureHeight; if (caps.NumSimultaneousRTs >= 2) { renderer->info.flags |= SDL_RENDERER_TARGETTEXTURE; } /* Set up parameters for rendering */ IDirect3DDevice9_SetVertexShader(data->device, NULL); IDirect3DDevice9_SetFVF(data->device, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); IDirect3DDevice9_SetRenderState(data->device, D3DRS_ZENABLE, D3DZB_FALSE); IDirect3DDevice9_SetRenderState(data->device, D3DRS_CULLMODE, D3DCULL_NONE); IDirect3DDevice9_SetRenderState(data->device, D3DRS_LIGHTING, FALSE); /* Enable color modulation by diffuse color */ IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLOROP, D3DTOP_MODULATE); IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE); IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); /* Enable alpha modulation by diffuse alpha */ IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); /* Disable second texture stage, since we're done */ IDirect3DDevice9_SetTextureStageState(data->device, 1, D3DTSS_COLOROP, D3DTOP_DISABLE); IDirect3DDevice9_SetTextureStageState(data->device, 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); /* Store the default render target */ IDirect3DDevice9_GetRenderTarget(data->device, 0, &data->defaultRenderTarget ); data->currentRenderTarget = NULL; /* Set an identity world and view matrix */ matrix.m[0][0] = 1.0f; matrix.m[0][1] = 0.0f; matrix.m[0][2] = 0.0f; matrix.m[0][3] = 0.0f; matrix.m[1][0] = 0.0f; matrix.m[1][1] = 1.0f; matrix.m[1][2] = 0.0f; matrix.m[1][3] = 0.0f; matrix.m[2][0] = 0.0f; matrix.m[2][1] = 0.0f; matrix.m[2][2] = 1.0f; matrix.m[2][3] = 0.0f; matrix.m[3][0] = 0.0f; matrix.m[3][1] = 0.0f; matrix.m[3][2] = 0.0f; matrix.m[3][3] = 1.0f; IDirect3DDevice9_SetTransform(data->device, D3DTS_WORLD, &matrix); IDirect3DDevice9_SetTransform(data->device, D3DTS_VIEW, &matrix); return renderer; }
void KPSdl2UserInterface::OpenWindow(int /* argc */ , char ** /* argv */) { auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; SDL_version compiled; SDL_version linked; std::stringstream message; SDL_VERSION(&compiled); SDL_GetVersion(&linked); BLogger::Log("SDL UserInterface initialization"); BLogger::Log("SDL linked version: ", static_cast<unsigned int>(linked.major), '.', static_cast<unsigned int>(linked.minor), '.', static_cast<unsigned int>(linked.patch)); BLogger::Log("SDL compiled version: ", static_cast<unsigned int>(compiled.major), '.', static_cast<unsigned int>(compiled.minor), '.', static_cast<unsigned int>(compiled.patch)); BLogger::Log("SDL Header version: ", SDL_MAJOR_VERSION, '.', SDL_MINOR_VERSION, '.', SDL_PATCHLEVEL); BLogger::Log("SDL Revision: ", SDL_GetRevision()); auto pVersion = Mix_Linked_Version(); BLogger::Log("SDL_mixer Linked version: ", static_cast<unsigned int>(pVersion->major), '.', static_cast<unsigned int>(pVersion->minor), '.', static_cast<unsigned int>(pVersion->patch)); BLogger::Log("SDL_mixer Header version: ", MIX_MAJOR_VERSION, '.', MIX_MINOR_VERSION, '.', MIX_PATCHLEVEL); // Set OpenGL's context to 2.1 subset functionality profile. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); // Open OpenGL Window with SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) { message << "Error in SDL_Init: " << SDL_GetError(); SDL_Quit(); throw std::runtime_error(message.str()); } if (config->FullScreen) { flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if (!IsWindowResolutionSupported(config->ScreenXResolution, (config->ScreenXResolution * 3) / 4)) { config->ScreenXResolution = 640; } window = SDL_CreateWindow( GetWindowTitle().c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, config->ScreenXResolution, (config->ScreenXResolution * 3) / 4, flags); if (window == nullptr) { message << "Error in SDL_CreateWindow: " << SDL_GetError(); SDL_Quit(); throw std::runtime_error(message.str()); } // We intentionally do not use the SDL renderer. It only supports 2D // and on Windows would use DirectX and not the OpenGL backend. // Instead the OpenGL renderer is used together with ligGLEW. glContext = SDL_GL_CreateContext(window); if (glContext == nullptr) { message << "Error in SDL_GL_CreateContext: " << SDL_GetError(); SDL_Quit(); throw std::runtime_error(message.str()); } // Do updates synchronized with VSync SDL_GL_SetSwapInterval(1); auto glewReturn = glewInit(); if (glewReturn != GLEW_OK) { message << "Error in glewInit: " << glewGetErrorString(glewReturn); SDL_Quit(); throw std::runtime_error(message.str()); } BLogger::Log("GLEW version: ", glewGetString(GLEW_VERSION)); SDL_DisplayMode mode; SDL_GetWindowDisplayMode(window, &mode); BLogger::Log("SDL pixel format: ", SDL_GetPixelFormatName(mode.format)); BLogger::Log("SDL refresh rate: ", mode.refresh_rate, " Hz"); DebugPrintOpenGLVersion(); DebugPrintOpenGLContextVersion(); InitializeAudio(config->TextureName); InitializeAfterOpen(); }
modesfound.clear(); doublesfound.clear(); SDL_DisplayMode current_mode; SDL_DisplayMode desktop_mode; bool bIsRetina = false; #ifdef __APPLE__ bIsRetina = ([[NSScreen mainScreen] backingScaleFactor] > 1.0); //if(bIsRetina) printf("I AM RETINAAAAA\n"); #endif int foo = SDL_GetWindowDisplayMode( m_window, ¤t_mode ); int nib = SDL_GetDesktopDisplayMode(displayIdx, &desktop_mode); // Push the current resolution information into Lua. lua_newtable(L); lua_pushstring(L, "w"); lua_pushnumber(L, current_mode.w); lua_settable(L, -3); lua_pushstring(L, "h"); lua_pushnumber(L, current_mode.h); lua_settable(L,-3); lua_pushstring(L, "bpp");
int sdl_window_info::complete_create() { osd_dim temp(0,0); // clear out original mode. Needed on OSX if (fullscreen()) { // default to the current mode exactly temp = monitor()->position_size().dim(); // if we're allowed to switch resolutions, override with something better if (video_config.switchres) temp = pick_best_mode(); } else if (m_windowed_dim.width() > 0) { // if we have a remembered size force the new window size to it temp = m_windowed_dim; } else if (m_startmaximized) temp = get_max_bounds(video_config.keepaspect ); else temp = get_min_bounds(video_config.keepaspect ); // create the window ..... /* FIXME: On Ubuntu and potentially other Linux OS you should use * to disable panning. This has to be done before every invocation of mame. * * xrandr --output HDMI-0 --panning 0x0+0+0 --fb 0x0 * */ osd_printf_verbose("Enter sdl_info::create\n"); if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL) && !video_config.novideo) { SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* FIXME: A reminder that gamma is wrong throughout MAME. Currently, SDL2.0 doesn't seem to * support the following attribute although my hardware lists GL_ARB_framebuffer_sRGB as an extension. * * SDL_GL_SetAttribute( SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1 ); * */ m_extra_flags = SDL_WINDOW_OPENGL; } else m_extra_flags = 0; #ifdef SDLMAME_MACOSX /* FIMXE: On OSX, SDL_WINDOW_FULLSCREEN_DESKTOP seems to be more reliable. * It however creates issues with white borders, i.e. the screen clear * does not work. This happens both with opengl and accel. */ #endif // We need to workaround an issue in SDL 2.0.4 for OS X where setting the // relative mode on the mouse in fullscreen mode makes mouse events stop // It is fixed in the latest revisions so we'll assume it'll be fixed // in the next public SDL release as well #if defined(SDLMAME_MACOSX) && SDL_VERSION_ATLEAST(2, 0, 2) // SDL_HINT_MOUSE_RELATIVE_MODE_WARP is introduced in 2.0.2 SDL_version linked; SDL_GetVersion(&linked); int revision = SDL_GetRevisionNumber(); // If we're running the exact version of SDL 2.0.4 (revision 10001) from the // SDL web site, we need to work around this issue and send the warp mode hint if (SDL_VERSION_EQUALS(linked, SDL_VERSIONNUM(2, 0, 4)) && revision == 10001) { osd_printf_verbose("Using warp mode for relative mouse in OS X SDL 2.0.4\n"); SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); } #endif // create the SDL window // soft driver also used | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_MOUSE_FOCUS m_extra_flags |= (fullscreen() ? SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE); #if defined(SDLMAME_WIN32) SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); #endif // get monitor work area for centering osd_rect work = monitor()->usuable_position_size(); // create the SDL window auto sdlwindow = SDL_CreateWindow(m_title, work.left() + (work.width() - temp.width()) / 2, work.top() + (work.height() - temp.height()) / 2, temp.width(), temp.height(), m_extra_flags); //window().sdl_window() = SDL_CreateWindow(window().m_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, // width, height, m_extra_flags); if (sdlwindow == nullptr ) { if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL)) osd_printf_error("OpenGL not supported on this driver: %s\n", SDL_GetError()); else osd_printf_error("Window creation failed: %s\n", SDL_GetError()); return 1; } set_platform_window(sdlwindow); if (fullscreen() && video_config.switchres) { SDL_DisplayMode mode; //SDL_GetCurrentDisplayMode(window().monitor()->handle, &mode); SDL_GetWindowDisplayMode(platform_window(), &mode); m_original_mode->mode = mode; mode.w = temp.width(); mode.h = temp.height(); if (m_win_config.refresh) mode.refresh_rate = m_win_config.refresh; SDL_SetWindowDisplayMode(platform_window(), &mode); // Try to set mode #ifndef SDLMAME_WIN32 /* FIXME: Warp the mouse to 0,0 in case a virtual desktop resolution * is in place after the mode switch - which will most likely be the case * This is a hack to work around a deficiency in SDL2 */ SDL_WarpMouseInWindow(platform_window(), 1, 1); #endif } else { //SDL_SetWindowDisplayMode(window().sdl_window(), nullptr); // Use desktop } // show window SDL_ShowWindow(platform_window()); //SDL_SetWindowFullscreen(window->sdl_window(), 0); //SDL_SetWindowFullscreen(window->sdl_window(), window->fullscreen()); SDL_RaiseWindow(platform_window()); #ifdef SDLMAME_WIN32 if (fullscreen()) SDL_SetWindowGrab(platform_window(), SDL_TRUE); #endif // set main window if (m_index > 0) { for (auto w : osd_common_t::s_window_list) { if (w->m_index == 0) { set_main_window(std::dynamic_pointer_cast<osd_window>(w)); break; } } } else { // We must be the main window set_main_window(shared_from_this()); } // update monitor resolution after mode change to ensure proper pixel aspect monitor()->refresh(); if (fullscreen() && video_config.switchres) monitor()->update_resolution(temp.width(), temp.height()); // initialize the drawing backend if (renderer().create()) return 1; // Make sure we have a consistent state SDL_ShowCursor(0); SDL_ShowCursor(1); return 0; }
/** * Initializes OpenGL */ void SpringApp::InitOpenGL() { // reinit vsync VSync.Init(); // check if FSAA init worked fine if (globalRendering->FSAA && !MultisampleVerify()) globalRendering->FSAA = 0; // setup GL smoothing const int lineSmoothing = configHandler->GetInt("SmoothLines"); if (lineSmoothing > 0) { GLenum hint = GL_FASTEST; if (lineSmoothing >= 3) { hint = GL_NICEST; } else if (lineSmoothing >= 2) { hint = GL_DONT_CARE; } glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, hint); } const int pointSmoothing = configHandler->GetInt("SmoothPoints"); if (pointSmoothing > 0) { GLenum hint = GL_FASTEST; if (pointSmoothing >= 3) { hint = GL_NICEST; } else if (pointSmoothing >= 2) { hint = GL_DONT_CARE; } glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, hint); } // setup LOD bias factor const float lodBias = configHandler->GetFloat("TextureLODBias"); if (math::fabs(lodBias) > 0.01f) { glTexEnvf(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, lodBias ); } //FIXME not needed anymore with SDL2? if (configHandler->GetBool("FixAltTab")) { // free GL resources GLContext::Free(); // initialize any GL resources that were lost GLContext::Init(); } // setup viewport SetupViewportGeometry(); glViewport(globalRendering->viewPosX, globalRendering->viewPosY, globalRendering->viewSizeX, globalRendering->viewSizeY); gluPerspective(45.0f, globalRendering->aspectRatio, 2.8f, CGlobalRendering::MAX_VIEW_RANGE); // Initialize some GL states glShadeModel(GL_SMOOTH); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Clear Window glClearColor(0.0f,0.0f,0.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SDL_GL_SwapWindow(window); // Print Final Mode (call after SetupViewportGeometry, which updates viewSizeX/Y) SDL_DisplayMode dmode; SDL_GetWindowDisplayMode(window, &dmode); bool isBorderless = (SDL_GetWindowFlags(window) & SDL_WINDOW_BORDERLESS) != 0; LOG("[%s] video mode set to %ix%i:%ibit @%iHz %s", __FUNCTION__, globalRendering->viewSizeX, globalRendering->viewSizeY, SDL_BITSPERPIXEL(dmode.format), dmode.refresh_rate, globalRendering->fullScreen ? (isBorderless ? "(borderless)" : "") : "(windowed)"); }
/*GLOBAL FUNCTIONS*/ void NLF_screen_init() { int flags; int aux; char *str; int sdlRet; NLF_bool saydone; /*INITIALIZING SDL_IMAGE*/ flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { flags = IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { printf("\tCan't initialize SDL_image\nSDL_IMAGE ERROR: %s\n", IMG_GetError()); printf("\ttraing for TIF format... "); flags = IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); tifFlag = NLF_True; }else{ printf("done\n"); tifFlag = NLF_False; } printf("\ttraing for PNG format... \n"); flags = IMG_INIT_PNG; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); pngFlag = NLF_True; }else{ printf("done\n"); pngFlag = NLF_False; } printf("\ttraing for JPG format... \n"); flags = IMG_INIT_JPG; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); jpgFlag = NLF_True; }else{ printf("done\n"); jpgFlag = NLF_False; } if(jpgFlag == NLF_False && pngFlag == NLF_False && tifFlag == NLF_False) { printf("\tScreen module initialization has failed.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLImageInitializer, "Screen module initialization has failed", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLImageInitializer); } } }else{ jpgFlag = NLF_True; pngFlag = NLF_True; tifFlag = NLF_True; } /************************/ /*SETTING GLOBALS VARIABLES*/ ///GETTING DISPLAY INFORMATIONS aux = SDL_GetNumVideoDisplays(); if(aux < 0) { //error case printf("Fail trying to get video display number.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Fail trying to get video display number", "SDL Error: ", str, NULL); exit(aux); }else{ displayInUse = 0; printf("\n\t%d Displays avaliable, piking the number %d as pattern\n", aux, displayInUse + 1); } displayInfoUnknown = NLF_False; for(aux = 0; aux < 3; aux++) { saydone = NLF_False; if(aux == 0) sdlRet = SDL_GetCurrentDisplayMode(displayInUse, &videoMode); else if(aux == 1) sdlRet = SDL_GetDisplayMode(displayInUse, displayInUse, &videoMode); else if(aux == 2) sdlRet = SDL_GetWindowDisplayMode(displayInUse, &videoMode); if(sdlRet != 0) { if(aux == 2) { //totally unsuccessful case printf("\tSorry, impossible to get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError()); printf("\tstandard 800x600 will be set\n"); displayInfoUnknown = NLF_True; }else{ printf("\tSorry, could not get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError()); printf("\ttrying another way...\n"); saydone = NLF_True; } }else{ printf("\tcurrent display(%d) mode detected %dx%dpx @ %dhz. \n", displayInUse + 1, videoMode.w, videoMode.h, videoMode.refresh_rate); if(videoMode.w == 0 || videoMode.h == 0 || videoMode.refresh_rate == 0) { printf("\tSorry, could not get all display #%d mode information\n", displayInUse + 1); printf("\ttrying another way...\n"); saydone = NLF_True; }else{ printf("\tdone\n"); aux = 3; } } } ///**************************** /*SETTING SOME GLOBAL VARIABLES*/ camera.x = 0; camera.y = 0; if(displayInfoUnknown == NLF_False) { camera.w = 800; camera.h = 600; }else{ camera.w = videoMode.w; camera.h = videoMode.h; } screens = NULL; currentFPS = 0; //there's just no need to the FPS be greater then the display refresh rate (videoMode.refresh_rate >= 60 || videoMode.refresh_rate == 0) ? (idealFPS = 60): (idealFPS = videoMode.refresh_rate); /*******************************/ ///CREATING WINDOW SET window = SDL_CreateWindow("NorthLionFramework Game", 0, 0, camera.w, camera.h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_MAXIMIZED); if(window == NULL) { printf("\tCould not craete the window\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Could not craete the window", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we need a window .-. } //this loop will try to initialize the render the best way possible for(aux = 0; aux < 4 && window_rederer == NULL; aux++) { switch(aux) { case 0: flags = SDL_RENDERER_SOFTWARE | SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE; break; case 1: flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE; break; case 2: flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; break; case 3: flags = SDL_RENDERER_ACCELERATED; break; } if(aux > 0) printf("\ttrying flags(%d)... ", flags); window_rederer = SDL_CreateRenderer(window, -1, flags); if(window_rederer == NULL) { if(aux > 0) printf("fail\n"); if(aux != 3) { printf("\tCould not create render with all flags(%d)\n", flags); printf("\tSDL_ERROR: %s\n", SDL_GetError()); }else{ printf("\tIt was impossible to create the render.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "It was impossible to create the render", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we also need a renderer .-. } }else{ if(aux > 0) printf("done\n"); } } if(aux > 0) ///******************* ///GETTING VIDEO CARD INFORMATION aux = 0; if(SDL_GetRendererInfo(window_rederer, &rendererInfo) < 0) { printf("\tCould not get information about the renderer.\n"); printf("\tSDL_ERROR: %s\n", SDL_GetError()); rendererInfoUnknown = NLF_True; }else{ aux = 1; rendererInfoUnknown = NLF_False; } if(SDL_GetRenderDriverInfo(displayInUse, &rendererDriverInfo) < 0) { printf("\tCould not get information about the renderer driver.\n"); printf("\tSDL_ERROR: %s\n", SDL_GetError()); rendererDriverInfoUnkown = NLF_True; }else{ aux = 1; rendererDriverInfoUnkown = NLF_False; } ///****************************** /***************************/ }
static void set_video_mode() { int flags = SDL_WINDOW_OPENGL; if (g_fs_emu_video_fullscreen_mode != FULLSCREEN_WINDOW && g_window_resizable) { flags |= SDL_WINDOW_RESIZABLE; } int x = g_window_x, y = g_window_y; int w = -1, h = -1; // if (g_initial_input_grab) { // flags |= SDL_WINDOW_INPUT_GRABBED; // g_has_input_grab = 1; // } if (g_fs_emu_video_fullscreen == 1) { w = g_fullscreen_width; h = g_fullscreen_height; //w = g_window_width; //h = g_window_height; if (g_fs_emu_video_fullscreen_mode == FULLSCREEN_WINDOW) { fs_log("using fullscreen window mode\n"); //x = 0; //y = 0; //w = g_fullscreen_width; //h = g_fullscreen_height; flags |= SDL_WINDOW_BORDERLESS; FSEmuMonitor monitor; fs_emu_monitor_get_by_index(g_display, &monitor); x = monitor.rect.x; y = monitor.rect.y; w = monitor.rect.w; h = monitor.rect.h; } else if (g_fs_emu_video_fullscreen_mode == FULLSCREEN_DESKTOP) { fs_log("using fullscreen desktop mode\n"); // the width and height will not be used for the fullscreen // desktop mode, only for the window when toggling fullscreen // state #if 0 w = g_window_width; h = g_window_height; #else FSEmuMonitor monitor; fs_emu_monitor_get_by_index(g_display, &monitor); x = monitor.rect.x; y = monitor.rect.y; w = monitor.rect.w; h = monitor.rect.h; #endif flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } else { fs_log("using SDL_FULLSCREEN mode\n"); flags |= SDL_WINDOW_FULLSCREEN; } fs_log("setting (fullscreen) video mode %d %d\n", w, h); } else { w = g_window_width; h = g_window_height; fs_log("using windowed mode\n"); //SDL_putenv("SDL_VIDEO_WINDOW_POS="); fs_log("setting (windowed) video mode %d %d\n", w, h); } if (fs_config_get_boolean("window_border") == 0) { fs_log("borderless window requested\n"); flags |= SDL_WINDOW_BORDERLESS; } #if 0 Uint8 data[] = "\0"; SDL_Cursor *cursor = SDL_CreateCursor(data, data, 8, 1, 0, 0); SDL_SetCursor(cursor); #endif g_fs_ml_video_width = w; g_fs_ml_video_height = h; fs_log("[SDL] CreateWindow(x=%d, y=%d, w=%d, h=%d, flags=%d)\n", x, y, w, h, flags); g_fs_ml_window = SDL_CreateWindow(g_window_title, x, y, w, h, flags); int assume_refresh_rate = fs_config_get_int("assume_refresh_rate"); if (assume_refresh_rate != FS_CONFIG_NONE) { fs_log("[DISPLAY] Assuming host refresh rate: %d Hz (from config)\n", assume_refresh_rate); g_fs_emu_video_frame_rate_host = assume_refresh_rate; } else { SDL_DisplayMode mode; if (SDL_GetWindowDisplayMode(g_fs_ml_window, &mode) == 0) { g_fs_emu_video_frame_rate_host = mode.refresh_rate; } else { g_fs_emu_video_frame_rate_host = 0; } fs_log("[DISPLAY] Host refresh rate: %d Hz\n", g_fs_emu_video_frame_rate_host); } if (g_fs_emu_video_frame_rate_host) { g_fs_ml_target_frame_time = 1000000 / g_fs_emu_video_frame_rate_host; } g_fs_ml_context = SDL_GL_CreateContext(g_fs_ml_window); #ifdef WITH_GLEW static int glew_initialized = 0; if (!glew_initialized) { GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "[GLEW] Error: %s\n", glewGetErrorString(err)); fs_emu_fatal("[GLEW] Error initializing glew"); } fs_log("[GLEW] Version %s\n", glewGetString(GLEW_VERSION)); glew_initialized = 1; } #elif defined(WITH_GLAD) static int glad_initialized = 0; if (!glad_initialized) { if (!gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress)) { fs_emu_fatal("[GLAD] Failed to initialize OpenGL context"); } glad_initialized = 1; } #endif fs_ml_configure_window(); // FIXME: this can be removed g_fs_ml_opengl_context_stamp++; log_opengl_information(); }
static void VID_SDL_Init(void) { SDL_Surface *icon_surface; extern void InitSig(void); SDL_DisplayMode display_mode; int flags; if (glConfig.initialized == true) return; flags = SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_SHOWN; #ifdef SDL_WINDOW_ALLOW_HIGHDPI flags |= SDL_WINDOW_ALLOW_HIGHDPI; #endif if (r_fullscreen.integer <= 0) { flags &= ~SDL_WINDOW_FULLSCREEN; if (vid_win_borderless.integer <= 0) flags &= ~SDL_WINDOW_BORDERLESS; } #if defined(__linux__) InitSig(); #endif VID_SDL_InitSubSystem(); VID_SDL_GL_SetupAttributes(); VID_SetupResolution(); sdl_window = SDL_CreateWindow(WINDOW_CLASS_NAME, vid_xpos.integer, vid_ypos.integer, glConfig.vidWidth, glConfig.vidHeight, flags); icon_surface = SDL_CreateRGBSurfaceFrom((void *)ezquake_icon.pixel_data, ezquake_icon.width, ezquake_icon.height, ezquake_icon.bytes_per_pixel * 8, ezquake_icon.width * ezquake_icon.bytes_per_pixel, 0x000000FF,0x0000FF00,0x00FF0000,0xFF000000); if (icon_surface) { SDL_SetWindowIcon(sdl_window, icon_surface); SDL_FreeSurface(icon_surface); } SDL_SetWindowMinimumSize(sdl_window, 320, 240); sdl_context = SDL_GL_CreateContext(sdl_window); if (!sdl_context) { Com_Printf("Couldn't create OpenGL context: %s\n", SDL_GetError()); return; } r_swapInterval.modified = true; if (!SDL_GetWindowDisplayMode(sdl_window, &display_mode)) glConfig.displayFrequency = display_mode.refresh_rate; else glConfig.displayFrequency = 0; glConfig.colorBits = 24; // FIXME SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &glConfig.depthBits); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &glConfig.stencilBits); glConfig.vendor_string = glGetString(GL_VENDOR); glConfig.renderer_string = glGetString(GL_RENDERER); glConfig.version_string = glGetString(GL_VERSION); glConfig.extensions_string = glGetString(GL_EXTENSIONS); glConfig.initialized = true; #if defined(__linux__) InitSig(); // not clear why this is at begin & end of function #endif }
int main(int argc, char *argv[]) { GLState glState; float fov = 45.f; try { srand(time(NULL)); if (SDL_Init(SDL_INIT_VIDEO) != 0) { #ifndef __ANDROID__ std::cout << "Couldn't initialize SDL: " << SDL_GetError() << std::endl; #endif return -1; } //ask for gles2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); //SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); //with _DESKTOP sometimes nothing is drawn, only glClear seems to work glState.window = SDL_CreateWindow("PCViewer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP); if (glState.window == NULL) throw std::runtime_error(fillSDLError("Failed to create window")); glState.context = SDL_GL_CreateContext(glState.window); if (glState.context == NULL) throw std::runtime_error(fillSDLError("Failed to create context")); //SDL_GL_SetSwapInterval(1); int status = SDL_GL_MakeCurrent(glState.window, glState.context); if (status) { fprintf(stderr, "SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); } GLuint vertexShader = load_shader(vshaderSrc, GL_VERTEX_SHADER); GLuint fragmentShader = load_shader(fshaderSrc, GL_FRAGMENT_SHADER); glState.shaderProgram = glCreateProgram(); glAttachShader(glState.shaderProgram, vertexShader); glAttachShader(glState.shaderProgram, fragmentShader); glLinkProgram(glState.shaderProgram); glUseProgram(glState.shaderProgram); readPLY("bun_zipper.ply", vertices); glm::mat4 mCenterAndScale(computeCenterAndScale(vertices)); glGenBuffers(1, &glState.vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, glState.vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); //prepare fix view matrices const glm::mat4 mView = glm::lookAt( glm::vec3(0,0,5), glm::vec3(0,0,0), glm::vec3(0,1,0) ); ModelPos pcPos; SDL_Event event; bool translating = false; bool rotating = false; SDL_FingerID activeFinger; int fingerCount = 0; bool run = true; while (run) { while (SDL_PollEvent(&event)) { switch (event.type) { #ifdef __ANDROID__ //TODO: add translation (2 fingers?) case SDL_FINGERDOWN: ++fingerCount; if (!rotating) { rotating = true; activeFinger = event.tfinger.fingerId; } break; case SDL_FINGERUP: --fingerCount; if (rotating && event.tfinger.fingerId == activeFinger) rotating = false; break; case SDL_FINGERMOTION: if (rotating && fingerCount == 1 && event.tfinger.fingerId == activeFinger) { pcPos.rx += event.tfinger.dy * 5; pcPos.ry += event.tfinger.dx * 5; } break; case SDL_MULTIGESTURE: fov -= event.mgesture.dDist * 100; break; #else case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) translating = true; else if (event.button.button == SDL_BUTTON_RIGHT) rotating = true; break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) translating = false; else if (event.button.button == SDL_BUTTON_RIGHT) rotating = false; break; case SDL_MOUSEWHEEL: if (event.wheel.y > 0) fov += 1; else if (event.wheel.y < 0) fov -= 1; break; case SDL_MOUSEMOTION: if (translating) { pcPos.tx += event.motion.xrel * .01; pcPos.ty -= event.motion.yrel * .01; } else if (rotating) { pcPos.rx += event.motion.yrel * .01; pcPos.ry += event.motion.xrel * .01; } break; #endif case SDL_QUIT: run = false; break; } } SDL_DisplayMode dm; SDL_GetWindowDisplayMode(glState.window, &dm); const glm::mat4 mProj = glm::perspective(fov, float(dm.w) / dm.h, 0.1f, 100.0f); const glm::mat4 mvp = mProj * mView * mModelFromPos(pcPos) * mCenterAndScale; render(glState, mvp); SDL_Delay(10); } } catch (const std::exception &e) { #ifndef __ANDROID__ std::cerr << "Error: " << e.what() << std::endl; #endif } if (glState.context) SDL_GL_DeleteContext(glState.context); if (glState.window) SDL_DestroyWindow(glState.window); SDL_Quit(); return 0; }
/* =============== GLimp_DetectAvailableModes =============== */ static bool GLimp_DetectAvailableModes(void) { int i, j; char buf[ MAX_STRING_CHARS ] = { 0 }; SDL_Rect *modes; int numModes = 0; int display = SDL_GetWindowDisplayIndex( screen ); SDL_DisplayMode windowMode; if( SDL_GetWindowDisplayMode( screen, &windowMode ) < 0 ) { Com_Printf( "Couldn't get window display mode, no resolutions detected (%s).\n", SDL_GetError() ); return false; } int numDisplayModes = SDL_GetNumDisplayModes( display ); if ( numDisplayModes < 0 ) Com_Error( ERR_FATAL, "SDL_GetNumDisplayModes() FAILED (%s)", SDL_GetError() ); modes = (SDL_Rect *)SDL_calloc( (size_t)numDisplayModes, sizeof( SDL_Rect ) ); if ( !modes ) Com_Error( ERR_FATAL, "Out of memory" ); for( i = 0; i < numDisplayModes; i++ ) { SDL_DisplayMode mode; if( SDL_GetDisplayMode( display, i, &mode ) < 0 ) continue; if( !mode.w || !mode.h ) { Com_Printf( "Display supports any resolution\n" ); SDL_free( modes ); return true; } if( windowMode.format != mode.format ) continue; // SDL can give the same resolution with different refresh rates. // Only list resolution once. for( j = 0; j < numModes; j++ ) { if( mode.w == modes[ j ].w && mode.h == modes[ j ].h ) break; } if( j != numModes ) continue; modes[ numModes ].w = mode.w; modes[ numModes ].h = mode.h; numModes++; } if( numModes > 1 ) qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes ); for( i = 0; i < numModes; i++ ) { const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h ); if( strlen( newModeString ) < (int)sizeof( buf ) - strlen( buf ) ) Q_strcat( buf, sizeof( buf ), newModeString ); else Com_Printf( "Skipping mode %ux%u, buffer too small\n", modes[ i ].w, modes[ i ].h ); } if( *buf ) { buf[ strlen( buf ) - 1 ] = 0; Com_Printf( "Available modes: '%s'\n", buf ); Cvar_Set( "r_availableModes", buf ); } SDL_free( modes ); return true; }
int lite3d_video_open(lite3d_video_settings *settings, int hideConsole) { uint32_t windowFlags; SDL_DisplayMode displayMode; SDL_assert(settings); #ifdef PLATFORM_Windows if (hideConsole) { FreeConsole(); } #endif SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, settings->colorBits > 24 ? 8 : 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); #ifndef GLES /* Specify openGL context */ if (settings->FSAA > 1) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, settings->FSAA); } if (settings->glProfile == LITE3D_GL_PROFILE_CORE) { SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "Setting Core OpenGL Profile"); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); set_opengl_version(settings); } else if (settings->glProfile == LITE3D_GL_PROFILE_COMPATIBILITY) { SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "Setting Compatibility OpenGL Profile"); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); set_opengl_version(settings); } else { SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "Using Default OpenGL Profile"); SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "Using Default OpenGL Version"); } #endif #ifdef WITH_GLES2 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #elif WITH_GLES3 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; if (settings->fullscreen) { windowFlags |= SDL_WINDOW_FULLSCREEN; windowFlags |= SDL_WINDOW_BORDERLESS; } if (settings->screenWidth == 0 || settings->screenHeight == 0) { if (!lite3d_video_get_display_size( &settings->screenWidth, &settings->screenHeight)) { SDL_LogWarn( SDL_LOG_CATEGORY_APPLICATION, "lite3d_video_get_display_size failed"); return LITE3D_FALSE; } } /* setup render window */ gRenderWindow = SDL_CreateWindow( settings->caption, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, settings->screenWidth, settings->screenHeight, windowFlags); if (!gRenderWindow) { SDL_LogCritical( SDL_LOG_CATEGORY_APPLICATION, "%s: SDL_CreateWindow failed..", LITE3D_CURRENT_FUNCTION); return LITE3D_FALSE; } SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "%s: render window created %dx%d (%s)", LITE3D_CURRENT_FUNCTION, settings->screenWidth, settings->screenHeight, settings->fullscreen ? "fullscreen" : "windowed"); /* Create an OpenGL context associated with the window. */ gGLContext = SDL_GL_CreateContext(gRenderWindow); if (!gGLContext) { SDL_LogCritical( SDL_LOG_CATEGORY_APPLICATION, "%s: GL Context create failed..", LITE3D_CURRENT_FUNCTION); return LITE3D_FALSE; } /* set gl context */ SDL_GL_MakeCurrent(gRenderWindow, gGLContext); SDL_GetWindowDisplayMode(gRenderWindow, &displayMode); SDL_LogInfo( SDL_LOG_CATEGORY_APPLICATION, "%s: selected pixel format: %d bpp, %s", LITE3D_CURRENT_FUNCTION, SDL_BITSPERPIXEL(displayMode.format), SDL_GetPixelFormatName(displayMode.format)); SDL_GL_SetSwapInterval(settings->vsync ? 1 : 0); if (!init_gl_extensions(settings)) { SDL_LogWarn( SDL_LOG_CATEGORY_APPLICATION, "init_gl_extensions failed"); lite3d_video_close(); return LITE3D_FALSE; } if (!settings->hidden) { SDL_ShowWindow(gRenderWindow); } return LITE3D_TRUE; }