int main( int argc, char *argv[ ] ) { SDL_Window *window; if( SDL_Init( SDL_INIT_VIDEO ) == -1 ) { printf( "Can't init SDL: %s\n", SDL_GetError( ) ); return EXIT_FAILURE; } if( SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) == -1) { printf( "Can't set attribute DOUBLE BUFFER : %s\n", SDL_GetError( ) ); return EXIT_FAILURE; } atexit( SDL_Quit ); SDL_Surface *surface; window = SDL_CreateWindow("Ma fenĂȘtre de jeu", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL ); SDL_GLContext *glcontext; glcontext = SDL_GL_CreateContext(window); int nValue; if( SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &nValue) < 0) { printf("Echec de recuperation du parametre SDL_GL_DOUBLEBUFFER : %s\n", SDL_GetError()); return (EXIT_FAILURE); } // assurons nous que le mode "double buffer" est bien actif if(nValue != 1) { printf("Erreur : SDL_GL_DOUBLEBUFFER inactif : %d\n", nValue); return (EXIT_FAILURE); } SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &nValue); printf("Depth %d\n", nValue); surface = SDL_GetWindowSurface(window); if( surface == NULL ) { printf( "Can't set video mode: %s\n", SDL_GetError( ) ); return EXIT_FAILURE; } opengl_init(); // Main loop SDL_Event event; while(1) { opengl_clear(window); // Check for messages if (SDL_PollEvent(&event)) { // Check for the quit message switch (event.type) { case SDL_QUIT: SDL_Quit(); return EXIT_SUCCESS;// Quit the program break; case SDL_KEYUP: case SDL_KEYDOWN: //printf("keydown %d\n", event.key.keysym.sym); switch(event.key.keysym.sym) { case SDLK_DOWN: t_y += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("y = %f\n", t_y); break; case SDLK_UP: t_y -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("y = %f\n", t_y); break; case SDLK_LEFT: t_x += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("y = %f\n", t_x); break; case SDLK_RIGHT: t_x -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("x = %f\n", t_x); break; case SDLK_PAGEUP: t_z += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("z = %f\n", t_z); break; case SDLK_PAGEDOWN: t_z -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0); printf("z = %f\n", t_z); break; case SDLK_ESCAPE: SDL_Quit(); return EXIT_SUCCESS;// Quit the program break; } //printf("speed %f\n", rotationspeed); break; } } uint32_t new_tick = SDL_GetTicks(); if(new_tick - delay > 100) { delay = new_tick; rotation += rotationspeed; if(rotation > 360) rotation -= 360; if(rotation < 0) rotation += 360; //printf("rotation of %f\n", rotation); } glRotatef(rotation, 1.0f, 1.5f, 0.0f); draw_cube(); //Swap the GL bufers, front and back. SDL_GL_SwapWindow(window); } // Tell the SDL to clean up and shut down SDL_Quit(); return EXIT_SUCCESS; }
std::unique_ptr<os::OpenGLContext> SDLGraphicsOperations::createOpenGLContext(const os::OpenGLContextAttributes& attrs, uint32_t width, uint32_t height) { mprintf((" Initializing SDL video...\n")); #ifdef SCP_UNIX // Slight hack to make Mesa advertise S3TC support without libtxc_dxtn setenv("force_s3tc_enable", "true", 1); #endif if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { Error(LOCATION, "Couldn't init SDL video: %s", SDL_GetError()); return nullptr; } SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attrs.red_size); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attrs.green_size); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, attrs.blue_size); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, attrs.depth_size); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, attrs.stencil_size); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, (attrs.multi_samples == 0) ? 0 : 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, attrs.multi_samples); mprintf((" Requested SDL Video values = R: %d, G: %d, B: %d, depth: %d, stencil: %d, double-buffer: %d, FSAA: %d\n", attrs.red_size, attrs.green_size, attrs.blue_size, attrs.depth_size, attrs.stencil_size, 1, attrs.multi_samples)); uint32_t windowflags = SDL_WINDOW_OPENGL; if (Cmdline_fullscreen_window) { windowflags |= SDL_WINDOW_BORDERLESS; } uint display = os_config_read_uint("Video", "Display", 0); SDL_Window* window = SDL_CreateWindow(Osreg_title, SDL_WINDOWPOS_CENTERED_DISPLAY(display), SDL_WINDOWPOS_CENTERED_DISPLAY(display), width, height, windowflags); if (window == nullptr) { Error(LOCATION, "Could not create window: %s\n", SDL_GetError()); return nullptr; } os_set_window(window); auto ctx = SDL_GL_CreateContext(os_get_window()); if (ctx == nullptr) { Error(LOCATION, "Could not create OpenGL Context: %s\n", SDL_GetError()); return nullptr; } int r, g, b, depth, stencil, db, fsaa_samples; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &db); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fsaa_samples); mprintf((" Actual SDL Video values = R: %d, G: %d, B: %d, depth: %d, stencil: %d, double-buffer: %d, FSAA: %d\n", r, g, b, depth, stencil, db, fsaa_samples)); return std::unique_ptr<os::OpenGLContext>(new SDLOpenGLContext(ctx)); }
int main( int argc, char **argv ) { MemStartCheck(); { char* test = new char[16]; delete [] test; } SDL_Surface *surface = 0; // SDL initialization steps. if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK ) < 0 ) { fprintf( stderr, "SDL initialization failed: %s\n", SDL_GetError( ) ); exit( 1 ); } SDL_EnableKeyRepeat( 0, 0 ); SDL_EnableUNICODE( 1 ); const SDL_version* sversion = SDL_Linked_Version(); GLOUTPUT(( "SDL: major %d minor %d patch %d\n", sversion->major, sversion->minor, sversion->patch )); 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); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8); if ( multisample ) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, multisample ); } int videoFlags = SDL_OPENGL; /* Enable OpenGL in SDL */ videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */ if ( fullscreen ) videoFlags |= SDL_FULLSCREEN; else videoFlags |= SDL_RESIZABLE; #ifdef TEST_ROTATION screenWidth = SCREEN_WIDTH; screenHeight = SCREEN_HEIGHT; #else screenWidth = SCREEN_HEIGHT; screenHeight = SCREEN_WIDTH; #endif if ( argc == 3 ) { screenWidth = atoi( argv[1] ); screenHeight = atoi( argv[2] ); if ( screenWidth <= 0 ) screenWidth = IPOD_SCREEN_WIDTH; if ( screenHeight <= 0 ) screenHeight = IPOD_SCREEN_HEIGHT; } // Note that our output surface is rotated from the iPod. //surface = SDL_SetVideoMode( IPOD_SCREEN_HEIGHT, IPOD_SCREEN_WIDTH, 32, videoFlags ); surface = SDL_SetVideoMode( screenWidth, screenHeight, 32, videoFlags ); GLASSERT( surface ); int stencil = 0; int depth = 0; SDL_GL_GetAttribute( SDL_GL_STENCIL_SIZE, &stencil ); glGetIntegerv( GL_DEPTH_BITS, &depth ); GLOUTPUT(( "SDL surface created. w=%d h=%d bpp=%d stencil=%d depthBits=%d\n", surface->w, surface->h, surface->format->BitsPerPixel, stencil, depth )); /* Verify there is a surface */ if ( !surface ) { fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); exit( 1 ); } SDL_JoystickEventState(SDL_ENABLE); SDL_Joystick* joystick = SDL_JoystickOpen(0); if ( joystick ) { GLOUTPUT(( "Joystick '%s' open.\n", SDL_JoystickName(0) )); } int r = glewInit(); GLASSERT( r == GL_NO_ERROR ); // Calling this seems to confuse my ATI driver and cause lag / event back up? //#ifdef TEST_FULLSPEED // wglSwapIntervalEXT( 0 ); // vsync //#else // wglSwapIntervalEXT( 1 ); // vsync //#endif const unsigned char* vendor = glGetString( GL_VENDOR ); const unsigned char* renderer = glGetString( GL_RENDERER ); const unsigned char* version = glGetString( GL_VERSION ); GLOUTPUT(( "OpenGL vendor: '%s' Renderer: '%s' Version: '%s'\n", vendor, renderer, version )); Audio_Init(); bool done = false; bool zooming = false; SDL_Event event; float yRotation = 45.0f; grinliz::Vector2I mouseDown = { 0, 0 }; grinliz::Vector2I prevMouseDown = { 0, 0 }; U32 prevMouseDownTime = 0; int zoomX = 0; int zoomY = 0; void* game = 0; bool mapMakerMode = false; WIN32_FIND_DATA findFileData; HANDLE h; h = FindFirstFile( ".\\mods\\*.xwdb", &findFileData ); if ( h != INVALID_HANDLE_VALUE ) { BOOL findResult = TRUE; while( findResult && nModDB < GAME_MAX_MOD_DATABASES ) { grinliz::GLString* str = new grinliz::GLString( ".\\mods\\" ); str->append( findFileData.cFileName ); databases[nModDB++] = str; GameAddDatabase( str->c_str() ); findResult = FindNextFile( h, &findFileData ); } FindClose( h ); } if ( argc > 3 ) { // -- MapMaker -- // Engine::mapMakerMode = true; TileSetDesc desc; desc.set = "FARM"; desc.size = 16; desc.type = "TILE"; desc.variation = 0; if ( argc > 2 ) { desc.set = argv[2]; GLASSERT( strlen( desc.set ) == 4 ); } if ( argc > 3 ) { desc.size = atol( argv[3] ); GLASSERT( desc.size == 16 || desc.size == 32 || desc.size == 48 || desc.size == 64 ); } if ( argc > 4 ) { desc.type = argv[4]; GLASSERT( strlen( desc.type ) == 4 ); } if ( argc > 5 ) { desc.variation = atol( argv[5] ); GLASSERT( desc.variation >= 0 && desc.variation < 100 ); } game = new Game( screenWidth, screenHeight, rotation, ".\\resin\\", desc ); mapMakerMode = true; } else { game = NewGame( screenWidth, screenHeight, rotation, ".\\", tvMode ); } #if SEND_CRASH_LOGS // Can't call this until after the game is created! if ( !SettingsManager::Instance()->GetSuppressCrashLog() ) { // Check for a "didn't crash" file. FILE* fp = fopen( "UFO_Running.txt", "r" ); if ( fp ) { fseek( fp, 0, SEEK_END ); long len = ftell( fp ); if ( len > 1 ) { // Wasn't deleted. PostCurrentGame(); } fclose( fp ); } } { FILE* fp = fopen( "UFO_Running.txt", "w" ); if ( fp ) { fprintf( fp, "Game running." ); fclose( fp ); } } #endif #ifndef TEST_FULLSPEED SDL_TimerID timerID = SDL_AddTimer( TIME_BETWEEN_FRAMES, TimerCallback, 0 ); #endif bool L2Down = false; bool R2Down = false; grinliz::Vector2F joystickAxis[2] = { 0, 0 }; // ---- Main Loop --- // #ifdef TEST_FULLSPEED while ( !done ) { if ( SDL_PollEvent( &event ) ) #else while ( !done && SDL_WaitEvent( &event ) ) #endif { // The user event shouldn't be duplicated...if there are 2, pull out the dupe. if ( event.type == SDL_USEREVENT ) { SDL_Event e; while( true ) { int n = SDL_PeepEvents( &e, 1, SDL_PEEKEVENT, SDL_ALLEVENTS ); if ( n == 1 && e.type == SDL_USEREVENT ) { SDL_PeepEvents( &e, 1, SDL_GETEVENT, SDL_ALLEVENTS ); } else { break; } } } switch( event.type ) { case SDL_VIDEORESIZE: screenWidth = event.resize.w; screenHeight = event.resize.h; surface = SDL_SetVideoMode( screenWidth, screenHeight, 32, videoFlags ); GameDeviceLoss( game ); GameResize( game, event.resize.w, event.resize.h, rotation ); break; /* A: 0 Triggers: axis=2 X: 2 Y: 3 B: 1 L1: 4 R1: 5 */ case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: //GLOUTPUT(( "Button %d.\n", event.jbutton.button )); switch( event.jbutton.button ) { case 0: GameJoyButton( game, GAME_JOY_BUTTON_DOWN, event.type == SDL_JOYBUTTONDOWN ); break; case 1: GameJoyButton( game, GAME_JOY_BUTTON_RIGHT, event.type == SDL_JOYBUTTONDOWN ); break; case 2: GameJoyButton( game, GAME_JOY_BUTTON_LEFT, event.type == SDL_JOYBUTTONDOWN ); break; case 3: GameJoyButton( game, GAME_JOY_BUTTON_UP, event.type == SDL_JOYBUTTONDOWN ); break; case 4: GameJoyButton( game, GAME_JOY_L1, event.type == SDL_JOYBUTTONDOWN ); break; case 5: GameJoyButton( game, GAME_JOY_R1, event.type == SDL_JOYBUTTONDOWN ); break; } break; case SDL_JOYAXISMOTION: //GLOUTPUT(( "Axis %d to %d.\n", event.jaxis.axis, event.jaxis.value )); // axis2, posL, negR if ( event.jaxis.axis == 2 ) { int value = event.jaxis.value; static const int T = 10*1000; if ( value > 10 ) { if ( !L2Down && value > T ) { L2Down = true; GameJoyButton( game, GAME_JOY_L2, true ); } else if ( L2Down && value < T ) { L2Down = false; GameJoyButton( game, GAME_JOY_L2, false ); } } else if ( value < -10 ) { if ( !R2Down && value < -T ) { R2Down = true; GameJoyButton( game, GAME_JOY_R2, true ); } else if ( R2Down && value > -T ) { R2Down = false; GameJoyButton( game, GAME_JOY_R2, false ); } } } else { int value = event.jaxis.value; double normal = (double)value/32768.0f; int axis = -1; int stick = -1; switch( event.jaxis.axis ) { case 0: axis=0; stick=0; break; case 1: axis=1; stick=0; normal *= -1.0; break; case 3: axis=1; stick=1; normal *= -1.0f; break; case 4: axis=0; stick=1; break; default: break; } if ( axis >= 0 && stick >= 0 ) { joystickAxis[stick].X(axis) = (float)normal; } } break; case SDL_JOYHATMOTION: GameJoyDPad( game, event.jhat.value ); break; case SDL_KEYDOWN: { SDLMod sdlMod = SDL_GetModState(); if ( mapMakerMode && event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9 ) { int index = 0; switch ( event.key.keysym.sym ) { case SDLK_1: index = 0; break; case SDLK_2: index = 1; break; case SDLK_3: index = 2; break; case SDLK_4: index = 3; break; case SDLK_5: index = 4; break; case SDLK_6: index = 5; break; case SDLK_7: index = 6; break; case SDLK_8: index = 7; break; case SDLK_9: index = 8; break; case SDLK_0: index = 9; break; }; const U8* light = ((Game*)game)->engine->GetMap()->DayTime() ? dayLight : nightLight; static const float INV = 1.0f/255.0f; U8 r = light[index*3+0]; U8 g = light[index*3+1]; U8 b = light[index*3+2]; if ( sdlMod & sdlMod & ( KMOD_LSHIFT | KMOD_RSHIFT ) ) { if ( index < 6 ) { // Average with shade. r = (light[index*3+0] + light[SHADE*3+0]) / 2; g = (light[index*3+1] + light[SHADE*3+1]) / 2; b = (light[index*3+2] + light[SHADE*3+2]) / 2; } else if ( index > 6 ) { // make darker (index 6 is the darkest. SHIFT does nothing.) int m = index-1; r = (light[index*3+0] + light[m*3+0]) / 2; g = (light[index*3+1] + light[m*3+1]) / 2; b = (light[index*3+2] + light[m*3+2]) / 2; } } ((Game*)game)->SetLightMap( (float)r * INV, (float)g * INV, (float)b * INV ); } switch ( event.key.keysym.sym ) { case SDLK_ESCAPE: { //int handled = GameHotKey( game, GAME_HK_BACK ); #ifdef DEBUG // only escape out in debug mode // if ( !handled ) done = true; #endif } break; case SDLK_F4: if ( sdlMod & ( KMOD_RALT | KMOD_LALT ) ) done = true; break; #ifdef SIM_GAMEPAD case SDLK_RIGHT: GameJoyDPad( game, GAME_JOY_DPAD_RIGHT ); break; case SDLK_LEFT: GameJoyDPad( game, GAME_JOY_DPAD_LEFT ); break; case SDLK_UP: GameJoyDPad( game, GAME_JOY_DPAD_UP ); break; case SDLK_DOWN: GameJoyDPad( game, GAME_JOY_DPAD_DOWN ); break; case SDLK_1: GameJoyButton( game, 1, true ); break; case SDLK_2: GameJoyButton( game, 2, true ); break; case SDLK_3: GameJoyButton( game, 3, true ); break; case SDLK_4: GameJoyButton( game, 4, true ); break; #else case SDLK_RIGHT: if ( !mapMakerMode ) { if ( sdlMod & (KMOD_RCTRL|KMOD_LCTRL) ) GameHotKey( game, GAME_HK_ROTATE_CW ); else GameHotKey( game, GAME_HK_NEXT_UNIT ); } break; case SDLK_LEFT: if ( !mapMakerMode ) { if ( sdlMod & (KMOD_RCTRL|KMOD_LCTRL) ) GameHotKey( game, GAME_HK_ROTATE_CCW ); else GameHotKey( game, GAME_HK_PREV_UNIT ); } break; #endif case SDLK_u: if ( mapMakerMode ) { ((Game*)game)->engine->camera.SetTilt( -90.0f ); ((Game*)game)->engine->camera.SetPosWC( 8.f, 90.f, 8.f ); ((Game*)game)->engine->camera.SetYRotation( 0.0f ); } else { GameHotKey( game, GAME_HK_TOGGLE_ROTATION_UI | GAME_HK_TOGGLE_NEXT_UI ); } break; case SDLK_o: if ( mapMakerMode ) { cameraIso = !cameraIso; ((Game*)game)->engine->CameraIso( cameraIso, true, (float)((Game*)game)->engine->GetMap()->Width(), (float)((Game*)game)->engine->GetMap()->Height() ); } break; case SDLK_s: if ( mapMakerMode ) { ((Game*)game)->SuppressText( true ); } GameDoTick( game, SDL_GetTicks() ); SDL_GL_SwapBuffers(); if ( mapMakerMode ) { ((Game*)game)->SuppressText( false ); } ScreenCapture( "cap" ); break; case SDLK_l: if ( mapMakerMode ) { const Surface* lightmap = ((Game*)game)->engine->GetMap()->GetLightMap(); SaveLightMap( lightmap ); } break; case SDLK_d: GameHotKey( game, GAME_HK_TOGGLE_DEBUG_TEXT ); break; case SDLK_DELETE: if ( mapMakerMode ) ((Game*)game)->DeleteAtSelection(); break; case SDLK_KP9: if ( mapMakerMode ) ((Game*)game)->RotateSelection( -1 ); break; case SDLK_r: case SDLK_KP7: if ( mapMakerMode ) ((Game*)game)->RotateSelection( 1 ); break; case SDLK_KP8: if ( mapMakerMode ) ((Game*)game)->DeltaCurrentMapItem(16); break; case SDLK_KP5: if ( mapMakerMode ) ((Game*)game)->DeltaCurrentMapItem(-16); break; case SDLK_KP6: if ( mapMakerMode ) ((Game*)game)->DeltaCurrentMapItem(1); break; case SDLK_KP4: if ( mapMakerMode ) ((Game*)game)->DeltaCurrentMapItem(-1); break; case SDLK_p: //if ( mapMakerMode ) { int pathing = (((Game*)game)->ShowingPathing() + 1) % 3; ((Game*)game)->ShowPathing( pathing ); } break; case SDLK_t: if ( mapMakerMode ) ((Game*)game)->engine->GetMap()->SetDayTime( !((Game*)game)->engine->GetMap()->DayTime() ); break; case SDLK_v: ((Game*)game)->ToggleTV(); break; case SDLK_m: if ( mapMakerMode ) ((Game*)game)->engine->EnableMetadata( !((Game*)game)->engine->IsMetadataEnabled() ); break; default: break; } /* GLOUTPUT(( "fov=%.1f rot=%.1f h=%.1f\n", game->engine.fov, game->engine.camera.Tilt(), game->engine.camera.PosWC().y )); */ } break; #ifdef SIM_GAMEPAD case SDL_KEYUP: { switch ( event.key.keysym.sym ) { case SDLK_1: GameJoyButton( game, 1, false ); break; case SDLK_2: GameJoyButton( game, 2, false ); break; case SDLK_3: GameJoyButton( game, 3, false ); break; case SDLK_4: GameJoyButton( game, 4, false ); break; } } break; #endif case SDL_MOUSEBUTTONDOWN: { int x, y; TransformXY( event.button.x, event.button.y, &x, &y ); mouseDown.Set( event.button.x, event.button.y ); if ( event.button.button == 1 ) { GameTap( game, GAME_TAP_DOWN, x, y ); } else if ( event.button.button == 3 ) { GameTap( game, GAME_TAP_CANCEL, x, y ); zooming = true; //GameCameraRotate( game, GAME_ROTATE_START, 0.0f ); SDL_GetRelativeMouseState( &zoomX, &zoomY ); } } break; case SDL_MOUSEBUTTONUP: { int x, y; TransformXY( event.button.x, event.button.y, &x, &y ); if ( event.button.button == 3 ) { zooming = false; } if ( event.button.button == 1 ) { GameTap( game, GAME_TAP_UP, x, y ); } } break; case SDL_MOUSEMOTION: { SDL_GetRelativeMouseState( &zoomX, &zoomY ); int state = SDL_GetMouseState(NULL, NULL); int x, y; TransformXY( event.button.x, event.button.y, &x, &y ); if ( state & SDL_BUTTON(1) ) { GameTap( game, GAME_TAP_MOVE, x, y ); } else if ( zooming && (state & SDL_BUTTON(3)) ) { float deltaZoom = 0.01f * (float)zoomY; GameZoom( game, GAME_ZOOM_DISTANCE, deltaZoom ); GameCameraRotate( game, (float)(zoomX)*0.5f ); } else if ( ( ( state & SDL_BUTTON(1) ) == 0 ) ) { ((Game*)game)->MouseMove( x, y ); } } break; case SDL_QUIT: { done = true; } break; case SDL_USEREVENT: { glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); for( int stick=0; stick<2; ++stick ) { if ( joystickAxis[stick].x || joystickAxis[stick].y ) { GameJoyStick( game, stick, joystickAxis[stick].x, joystickAxis[stick].y ); } } GameDoTick( game, SDL_GetTicks() ); SDL_GL_SwapBuffers(); int databaseID=0, size=0, offset=0; // FIXME: account for databaseID when looking up sound. while ( GamePopSound( game, &databaseID, &offset, &size ) ) { Audio_PlayWav( "./res/uforesource.db", offset, size ); } }; default: break; } #ifdef TEST_FULLSPEED } glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); GameDoTick( game, SDL_GetTicks() ); SDL_GL_SwapBuffers(); } #else }
void CRenderManager::InitGL() { // VSYNC OFF SDL_GL_SetSwapInterval(0); ogl_LoadFunctions(); // DEBUG OPENGL... not ready yet //if (InitGLDebugFunctions()) CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"OpenGL Error Checking: ENABLED"); int l_red, l_green, l_blue, l_alpha; SDL_GL_GetAttribute(SDL_GL_RED_SIZE,&l_red); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE,&l_green); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE,&l_blue); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE,&l_alpha); CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"Framebuffer Bytes Info-> R:%d G:%d B:%d: A:%d",l_red, l_green, l_blue, l_alpha); char *l_vendor = (char*) glGetString(GL_VENDOR); char *l_renderer =(char*) glGetString(GL_RENDERER); char *l_version = (char*)glGetString(GL_VERSION); char *l_glsl = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION); CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"Renderer: %s", l_renderer); CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"Vendor: %s", l_vendor); CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"Version: %s", l_version); CCoreEngine::Instance().GetLogManager().LogOutput( LOG_INFO, LOGSUB_VIDEO,"GLSL: %s", l_glsl); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // TODO: Set antialiasing/multisampling /*glEnable( GL_MULTISAMPLE ); glEnable( GL_LINE_SMOOTH ); glEnable( GL_POLYGON_SMOOTH ); glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST ); */ /*set our viewing volume. */ glViewport( 0, 0, m_Window->GetWidth(), m_Window->GetHeight()); /* Set our perspective */ /* * ________ (width,height) * | | * | | * | | * |________| * (0,0) * */ glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho(0, (GLfloat) m_Window->GetWidth(), 0, (GLfloat) m_Window->GetHeight(), -1000, 1000); /* Make sure we're chaning the model view and not the projection */ glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); }
bool fxwt::init_graphics(GraphicsInitParameters *gparams) { info("Initializing SDL"); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE) == -1) { error("%s: Could not initialize SDL library.", __func__); return false; } if(!gparams->fullscreen) { const SDL_VideoInfo *vid_inf = SDL_GetVideoInfo(); gparams->bpp = vid_inf->vfmt->BitsPerPixel; } info("Trying to set video mode %dx%dx%d, d:%d s:%d %s", gparams->x, gparams->y, gparams->bpp, gparams->depth_bits, gparams->stencil_bits, gparams->fullscreen ? "fullscreen" : "windowed"); int rbits, gbits, bbits; switch(gparams->bpp) { case 32: rbits = gbits = bbits = 8; break; case 16: rbits = bbits = 5; gbits = 6; break; default: error("%s: Tried to set unsupported pixel format: %d bpp", __func__, gparams->bpp); return false; } SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rbits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, gbits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, bbits); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, gparams->depth_bits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, gparams->stencil_bits); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); unsigned long flags = SDL_OPENGL; if(gparams->fullscreen) flags |= SDL_FULLSCREEN; if(!SDL_SetVideoMode(gparams->x, gparams->y, gparams->bpp, flags)) { if(gparams->depth_bits == 32) gparams->depth_bits = 24; SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, gparams->depth_bits); if(!SDL_SetVideoMode(gparams->x, gparams->y, gparams->bpp, flags)) { error("%s: Could not set requested video mode", __func__); } } // now check the actual video mode we got int arbits, agbits, abbits, azbits, astencilbits; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &arbits); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &agbits); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &abbits); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &azbits); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &astencilbits); info("Initialized video mode:"); info(" bpp: %d (%d%d%d)", arbits + agbits + abbits, arbits, agbits, abbits); info("zbuffer: %d", azbits); info("stencil: %d", astencilbits); /* if the dont_care_flags does not contain DONT_CARE_BPP and our color bits * does not match, we should return failure, however we test against * the difference allowing a +/-1 difference in order to allow for 16bpp * formats of either 565 or 555 and consider them equal. */ if(!(gparams->dont_care_flags & DONT_CARE_BPP) && abs(arbits - rbits) > 1 && abs(agbits - gbits) > 1 && abs(abbits - bbits) > 1) { error("%s: Could not set requested exact bpp mode", __func__); return false; } // now if we don't have DONT_CARE_DEPTH in the dont_care_flags check for // exact depth buffer format, however consider 24 and 32 bit the same if(!(gparams->dont_care_flags & DONT_CARE_DEPTH) && azbits != gparams->depth_bits) { if(!((gparams->depth_bits == 32 && azbits == 24) || (gparams->depth_bits == 24 && azbits == 32))) { error("%s: Could not set requested exact zbuffer depth", __func__); return false; } } // if we don't have DONT_CARE_STENCIL make sure we have the stencil format // that was asked. if(!(gparams->dont_care_flags & DONT_CARE_STENCIL) && astencilbits != gparams->stencil_bits) { error("%s: Could not set exact stencil format", __func__); return false; } return true; }
Graphics::PixelBuffer SurfaceSdlGraphicsManager::setupScreen(uint screenW, uint screenH, bool fullscreen, bool accel3d) { uint32 sdlflags; int bpp; closeOverlay(); #ifdef USE_OPENGL _opengl = accel3d; _antialiasing = 0; #endif _fullscreen = fullscreen; ConfMan.registerDefault("fullscreen_res", "desktop"); const Common::String &fsres = ConfMan.get("fullscreen_res"); if (fsres != "desktop") { uint newW, newH; int converted = sscanf(fsres.c_str(), "%ux%u", &newW, &newH); if (converted == 2) { _desktopW = newW; _desktopH = newH; } else { warning("Could not parse 'fullscreen_res' option: expected WWWxHHH, got %s", fsres.c_str()); } } ConfMan.registerDefault("aspect_ratio", true); _lockAspectRatio = ConfMan.getBool("aspect_ratio"); uint fbW = screenW; uint fbH = screenH; _gameRect = Math::Rect2d(Math::Vector2d(0, 0), Math::Vector2d(1, 1)); #ifdef USE_OPENGL bool framebufferSupported = false; // Use the desktop resolution for fullscreen when possible if (_fullscreen) { if (g_engine->hasFeature(Engine::kSupportsArbitraryResolutions)) { // If the game supports arbitrary resolutions, use the desktop mode as the game mode screenW = _desktopW; screenH = _desktopH; } else if (_opengl) { // If available, draw to a framebuffer and scale it to the desktop resolution #ifndef AMIGAOS // Spawn a 32x32 window off-screen SDL_putenv(const_cast<char *>("SDL_VIDEO_WINDOW_POS=9000,9000")); SDL_SetVideoMode(32, 32, 0, SDL_OPENGL); SDL_putenv(const_cast<char *>("SDL_VIDEO_WINDOW_POS=centered")); Graphics::initExtensions(); framebufferSupported = Graphics::isExtensionSupported("GL_EXT_framebuffer_object"); if (_fullscreen && framebufferSupported) { screenW = _desktopW; screenH = _desktopH; if (_lockAspectRatio) { float scale = MIN(_desktopH / float(fbH), _desktopW / float(fbW)); float scaledW = scale * (fbW / float(_desktopW)); float scaledH = scale * (fbH / float(_desktopH)); _gameRect = Math::Rect2d( Math::Vector2d(0.5 - (0.5 * scaledW), 0.5 - (0.5 * scaledH)), Math::Vector2d(0.5 + (0.5 * scaledW), 0.5 + (0.5 * scaledH)) ); } } #endif } } if (_opengl) { if (ConfMan.hasKey("antialiasing")) _antialiasing = ConfMan.getInt("antialiasing"); 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); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); setAntialiasing(true); sdlflags = SDL_OPENGL; bpp = 24; } else #endif { bpp = 16; sdlflags = SDL_SWSURFACE; } if (_fullscreen && !accel3d && _lockAspectRatio) { screenW = _desktopW; screenH = _desktopH; _gameRect = Math::Rect2d( Math::Vector2d((_desktopW - fbW) / 2, (_desktopH - fbH) / 2), Math::Vector2d((_desktopW + fbW) / 2, (_desktopH + fbH) / 2) ); } if (_fullscreen) sdlflags |= SDL_FULLSCREEN; _screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags); #ifdef USE_OPENGL // If 32-bit with antialiasing failed, try 32-bit without antialiasing if (!_screen && _opengl && _antialiasing) { warning("Couldn't create 32-bit visual with AA, trying 32-bit without AA"); setAntialiasing(false); _screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags); } // If 32-bit failed, try 16-bit if (!_screen && _opengl) { warning("Couldn't create 32-bit visual, trying 16-bit"); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 1); setAntialiasing(true); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } // If 16-bit with antialiasing failed, try 16-bit without antialiasing if (!_screen && _opengl && _antialiasing) { warning("Couldn't create 16-bit visual with AA, trying 16-bit without AA"); setAntialiasing(false); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } // If 16-bit with alpha failed, try 16-bit without alpha if (!_screen && _opengl) { warning("Couldn't create 16-bit visual with alpha, trying without alpha"); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); setAntialiasing(true); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } // If 16-bit without alpha and with antialiasing didn't work, try without antialiasing if (!_screen && _opengl && _antialiasing) { warning("Couldn't create 16-bit visual with AA, trying 16-bit without AA"); setAntialiasing(false); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } #endif if (!_screen) { warning("Error: %s", SDL_GetError()); g_system->quit(); } #ifdef USE_OPENGL if (_opengl) { int glflag; const GLubyte *str; // apply atribute again for sure based on SDL docs SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); str = glGetString(GL_VENDOR); debug("INFO: OpenGL Vendor: %s", str); str = glGetString(GL_RENDERER); debug("INFO: OpenGL Renderer: %s", str); str = glGetString(GL_VERSION); debug("INFO: OpenGL Version: %s", str); SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &glflag); debug("INFO: OpenGL Red bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &glflag); debug("INFO: OpenGL Green bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &glflag); debug("INFO: OpenGL Blue bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &glflag); debug("INFO: OpenGL Alpha bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &glflag); debug("INFO: OpenGL Z buffer depth bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &glflag); debug("INFO: OpenGL Double Buffer: %d", glflag); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &glflag); debug("INFO: OpenGL Stencil buffer bits: %d", glflag); #ifdef USE_GLEW debug("INFO: GLEW Version: %s", glewGetString(GLEW_VERSION)); GLenum err = glewInit(); if (err != GLEW_OK) { warning("Error: %s", glewGetErrorString(err)); g_system->quit(); } #endif #ifdef USE_OPENGL_SHADERS debug("INFO: GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); const GLfloat vertices[] = { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, }; // Setup the box shader used to render the overlay const char* attributes[] = { "position", "texcoord", NULL }; _boxShader = Graphics::Shader::fromStrings("box", Graphics::BuiltinShaders::boxVertex, Graphics::BuiltinShaders::boxFragment, attributes); _boxVerticesVBO = Graphics::Shader::createBuffer(GL_ARRAY_BUFFER, sizeof(vertices), vertices); _boxShader->enableVertexAttribute("position", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0); _boxShader->enableVertexAttribute("texcoord", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0); #endif Graphics::initExtensions(); } #endif _overlayWidth = screenW; _overlayHeight = screenH; #ifdef USE_OPENGL if (_opengl) { uint32 rmask, gmask, bmask, amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0x00001f00; gmask = 0x000007e0; bmask = 0x000000f8; amask = 0x00000000; #else rmask = 0x0000f800; gmask = 0x000007e0; bmask = 0x0000001f; amask = 0x00000000; #endif _overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16, rmask, gmask, bmask, amask); _overlayScreenGLFormat = GL_UNSIGNED_SHORT_5_6_5; } else #endif { _overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16, _screen->format->Rmask, _screen->format->Gmask, _screen->format->Bmask, _screen->format->Amask); } if (!_overlayscreen) { warning("Error: %s", SDL_GetError()); g_system->quit(); } /*_overlayFormat.bytesPerPixel = _overlayscreen->format->BytesPerPixel; // For some reason the values below aren't right, at least on my system _overlayFormat.rLoss = _overlayscreen->format->Rloss; _overlayFormat.gLoss = _overlayscreen->format->Gloss; _overlayFormat.bLoss = _overlayscreen->format->Bloss; _overlayFormat.aLoss = _overlayscreen->format->Aloss; _overlayFormat.rShift = _overlayscreen->format->Rshift; _overlayFormat.gShift = _overlayscreen->format->Gshift; _overlayFormat.bShift = _overlayscreen->format->Bshift; _overlayFormat.aShift = _overlayscreen->format->Ashift;*/ _overlayFormat = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0); _screenChangeCount++; SDL_PixelFormat *f = _screen->format; _screenFormat = Graphics::PixelFormat(f->BytesPerPixel, 8 - f->Rloss, 8 - f->Gloss, 8 - f->Bloss, 0, f->Rshift, f->Gshift, f->Bshift, f->Ashift); #if defined(USE_OPENGL) && !defined(AMIGAOS) if (_opengl && _fullscreen && !g_engine->hasFeature(Engine::kSupportsArbitraryResolutions) && framebufferSupported) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); _frameBuffer = new Graphics::FrameBuffer(fbW, fbH); _frameBuffer->attach(); } #endif if (_fullscreen && !accel3d) { _subScreen = SDL_CreateRGBSurface(SDL_SWSURFACE, fbW, fbH, bpp, _screen->format->Rmask, _screen->format->Gmask, _screen->format->Bmask, _screen->format->Amask); return Graphics::PixelBuffer(_screenFormat, (byte *)_subScreen->pixels); } return Graphics::PixelBuffer(_screenFormat, (byte *)_screen->pixels); }
int main(int argc, char *argv[]) { int fsaa, accel; int value; int i, done; SDL_DisplayMode mode; SDL_Event event; Uint32 then, now, frames; int status; /* Initialize parameters */ fsaa = 0; accel = 0; /* Initialize test framework */ state = CommonCreateState(argv, SDL_INIT_VIDEO); if (!state) { return 1; } for (i = 1; i < argc;) { int consumed; consumed = CommonArg(state, i); if (consumed == 0) { if (SDL_strcasecmp(argv[i], "--fsaa") == 0) { ++fsaa; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--accel") == 0) { ++accel; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) { i++; if (!argv[i]) { consumed = -1; } else { depth = SDL_atoi(argv[i]); consumed = 1; } } else { consumed = -1; } } if (consumed < 0) { fprintf(stderr, "Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0], CommonUsage(state)); quit(1); } i += consumed; } /* Set OpenGL parameters */ state->window_flags |= SDL_WINDOW_OPENGL; state->gl_red_size = 5; state->gl_green_size = 5; state->gl_blue_size = 5; state->gl_depth_size = depth; if (fsaa) { state->gl_multisamplebuffers=1; state->gl_multisamplesamples=fsaa; } if (accel) { state->gl_accelerated=1; } if (!CommonInit(state)) { quit(2); } context = SDL_calloc(state->num_windows, sizeof(context)); if (context == NULL) { fprintf(stderr, "Out of memory!\n"); quit(2); } /* Create OpenGL ES contexts */ for (i = 0; i < state->num_windows; i++) { context[i] = SDL_GL_CreateContext(state->windows[i]); if (!context[i]) { fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError()); quit(2); } } if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } SDL_GetCurrentDisplayMode(&mode); printf("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format)); printf("\n"); printf("Vendor : %s\n", glGetString(GL_VENDOR)); printf("Renderer : %s\n", glGetString(GL_RENDERER)); printf("Version : %s\n", glGetString(GL_VERSION)); printf("Extensions : %s\n", glGetString(GL_EXTENSIONS)); printf("\n"); status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value); if (!status) { printf("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_RED_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value); if (!status) { printf("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_GREEN_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value); if (!status) { printf("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_BLUE_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value); if (!status) { printf("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value); } else { fprintf(stderr, "Failed to get SDL_GL_DEPTH_SIZE: %s\n", SDL_GetError()); } if (fsaa) { status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value); if (!status) { printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value); } else { fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value); if (!status) { printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value); } else { fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n", SDL_GetError()); } } if (accel) { status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value); if (!status) { printf("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value); } else { fprintf(stderr, "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n", SDL_GetError()); } } /* Set rendering settings for each context */ for (i = 0; i < state->num_windows; ++i) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } glViewport(0, 0, state->window_w, state->window_h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); } /* Main render loop */ frames = 0; then = SDL_GetTicks(); done = 0; while (!done) { /* Check for events */ ++frames; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: for (i = 0; i < state->num_windows; ++i) { if (event.window.windowID == state->windows[i]) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); break; } /* Change view port to the new window dimensions */ glViewport(0, 0, event.window.data1, event.window.data2); /* Update window content */ Render(); SDL_GL_SwapWindow(state->windows[i]); break; } } break; } } CommonEvent(state, &event, &done); } for (i = 0; i < state->num_windows; ++i) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } Render(); SDL_GL_SwapWindow(state->windows[i]); } } /* Print out some timing information */ now = SDL_GetTicks(); if (now > then) { printf("%2.2f frames per second\n", ((double) frames * 1000) / (now - then)); } quit(0); return 0; }
void WindowSDL2::create( const window_config &_config, AutoGCRoot* _on_created ) { //store these first created_handler = _on_created; //assign it now so we take a copy from the const config = _config; //then try init sdl video system int err = snow::window::init_sdl(); if (err == -1) { snow::log(1, "/ snow / could not initialize Video for SDL : %s\n", SDL_GetError()); on_created( false ); return; } //then create flags for the given config int request_flags = 0; int real_flags = 0; request_flags |= SDL_WINDOW_OPENGL; if(config.resizable) { request_flags |= SDL_WINDOW_RESIZABLE; } if(config.borderless) { request_flags |= SDL_WINDOW_BORDERLESS; } if(config.fullscreen) { request_flags |= SDL_WINDOW_FULLSCREEN; } //SDL_WINDOW_FULLSCREEN_DESKTOP; //opengl specifics, these all need to be set before create window SDL_GL_SetAttribute(SDL_GL_RED_SIZE, config.red_bits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, config.green_bits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, config.blue_bits); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, config.alpha_bits); if(config.depth_bits > 0) { SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, config.depth_bits ); } if(config.stencil_bits > 0) { SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, config.stencil_bits ); } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #ifdef SNOW_GLES SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif if(config.antialiasing > 0) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, config.antialiasing ); } //now actually try and create a window window = SDL_CreateWindow( config.title.c_str(), config.x, config.y, config.width, config.height, request_flags ); //#21 proves this false. need to adjust. //based on the code in SDL, the only reasons this can fail is // - no opengl at all (and we will always be requesting it so if that fails its game over) // - unable to load gl functions from library (same as no gl then) // - run out of memory to allocate a window (extremely unlikely but also game over) // - platform specific window failure, also unavoidable if( !window ) { snow::log(1, "/ snow / window failed to create for platform, cannot recover : %s\n", SDL_GetError()); on_created( false ); return; } //!window SDL_GetWindowPosition( window, &config.x, &config.y ); SDL_GetWindowSize( window, &config.width, &config.height ); id = SDL_GetWindowID(window); //now try creating the GL context, //if one doesn't already exist if(!snow_gl_context) { snow::log(2, "/ snow / attempting to create a GL context..."); snow_gl_context = SDL_GL_CreateContext(window); if( !snow_gl_context ) { snow::log(1, "/ snow / failed to create GL context for windowing (window id %d): %s\n", id, SDL_GetError() ); snow::log(1, "/ snow / trying again in a safer mode (no AA)"); //try without AA as this is a common cause of problems SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); //undo the local config for the aa, so it's sent back as off config.antialiasing = 0; //try again snow_gl_context = SDL_GL_CreateContext(window); if(!snow_gl_context) { snow::log(1, "/ snow / failed to create GL context without AA (window id %d): %s\n", id, SDL_GetError() ); //if that fails, we try and run a diagnostic test //against no stencil / depth buffer, so we can log more useful information SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0 ); snow_gl_context = SDL_GL_CreateContext(window); //if this succeeds we can at least log that there was a misconfigured depth/stencil buffer if(snow_gl_context) { snow::log(1, "/ snow / diagnostic test with no stencil/depth passed, meaning your stencil/depth bit combo is invalid (requested stencil:%d, depth:%d)\n", config.stencil_bits, config.depth_bits ); } else { snow::log(1, "/ snow / diagnostic test with no stencil/depth failed as well %s\n", SDL_GetError() ); } on_created( false ); return; } } //if we end up with a context if(snow_gl_context) { //update the window config flags to what //SDL has actually given us in return int actual_aa = config.antialiasing; int actual_depth = config.depth_bits; int actual_stencil = config.stencil_bits; int actual_red = config.red_bits; int actual_blue = config.blue_bits; int actual_green = config.green_bits; int actual_alpha = config.alpha_bits; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &actual_aa); SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &actual_red); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &actual_green); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &actual_blue); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &actual_alpha); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &actual_depth); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &actual_stencil); config.antialiasing = actual_aa; config.red_bits = actual_red; config.green_bits = actual_green; config.blue_bits = actual_blue; config.alpha_bits = actual_alpha; config.depth_bits = actual_depth; config.stencil_bits = actual_stencil; snow::render::set_context_attributes( actual_red, actual_green, actual_blue, actual_alpha, actual_depth, actual_stencil, actual_aa ); snow::log(2, "/ snow / success in creating GL context for window %d\n", id); } #ifdef NATIVE_TOOLKIT_GLEW int err = glewInit(); if(err != 0) { snow::log(1, "/ snow / failed to init glew?! %s\n", glewGetErrorString(err)); on_created( false ); return; } else { snow::log(2, "/ snow / GLEW init ok"); } #endif //NATIVE_TOOLKIT_GLEW } //!snow_gl_context //on iOS we need to intercept the loop #ifdef IPHONE snow::log(1, "/ snow / requesting main loop for iOS"); SDL_iPhoneSetAnimationCallback(window, 1, snow::core::loop, NULL); #endif //IPHONE #ifdef HX_WINDOWS snow::platform::window::load_icon( window ); #endif on_created( true ); } //WindowSDL2::create
bool SDL2Window::initialize() { arx_assert(!m_displayModes.empty()); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); #if ARX_PLATFORM == ARX_PLATFORM_WIN32 // Used on Windows to prevent software opengl fallback. // The linux situation: // Causes SDL to require visuals without caveats. // On linux some drivers only supply multisample capable GLX Visuals // with a GLX_NON_CONFORMANT_VISUAL_EXT caveat. // see: https://www.opengl.org/registry/specs/EXT/visual_rating.txt SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); #endif // TODO EGL and core profile are not supported yet SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); if(gldebug::isEnabled()) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); } int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; Uint32 windowFlags = getSDLFlagsForMode(m_size, m_fullscreen); windowFlags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; for(int msaa = m_maxMSAALevel; msaa > 0; msaa--) { bool lastTry = (msaa == 1); // Cleanup context and window from previous tries if(m_glcontext) { SDL_GL_DeleteContext(m_glcontext); m_glcontext = NULL; } if(m_window) { SDL_DestroyWindow(m_window); m_window = NULL; } SDL_ClearError(); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, msaa > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, msaa > 1 ? msaa : 0); m_window = SDL_CreateWindow(m_title.c_str(), x, y, m_size.x, m_size.y, windowFlags); if(!m_window) { if(lastTry) { LogError << "Could not create window: " << SDL_GetError(); return false; } continue; } m_glcontext = SDL_GL_CreateContext(m_window); if(!m_glcontext) { if(lastTry) { LogError << "Could not create GL context: " << SDL_GetError(); return false; } continue; } // Verify that the MSAA setting matches what was requested int msaaEnabled, msaaValue; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &msaaEnabled); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &msaaValue); if(!lastTry) { if(!msaaEnabled || msaaValue < msaa) { continue; } } if(msaaEnabled) { m_MSAALevel = msaaValue; } else { m_MSAALevel = 0; } // Verify that we actually got an accelerated context (void)glGetError(); // clear error flags GLint texunits = 0; glGetIntegerv(GL_MAX_TEXTURE_UNITS, &texunits); if(glGetError() != GL_NO_ERROR || texunits < GLint(m_minTextureUnits)) { if(lastTry) { LogError << "Not enough GL texture units available: have " << texunits << ", need at least " << m_minTextureUnits; return false; } continue; } // All good const char * system = "(unknown)"; { ARX_SDL_SysWMinfo info; info.version.major = 2; info.version.minor = 0; info.version.patch = 4; if(SDL_GetWindowWMInfo(m_window, reinterpret_cast<SDL_SysWMinfo *>(&info))) { switch(info.subsystem) { case ARX_SDL_SYSWM_UNKNOWN: break; case ARX_SDL_SYSWM_WINDOWS: system = "Windows"; break; case ARX_SDL_SYSWM_X11: system = "X11"; break; #if SDL_VERSION_ATLEAST(2, 0, 3) case ARX_SDL_SYSWM_WINRT: system = "WinRT"; break; #endif case ARX_SDL_SYSWM_DIRECTFB: system = "DirectFB"; break; case ARX_SDL_SYSWM_COCOA: system = "Cocoa"; break; case ARX_SDL_SYSWM_UIKIT: system = "UIKit"; break; #if SDL_VERSION_ATLEAST(2, 0, 2) case ARX_SDL_SYSWM_WAYLAND: system = "Wayland"; break; case ARX_SDL_SYSWM_MIR: system = "Mir"; break; #endif #if SDL_VERSION_ATLEAST(2, 0, 4) case ARX_SDL_SYSWM_ANDROID: system = "Android"; break; #endif } } } int red = 0, green = 0, blue = 0, alpha = 0, depth = 0, doublebuffer = 0; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &red); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &green); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &blue); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alpha); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doublebuffer); LogInfo << "Window: " << system << " r:" << red << " g:" << green << " b:" << blue << " a:" << alpha << " depth:" << depth << " aa:" << msaa << "x" << " doublebuffer:" << doublebuffer; break; } // Use the executable icon for the window #if ARX_PLATFORM == ARX_PLATFORM_WIN32 { SDL_SysWMinfo info; SDL_VERSION(&info.version); if(SDL_GetWindowWMInfo(m_window, &info) && info.subsystem == SDL_SYSWM_WINDOWS) { platform::WideString filename; filename.allocate(filename.capacity()); while(true) { DWORD size = GetModuleFileNameW(NULL, filename.data(), filename.size()); if(size < filename.size()) { filename.resize(size); break; } filename.allocate(filename.size() * 2); } HICON largeIcon = 0; HICON smallIcon = 0; ExtractIconExW(filename, 0, &largeIcon, &smallIcon, 1); if(smallIcon) { SendMessage(info.info.win.window, WM_SETICON, ICON_SMALL, LPARAM(smallIcon)); } if(largeIcon) { SendMessage(info.info.win.window, WM_SETICON, ICON_BIG, LPARAM(largeIcon)); } } } #endif setVSync(m_vsync); SDL_ShowWindow(m_window); SDL_ShowCursor(SDL_DISABLE); m_renderer->initialize(); onCreate(); onToggleFullscreen(m_fullscreen); updateSize(true); onShow(true); onFocus(true); return true; }
static qboolean GLimp_InitGraphics(qboolean fullscreen) { int flags; /* Just toggle fullscreen if that's all that has been changed */ if (surface && (surface->w == vid.width) && (surface->h == vid.height)) { int isfullscreen = (surface->flags & SDL_FULLSCREEN) ? 1 : 0; if (fullscreen != isfullscreen) SDL_WM_ToggleFullScreen(surface); isfullscreen = (surface->flags & SDL_FULLSCREEN) ? 1 : 0; if (fullscreen == isfullscreen) return true; } srandom(getpid()); /* free resources in use */ if (surface) SDL_FreeSurface(surface); /* let the sound and input subsystems know about the new window */ ri.Vid_NewWindow(vid.width, vid.height); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (use_stencil) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1); flags = SDL_OPENGL; if (fullscreen) flags |= SDL_FULLSCREEN; SetSDLIcon(); /* currently uses q2icon.xbm data */ if ((surface = SDL_SetVideoMode(vid.width, vid.height, 0, flags)) == NULL) { Sys_Error("(SDLGL) SDL SetVideoMode failed: %s\n", SDL_GetError()); return false; } /* stencilbuffer shadows */ if (use_stencil) { int stencil_bits; have_stencil = false; if (!SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil_bits)) { ri.Con_Printf(PRINT_ALL, "I: got %d bits of stencil\n", stencil_bits); if (stencil_bits >= 1) { have_stencil = true; } } } SDL_WM_SetCaption(QUDOS_VERSION, QUDOS_VERSION); SDL_ShowCursor(0); X11_active = true; SetSDLGamma(); return true; }
int RunGLTest(int argc, char *argv[], int logo, int logocursor, int slowly, int bpp, float gamma, int noframe, int fsaa, int sync, int accel) { int i; int rgb_size[3]; int w = 640; int h = 480; int done = 0; int frames; Uint32 start_time, this_time; float color[8][3] = { {1.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, {1.0, 0.0, 1.0}, {0.0, 0.0, 1.0} }; float cube[8][3] = { {0.5, 0.5, -0.5}, {0.5, -0.5, -0.5}, {-0.5, -0.5, -0.5}, {-0.5, 0.5, -0.5}, {-0.5, 0.5, 0.5}, {0.5, 0.5, 0.5}, {0.5, -0.5, 0.5}, {-0.5, -0.5, 0.5} }; Uint32 video_flags; int value; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } /* See if we should detect the display depth */ if (bpp == 0) { if (SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8) { bpp = 8; } else { bpp = 16; /* More doesn't seem to work */ } } /* Set the flags we want to use for setting the video mode */ video_flags = SDL_OPENGL; for (i = 1; argv[i]; ++i) { if (strcmp(argv[i], "-fullscreen") == 0) { video_flags |= SDL_FULLSCREEN; } } if (noframe) { video_flags |= SDL_NOFRAME; } /* Initialize the display */ switch (bpp) { case 8: rgb_size[0] = 3; rgb_size[1] = 3; rgb_size[2] = 2; break; case 15: case 16: rgb_size[0] = 5; rgb_size[1] = 5; rgb_size[2] = 5; break; default: rgb_size[0] = 8; rgb_size[1] = 8; rgb_size[2] = 8; break; } SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rgb_size[0]); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, rgb_size[1]); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, rgb_size[2]); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (fsaa) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa); } if (accel) { SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); } if (SDL_SetVideoMode(w, h, bpp, video_flags) == NULL) { fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } if (sync) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } printf("Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel); printf("\n"); printf("Vendor : %s\n", glGetString(GL_VENDOR)); printf("Renderer : %s\n", glGetString(GL_RENDERER)); printf("Version : %s\n", glGetString(GL_VERSION)); printf("Extensions : %s\n", glGetString(GL_EXTENSIONS)); printf("\n"); SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value); printf("SDL_GL_RED_SIZE: requested %d, got %d\n", rgb_size[0], value); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value); printf("SDL_GL_GREEN_SIZE: requested %d, got %d\n", rgb_size[1], value); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value); printf("SDL_GL_BLUE_SIZE: requested %d, got %d\n", rgb_size[2], value); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value); printf("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", bpp, value); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &value); printf("SDL_GL_DOUBLEBUFFER: requested 1, got %d\n", value); if (fsaa) { SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value); printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value); printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value); } if (accel) { SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value); printf("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value); } if (sync) { printf("Buffer swap interval: requested 1, got %d\n", SDL_GL_GetSwapInterval()); } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL GL test", "testgl"); /* Set the gamma for the window */ if (gamma != 0.0) { SDL_SetGamma(gamma, gamma, gamma); } glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); /* Loop until done. */ start_time = SDL_GetTicks(); frames = 0; while (!done) { GLenum gl_error; char *sdl_error; SDL_Event event; /* Do our drawing, too. */ glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBegin(GL_QUADS); #ifdef SHADED_CUBE glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[7]); glVertex3fv(cube[7]); #else /* flat cube */ glColor3f(1.0, 0.0, 0.0); glVertex3fv(cube[0]); glVertex3fv(cube[1]); glVertex3fv(cube[2]); glVertex3fv(cube[3]); glColor3f(0.0, 1.0, 0.0); glVertex3fv(cube[3]); glVertex3fv(cube[4]); glVertex3fv(cube[7]); glVertex3fv(cube[2]); glColor3f(0.0, 0.0, 1.0); glVertex3fv(cube[0]); glVertex3fv(cube[5]); glVertex3fv(cube[6]); glVertex3fv(cube[1]); glColor3f(0.0, 1.0, 1.0); glVertex3fv(cube[5]); glVertex3fv(cube[4]); glVertex3fv(cube[7]); glVertex3fv(cube[6]); glColor3f(1.0, 1.0, 0.0); glVertex3fv(cube[5]); glVertex3fv(cube[0]); glVertex3fv(cube[3]); glVertex3fv(cube[4]); glColor3f(1.0, 0.0, 1.0); glVertex3fv(cube[6]); glVertex3fv(cube[1]); glVertex3fv(cube[2]); glVertex3fv(cube[7]); #endif /* SHADED_CUBE */ glEnd(); glMatrixMode(GL_MODELVIEW); glRotatef(5.0, 1.0, 1.0, 1.0); /* Draw 2D logo onto the 3D display */ if (logo) { DrawLogoTexture(); } if (logocursor) { DrawLogoCursor(); } SDL_GL_SwapBuffers(); /* Check for error conditions. */ gl_error = glGetError(); if (gl_error != GL_NO_ERROR) { fprintf(stderr, "testgl: OpenGL error: %d\n", gl_error); } sdl_error = SDL_GetError(); if (sdl_error[0] != '\0') { fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error); SDL_ClearError(); } /* Allow the user to see what's happening */ if (slowly) { SDL_Delay(20); } /* Check if there's a pending event. */ while (SDL_PollEvent(&event)) { done |= HandleEvent(&event); } ++frames; } /* Print out the frames per second */ this_time = SDL_GetTicks(); if (this_time != start_time) { printf("%2.2f FPS\n", ((float) frames / (this_time - start_time)) * 1000.0); } if (global_image) { SDL_FreeSurface(global_image); global_image = NULL; } if (global_texture) { glDeleteTextures(1, &global_texture); global_texture = 0; } if (cursor_texture) { glDeleteTextures(1, &cursor_texture); cursor_texture = 0; } /* Destroy our GL context, etc. */ SDL_Quit(); return (0); }
WindowSDL::WindowSDL(const Graphics::Settings &vs, const std::string &name) { Uint32 winFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; if (vs.fullscreen) winFlags |= SDL_WINDOW_FULLSCREEN; SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, vs.requestedSamples ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, vs.requestedSamples); // attempt sequence is: // 1- requested mode m_window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, vs.width, vs.height, winFlags); // 2- requested mode with no anti-aliasing (skipped if no AA was requested anyway) if (!m_window && vs.requestedSamples) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying without multisampling.\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); m_window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, vs.width, vs.height, winFlags); } // 3- requested mode with 16 bit depth buffer if (!m_window) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying with 16-bit depth buffer\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, vs.requestedSamples ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, vs.requestedSamples); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); m_window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, vs.width, vs.height, winFlags); } // 4- requested mode with 16-bit depth buffer and no anti-aliasing // (skipped if no AA was requested anyway) if (!m_window && vs.requestedSamples) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying with 16-bit depth buffer and no multisampling\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); m_window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, vs.width, vs.height, winFlags); } // 5- abort! if (!m_window) { OS::Error("Failed to set video mode: %s", SDL_GetError()); } m_glContext = SDL_GL_CreateContext(m_window); int bpp; Uint32 rmask, gmask, bmask, amask; SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(m_window), &bpp, &rmask, &gmask, &bmask, &amask); switch (bpp) { case 16: SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); break; case 24: case 32: 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); break; default: fprintf(stderr, "Invalid pixel depth: %d bpp\n", bpp); // this valuable is not reliable if antialiasing vs are overridden by // nvidia/ati/whatever vs int actualSamples = 0; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &actualSamples); if (vs.requestedSamples != actualSamples) fprintf(stderr, "Requested AA mode: %dx, actual: %dx\n", vs.requestedSamples, actualSamples); } SDLSurfacePtr surface = LoadSurfaceFromFile(vs.iconFile); if (surface) SDL_SetWindowIcon(m_window, surface.Get()); SDL_SetWindowTitle(m_window, vs.title); }
void I_UpdateVideoMode(void) { int init_flags; int i; video_mode_t mode; lprintf(LO_INFO, "I_UpdateVideoMode: %dx%d (%s)\n", SCREENWIDTH, SCREENHEIGHT, desired_fullscreen ? "fullscreen" : "nofullscreen"); mode = I_GetModeFromString(default_videomode); if ((i=M_CheckParm("-vidmode")) && i<myargc-1) { mode = I_GetModeFromString(myargv[i+1]); } V_InitMode(mode); V_DestroyUnusedTrueColorPalettes(); V_FreeScreens(); I_SetRes(); // Initialize SDL with this graphics mode if (V_GetMode() == VID_MODEGL) { init_flags = SDL_OPENGL; } else { if (use_doublebuffer) init_flags = SDL_DOUBLEBUF; else init_flags = SDL_SWSURFACE; #ifndef _DEBUG init_flags |= SDL_HWPALETTE; #endif } if ( desired_fullscreen ) init_flags |= SDL_FULLSCREEN; if (V_GetMode() == VID_MODEGL) { SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, gl_colorbuffer_bits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, gl_depthbuffer_bits ); screen = SDL_SetVideoMode(SCREENWIDTH, SCREENHEIGHT, gl_colorbuffer_bits, init_flags); } else { screen = SDL_SetVideoMode(SCREENWIDTH, SCREENHEIGHT, V_GetNumPixelBits(), init_flags); } if(screen == NULL) { I_Error("Couldn't set %dx%d video mode [%s]", SCREENWIDTH, SCREENHEIGHT, SDL_GetError()); } lprintf(LO_INFO, "I_UpdateVideoMode: 0x%x, %s, %s\n", init_flags, screen->pixels ? "SDL buffer" : "own buffer", SDL_MUSTLOCK(screen) ? "lock-and-copy": "direct access"); // Get the info needed to render to the display if (!SDL_MUSTLOCK(screen)) { screens[0].not_on_heap = true; screens[0].data = (unsigned char *) (screen->pixels); screens[0].byte_pitch = screen->pitch; screens[0].short_pitch = screen->pitch / V_GetModePixelDepth(VID_MODE16); screens[0].int_pitch = screen->pitch / V_GetModePixelDepth(VID_MODE32); } else { screens[0].not_on_heap = false; } V_AllocScreens(); // Hide pointer while over this window SDL_ShowCursor(0); I_PrepareMouse(1); R_InitBuffer(SCREENWIDTH, SCREENHEIGHT); if (V_GetMode() == VID_MODEGL) { int temp; lprintf(LO_INFO,"SDL OpenGL PixelFormat:\n"); SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_RED_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_GREEN_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_BLUE_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_STENCIL_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_STENCIL_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_ACCUM_RED_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_ACCUM_RED_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_ACCUM_GREEN_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_ACCUM_GREEN_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_ACCUM_BLUE_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_ACCUM_BLUE_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_ACCUM_ALPHA_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &temp ); lprintf(LO_INFO," SDL_GL_DOUBLEBUFFER: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_BUFFER_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_BUFFER_SIZE: %i\n",temp); SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &temp ); lprintf(LO_INFO," SDL_GL_DEPTH_SIZE: %i\n",temp); #ifdef GL_DOOM gld_Init(SCREENWIDTH, SCREENHEIGHT); #endif } }
SDL_Surface *initsdl(int w,int h,int *bppp,Uint32 flags) { // SDL_INIT_EVENTTHREAD if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError()); exit( 1 ); } SDL_Surface *s; static int bpp=0; Uint32 video_flags; video_flags = flags; int rgb_size[3]={0,0,0}; printf("yoyoyo\n"); if (flags& SDL_OPENGL) { /* if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) { bpp = 8; } else { bpp = 16; // More doesn't seem to work }*/ bpp=SDL_GetVideoInfo()->vfmt->BitsPerPixel; switch (bpp) { case 8: rgb_size[0] = 3; rgb_size[1] = 3; rgb_size[2] = 2; break; case 15: case 16: rgb_size[0] = 5; rgb_size[1] = 5; rgb_size[2] = 5; break; default: rgb_size[0] = 8; rgb_size[1] = 8; rgb_size[2] = 8; break; } SDL_GL_SetAttribute( SDL_GL_RED_SIZE, rgb_size[0] ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, rgb_size[1] ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, rgb_size[2] ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); } video_flags|=(SDL_RESIZABLE|SDL_ANYFORMAT|SDL_DOUBLEBUF); s= SDL_SetVideoMode( w, h, bpp, video_flags ); if (s == NULL ) { fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } //#ifdef chaos printf("Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel); printf("\n"); #ifdef GL printf( "Vendor : %s\n", glGetString( GL_VENDOR ) ); printf( "Renderer : %s\n", glGetString( GL_RENDERER ) ); printf( "Version : %s\n", glGetString( GL_VERSION ) ); printf( "Extensions : %s\n", glGetString( GL_EXTENSIONS ) ); printf("\n"); int value; SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value ); printf( "SDL_GL_RED_SIZE: requested %d, got %d\n", rgb_size[0],value); SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value ); printf( "SDL_GL_GREEN_SIZE: requested %d, got %d\n", rgb_size[1],value); SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value ); printf( "SDL_GL_BLUE_SIZE: requested %d, got %d\n", rgb_size[2],value); SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value ); printf( "SDL_GL_DEPTH_SIZE: requested %d, got %d\n", bpp, value ); SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value ); printf( "SDL_GL_DOUBLEBUFFER: requested 1, got %d\n", value ); #endif printf("mustlock=%i\n", SDL_MUSTLOCK(s)); *bppp=bpp; char * x= (char*)malloc(20); if(x&&SDL_VideoDriverName(x,20)) printf("Current SDL video driver is %s.\n",x); //#endif return s; }
static void VID_SDL_Init(void) { int flags; int r, g, b, a; if (glConfig.initialized == true) { return; } flags = 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) { if (vid_usedesktopres.integer == 1) { flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } } else { if (vid_win_borderless.integer > 0) { flags |= SDL_WINDOW_BORDERLESS; } } #ifdef __APPLE__ SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0"); SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); #endif VID_SDL_InitSubSystem(); VID_SDL_GL_SetupAttributes(); VID_SetupModeList(); VID_SetupResolution(); if (r_fullscreen.integer == 0) { int displayNumber = VID_DisplayNumber(false); int xpos = vid_xpos.integer; int ypos = vid_ypos.integer; VID_AbsolutePositionFromRelative(&xpos, &ypos, &displayNumber); sdl_window = SDL_CreateWindow(WINDOW_CLASS_NAME, xpos, ypos, glConfig.vidWidth, glConfig.vidHeight, flags); } else { int windowWidth = glConfig.vidWidth; int windowHeight = glConfig.vidHeight; int windowX = SDL_WINDOWPOS_CENTERED; int windowY = SDL_WINDOWPOS_CENTERED; int displayNumber = VID_DisplayNumber(true); SDL_Rect bounds; if (SDL_GetDisplayBounds(displayNumber, &bounds) == 0) { windowX = bounds.x; windowY = bounds.y; windowWidth = bounds.w; windowHeight = bounds.h; } else { Com_Printf("Couldn't determine bounds of display #%d, defaulting to main display\n", displayNumber); } sdl_window = SDL_CreateWindow(WINDOW_CLASS_NAME, windowX, windowY, windowWidth, windowHeight, flags); } if (r_fullscreen.integer > 0 && vid_usedesktopres.integer != 1) { int index; index = VID_GetCurrentModeIndex(); /* FIXME: Make a pre-check if the values render a valid video mode before attempting to switch (when vid_usedesktopres != 1) !! */ if (index < 0) { Com_Printf("Couldn't find a matching video mode for the selected values, check video settings!\n"); } else { if (SDL_SetWindowDisplayMode(sdl_window, &modelist[index]) != 0) { Com_Printf("sdl error: %s\n", SDL_GetError()); } } if (SDL_SetWindowFullscreen(sdl_window, SDL_WINDOW_FULLSCREEN) < 0) { Com_Printf("Failed to change to fullscreen mode\n"); } } if (VID_SetWindowIcon(sdl_window) < 0) { Com_Printf("Failed to set window icon"); } 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; } v_gamma.modified = true; r_swapInterval.modified = true; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &a); glConfig.colorBits = r+g+b+a; 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; }
void SDLX_sdl_gl_multisampling_t::download() { SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &multibuffers); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &multisamples); }
bool Graphics::setOpenGLMode() { #ifdef USE_OPENGL SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (!(mWindow = graphicsManager.createWindow( mActualWidth, mActualHeight, mBpp, getOpenGLFlags()))) { logger->log("Window/context creation failed"); mRect.w = 0; mRect.h = 0; return false; } #if defined(USE_X11) Glx::initFunctions(); #endif #ifdef USE_SDL2 int w1 = 0; int h1 = 0; SDL_GetWindowSize(mWindow, &w1, &h1); mRect.w = static_cast<int32_t>(w1 / mScale); mRect.h = static_cast<int32_t>(h1 / mScale); createGLContext(); #else // USE_SDL2 createGLContext(); mRect.w = static_cast<uint16_t>(mWindow->w / mScale); mRect.h = static_cast<uint16_t>(mWindow->h / mScale); #endif // USE_SDL2 #ifdef __APPLE__ if (mSync) { const GLint VBL = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); } #endif graphicsManager.setGLVersion(); graphicsManager.logVersion(); // Setup OpenGL glViewport(0, 0, mActualWidth, mActualHeight); int gotDoubleBuffer = 0; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &gotDoubleBuffer); logger->log("Using OpenGL %s double buffering.", (gotDoubleBuffer ? "with" : "without")); graphicsManager.initOpenGL(); initArrays(graphicsManager.getMaxVertices()); graphicsManager.updateTextureCompressionFormat(); graphicsManager.updateTextureFormat(); updateMemoryInfo(); GLint texSize; bool rectTex = graphicsManager.supportExtension( "GL_ARB_texture_rectangle"); if (rectTex && OpenGLImageHelper::getInternalTextureType() == 4 && getOpenGL() != RENDER_GLES_OPENGL && getOpenGL() != RENDER_MODERN_OPENGL && config.getBoolValue("rectangulartextures") && !graphicsManager.isUseTextureSampler()) { logger->log1("using GL_ARB_texture_rectangle"); OpenGLImageHelper::mTextureType = GL_TEXTURE_RECTANGLE_ARB; glEnable(GL_TEXTURE_RECTANGLE_ARB); glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &texSize); OpenGLImageHelper::mTextureSize = texSize; logger->log("OpenGL texture size: %d pixels (rectangle textures)", OpenGLImageHelper::mTextureSize); } else { OpenGLImageHelper::mTextureType = GL_TEXTURE_2D; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); OpenGLImageHelper::mTextureSize = texSize; logger->log("OpenGL texture size: %d pixels", OpenGLImageHelper::mTextureSize); } return videoInfo(); #else // USE_OPENGL return false; #endif // USE_OPENGL }
void SDLX_sdl_gl_attrib_t::download(SDLX_sdl_gl_attrib_t& self) { int temporary[4]; // (1) Get the colour buffer depth. SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &(temporary[0])); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &(temporary[1])); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &(temporary[2])); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &(temporary[3])); self.colourBufferDepth = Ego::ColourDepth(temporary[0] + temporary[1] + temporary[2] + temporary[3], temporary[0], temporary[1], temporary[2], temporary[3]); SDL_GL_GetAttribute(SDL_GL_BUFFER_SIZE, &(self.buffer_size)); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &(self.doublebuffer)); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &(self.depthBufferDepth)); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &(self.stencilBufferDepth)); // (2) Get the accumulation buffer depth. SDL_GL_GetAttribute(SDL_GL_ACCUM_RED_SIZE, &(temporary[0])); SDL_GL_GetAttribute(SDL_GL_ACCUM_GREEN_SIZE, &(temporary[1])); SDL_GL_GetAttribute(SDL_GL_ACCUM_BLUE_SIZE, &(temporary[1])); SDL_GL_GetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, &(temporary[2])); self.accumulationBufferDepth = Ego::ColourDepth(temporary[0] + temporary[1] + temporary[2] + temporary[3], temporary[0], temporary[1], temporary[2], temporary[3]); SDL_GL_GetAttribute(SDL_GL_STEREO, &(self.stereo)); self.swap_control = SDL_GL_GetSwapInterval(); self.multisampling.download(); #if !defined(ID_LINUX) SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &(self.accelerated_visual)); #endif }
// This stage, we handle display mode setting bool wzMainScreenSetup(int antialiasing, bool fullscreen, bool vsync) { // populate with the saved values (if we had any) int width = pie_GetVideoBufferWidth(); int height = pie_GetVideoBufferHeight(); int bitDepth = pie_GetVideoBufferDepth(); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { debug(LOG_ERROR, "Error: Could not initialise SDL (%s).", SDL_GetError()); return false; } // Populated our resolution list (does all displays now) SDL_DisplayMode displaymode; struct screeninfo screenlist; for (int i = 0; i < SDL_GetNumVideoDisplays(); ++i) // How many monitors we got { int numdisplaymodes = SDL_GetNumDisplayModes(i); // Get the number of display modes on this monitor for (int j = 0; j < numdisplaymodes; j++) { displaymode.format = displaymode.w = displaymode.h = displaymode.refresh_rate = 0; displaymode.driverdata = 0; if (SDL_GetDisplayMode(i, j, &displaymode) < 0) { debug(LOG_FATAL, "SDL_LOG_CATEGORY_APPLICATION error:%s", SDL_GetError()); SDL_Quit(); exit(EXIT_FAILURE); } debug(LOG_WZ, "Monitor[%d]%dx%d %d %s", i, displaymode.w, displaymode.h, displaymode.refresh_rate, getSDL_fmt_string(displaymode.format)); if (displaymode.refresh_rate < 59) { continue; // only store 60Hz & higher modes, some display report 59 on linux } screenlist.height = displaymode.h; screenlist.width = displaymode.w; screenlist.refresh_rate = displaymode.refresh_rate; screenlist.screen = i; // which monitor this belongs to displaylist.push_back(screenlist); } } SDL_DisplayMode current = { 0, 0, 0, 0, 0 }; for (int i = 0; i < SDL_GetNumVideoDisplays(); ++i) { int display = SDL_GetCurrentDisplayMode(i, ¤t); if (display != 0) { debug(LOG_FATAL, "Can't get the current display mode, because: %s", SDL_GetError()); SDL_Quit(); exit(EXIT_FAILURE); } debug(LOG_WZ, "Monitor[%d]%dx%d %d", i, current.w, current.h, current.refresh_rate); } if (width == 0 || height == 0) { pie_SetVideoBufferWidth(width = screenWidth = current.w); pie_SetVideoBufferHeight(height = screenHeight = current.h); } else { screenWidth = width; screenHeight = height; } screenWidth = MAX(screenWidth, 640); screenHeight = MAX(screenHeight, 480); //// The flags to pass to SDL_CreateWindow int video_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; if (war_getFullscreen()) { video_flags |= SDL_WINDOW_FULLSCREEN; } SDL_Rect bounds; for (int i = 0; i < SDL_GetNumVideoDisplays(); i++) { SDL_GetDisplayBounds(i, &bounds); debug(LOG_WZ, "Monitor %d: pos %d x %d : res %d x %d", i, (int)bounds.x, (int)bounds.y, (int)bounds.w, (int)bounds.h); } if (war_GetScreen() > SDL_GetNumVideoDisplays()) { debug(LOG_FATAL, "Invalid screen defined in configuration"); SDL_Quit(); exit(EXIT_FAILURE); } SDL_GetDisplayBounds(war_GetScreen(), &bounds); bounds.w -= (bounds.w + screenWidth) / 2; bounds.h -= (bounds.h + screenHeight) / 2; WZwindow = SDL_CreateWindow(PACKAGE_NAME, bounds.x + bounds.w, bounds.y + bounds.h, screenWidth, screenHeight, video_flags); if (!WZwindow) { debug(LOG_FATAL, "Can't create a window, because: %s", SDL_GetError()); SDL_Quit(); exit(EXIT_FAILURE); } WZglcontext = SDL_GL_CreateContext(WZwindow); if (!WZglcontext) { debug(LOG_ERROR, "Failed to create a openGL context! [%s]", SDL_GetError()); return false; } // Set the double buffer OpenGL attribute. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Enable FSAA anti-aliasing if and at the level requested by the user if (antialiasing) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, antialiasing); } int bpp = SDL_BITSPERPIXEL(SDL_GetWindowPixelFormat(WZwindow)); debug(LOG_WZ, "Bpp = %d format %s" , bpp, getSDL_fmt_string(SDL_GetWindowPixelFormat(WZwindow))); if (!bpp) { debug(LOG_ERROR, "Video mode %dx%d@%dbpp is not supported!", width, height, bitDepth); return false; } switch (bpp) { case 32: case 24: // all is good... break; case 16: info("Using colour depth of %i instead of a 32/24 bit depth (True color).", bpp); info("You will experience graphics glitches!"); break; case 8: debug(LOG_FATAL, "You don't want to play Warzone with a bit depth of %i, do you?", bpp); SDL_Quit(); exit(1); break; default: debug(LOG_FATAL, "Unsupported bit depth: %i", bpp); exit(1); break; } // Enable/disable vsync if requested by the user wzSetSwapInterval(war_GetVsync()); int value = 0; if (SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &value) == -1 || value == 0) { debug(LOG_FATAL, "OpenGL initialization did not give double buffering!"); debug(LOG_FATAL, "Double buffering is required for this game!"); SDL_Quit(); exit(1); } #if SDL_BYTEORDER == SDL_BIG_ENDIAN uint32_t rmask = 0xff000000; uint32_t gmask = 0x00ff0000; uint32_t bmask = 0x0000ff00; uint32_t amask = 0x000000ff; #else uint32_t rmask = 0x000000ff; uint32_t gmask = 0x0000ff00; uint32_t bmask = 0x00ff0000; uint32_t amask = 0xff000000; #endif SDL_Surface *surface_icon = SDL_CreateRGBSurfaceFrom((void *)wz2100icon.pixel_data, wz2100icon.width, wz2100icon.height, wz2100icon.bytes_per_pixel * 8, wz2100icon.width * wz2100icon.bytes_per_pixel, rmask, gmask, bmask, amask); if (surface_icon) { SDL_SetWindowIcon(WZwindow, surface_icon); SDL_FreeSurface(surface_icon); } else { debug(LOG_ERROR, "Could not set window icon because %s", SDL_GetError()); } SDL_SetWindowTitle(WZwindow, PACKAGE_NAME); /* initialise all cursors */ if (war_GetColouredCursor()) { sdlInitColoredCursors(); } else { sdlInitCursors(); } // FIXME: aspect ratio glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, width, height, 0, 1, -1); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glCullFace(GL_FRONT); glEnable(GL_CULL_FACE); return true; }
SDL_Window * SDLX_CreateWindow( SDLX_video_parameters_t& v, bool make_report ) { SDL_Window * ret = nullptr; int windowPos = SDL_WINDOWPOS_CENTERED; if (Ego::GraphicsSystem::window) return nullptr; if (!v.flags.opengl) { // do our one-and-only video initialization ret = SDLX_CreateWindow(v.flags); if (!ret) { Log::get().message("SDL WARN: Unable to create SDL window: %s\n", SDL_GetError()); } else { SDL_SetWindowSize(ret, v.horizontalResolution, v.verticalResolution); SDL_SetWindowPosition(ret, windowPos, windowPos); } } else { SDLX_sdl_gl_attrib_t::validate(v.gl_att); // synch some parameters between OpenGL and SDL v.colorBufferDepth = v.gl_att.buffer_size; // try a softer video initialization // if it fails, then it tries to get the closest possible valid video mode ret = SDLX_CreateWindow(v.flags); if ( nullptr == ret ) { Log::get().warn("unable to create SDL window: %s\n", SDL_GetError()); } else { SDL_SetWindowSize(ret, v.horizontalResolution, v.verticalResolution); SDL_SetWindowPosition(ret, windowPos, windowPos); SDL_GLContext context = SDLX_CreateContext(ret, v.gl_att); if (!context) { Log::get().warn("unable to create GL context: %s\n", SDL_GetError()); SDL_DestroyWindow(ret); ret = nullptr; } } if (!ret) { // if we're using multisamples, try lowering it until we succeed if ( v.gl_att.multisampling.multisamples > 0 ) { v.gl_att.multisampling.multisamples -= 1; while ( v.gl_att.multisampling.multisamples > 1 && !ret ) { v.gl_att.multisampling.multibuffers = 1; ret = SDLX_CreateWindow(v.flags); if ( nullptr == ret ) { Log::get().warn("unable to create SDL window (%d multisamples): %s\n", v.gl_att.multisampling.multisamples, SDL_GetError()); } else { SDL_SetWindowSize(ret, v.horizontalResolution, v.verticalResolution); SDL_SetWindowPosition(ret, windowPos, windowPos); SDL_GLContext context = SDLX_CreateContext(ret, v.gl_att); if (!context) { Log::get().warn("unable to create GL context (%d multisamples): %s\n", v.gl_att.multisampling.multisamples, SDL_GetError()); SDL_DestroyWindow(ret); ret = nullptr; } } v.gl_att.multisampling.multisamples -= 1; } } } if (nullptr == ret) { // something is interfering with our ability to generate a screen. // assume that it is a complete incompatability with multisampling Log::get().warn("Disabled antialiasing\n"); v.gl_att.multisampling.multibuffers = 0; v.gl_att.multisampling.multisamples = 0; ret = SDLX_CreateWindow(v.flags); if ( nullptr == ret ) { Log::get().warn("unable to create SDL window (no multisamples): %s\n", SDL_GetError()); } else { SDL_SetWindowSize(ret, v.horizontalResolution, v.verticalResolution); SDL_SetWindowPosition(ret, windowPos, windowPos); SDL_GLContext context = SDLX_CreateContext(ret, v.gl_att); if (!context) { Log::get().warn("unable to create GL context (no multisamples): %s\n", SDL_GetError()); SDL_DestroyWindow(ret); ret = nullptr; } } } if (ret) { // grab the actual status of the multi_buffers and multi_samples v.gl_att.multisampling.multibuffers = 0; v.gl_att.multisampling.multisamples = 0; v.gl_att.accelerated_visual = SDL_FALSE; v.gl_att.multisampling.download(); #if !defined(ID_LINUX) SDL_GL_GetAttribute( SDL_GL_ACCELERATED_VISUAL, &( v.gl_att.accelerated_visual ) ); #endif // Swap interval needs a current context SDL_GL_SetSwapInterval(v.gl_att.swap_control); } } // Update the video parameters. Ego::GraphicsSystem::window = ret; if ( NULL != ret ) { SDLX_Get_Screen_Info( sdl_scr, make_report ); SDLX_synch_video_parameters( ret, &v ); } return ret; }
/* * @overload get_attribute(attr) * Get the acutal value for an attribute from current context. * * @param attr [Integer] the OpenGL attribute to query * @return [Integer] */ static VALUE GL_s_get_attribute(VALUE self, VALUE attr) { int value; HANDLE_ERROR(SDL_GL_GetAttribute(NUM2INT(attr), &value)); return INT2NUM(value); }
SDL_Window* Window::_create(const char* utf8Title, int width, int height) { lairAssert(!isValid()); // 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); unsigned windowFlags = 0 | SDL_WINDOW_OPENGL // | SDL_WINDOW_FULLSCREEN_DESKTOP ; _window = SDL_CreateWindow( utf8Title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, windowFlags); if(!_window) { log().error("Failed to create SDL window.", SDL_GetError()); return 0; } _glContext = SDL_GL_CreateContext(_window); if(!_glContext) { log().error("failed to create OpenGL context: ", SDL_GetError()); SDL_DestroyWindow(_window); return 0; } typedef std::pair<const char*, SDL_GLattr> GLAttr; GLAttr glAttrs[] = { std::make_pair("SDL_GL_RED_SIZE = ", SDL_GL_RED_SIZE), std::make_pair("SDL_GL_GREEN_SIZE = ", SDL_GL_GREEN_SIZE), std::make_pair("SDL_GL_BLUE_SIZE = ", SDL_GL_BLUE_SIZE), std::make_pair("SDL_GL_ALPHA_SIZE = ", SDL_GL_ALPHA_SIZE), std::make_pair("SDL_GL_BUFFER_SIZE = ", SDL_GL_BUFFER_SIZE), std::make_pair("SDL_GL_DOUBLEBUFFER = ", SDL_GL_DOUBLEBUFFER), std::make_pair("SDL_GL_DEPTH_SIZE = ", SDL_GL_DEPTH_SIZE), std::make_pair("SDL_GL_STENCIL_SIZE = ", SDL_GL_STENCIL_SIZE), std::make_pair("SDL_GL_ACCUM_RED_SIZE = ", SDL_GL_ACCUM_RED_SIZE), std::make_pair("SDL_GL_ACCUM_GREEN_SIZE = ", SDL_GL_ACCUM_GREEN_SIZE), std::make_pair("SDL_GL_ACCUM_BLUE_SIZE = ", SDL_GL_ACCUM_BLUE_SIZE), std::make_pair("SDL_GL_ACCUM_ALPHA_SIZE = ", SDL_GL_ACCUM_ALPHA_SIZE), std::make_pair("SDL_GL_STEREO = ", SDL_GL_STEREO), std::make_pair("SDL_GL_MULTISAMPLEBUFFERS = ", SDL_GL_MULTISAMPLEBUFFERS), std::make_pair("SDL_GL_MULTISAMPLESAMPLES = ", SDL_GL_MULTISAMPLESAMPLES), std::make_pair("SDL_GL_ACCELERATED_VISUAL = ", SDL_GL_ACCELERATED_VISUAL), // std::make_pair("SDL_GL_RETAINED_BACKING = ", SDL_GL_RETAINED_BACKING), std::make_pair("SDL_GL_CONTEXT_MAJOR_VERSION = ", SDL_GL_CONTEXT_MAJOR_VERSION), std::make_pair("SDL_GL_CONTEXT_MINOR_VERSION = ", SDL_GL_CONTEXT_MINOR_VERSION), // std::make_pair("SDL_GL_CONTEXT_EGL = ", SDL_GL_CONTEXT_EGL), std::make_pair("SDL_GL_CONTEXT_FLAGS = ", SDL_GL_CONTEXT_FLAGS), std::make_pair("SDL_GL_CONTEXT_PROFILE_MASK = ", SDL_GL_CONTEXT_PROFILE_MASK), std::make_pair("SDL_GL_SHARE_WITH_CURRENT_CONTEXT = ", SDL_GL_SHARE_WITH_CURRENT_CONTEXT), // std::make_pair("SDL_GL_FRAMEBUFFER_SRGB_CAPABLE = ", SDL_GL_FRAMEBUFFER_SRGB_CAPABLE), }; for(unsigned i = 0; i < (sizeof(glAttrs) / sizeof(GLAttr)); ++i) { int attr; SDL_GL_GetAttribute(glAttrs[i].second, &attr); log().info(glAttrs[i].first, attr); } return _window; }
Renderer::Renderer():ping(true) { //setup OpenGL parameters 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 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 0 ); //define video settings if(!SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 0, SDL_OPENGL))//|SDL_FULLSCREEN))// | { throw std::exception("SDL_SetVideoMode failed."); } log_file << "OpenGL Vendor: " << glGetString(GL_VENDOR) << std::endl; log_file << "OpenGL Renderer: " << glGetString(GL_RENDERER) << std::endl; log_file << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl; int value; log_file << "Display parameters: " << std::endl; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value); log_file << "SDL_GL_RED_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value); log_file << "SDL_GL_GREEN_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value); log_file << "SDL_GL_BLUE_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &value); log_file << "SDL_GL_ALPHA_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value); log_file << "SDL_GL_DEPTH_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_BUFFER_SIZE, &value); log_file << "SDL_GL_BUFFER_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &value); log_file << "SDL_GL_STENCIL_SIZE = " << value << std::endl; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &value); log_file << "SDL_GL_DOUBLEBUFFER = " << value << std::endl; glClearColor(0.0,0.0,0.0,1.0); //setup OpenGL glDisable(GL_LIGHTING); glShadeModel(GL_FLAT); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 1.0, 0.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); Init(); }
Graphics::PixelBuffer SurfaceSdlGraphicsManager::setupScreen(uint screenW, uint screenH, bool fullscreen, bool accel3d) { uint32 sdlflags; int bpp; closeOverlay(); #ifdef USE_OPENGL _opengl = accel3d; _antialiasing = 0; #endif _fullscreen = fullscreen; #ifdef USE_OPENGL if (_opengl) { if (ConfMan.hasKey("antialiasing")) _antialiasing = ConfMan.getInt("antialiasing"); 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); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); setAntialiasing(true); sdlflags = SDL_OPENGL; bpp = 24; } else #endif { bpp = 16; sdlflags = SDL_SWSURFACE; } if (_fullscreen) sdlflags |= SDL_FULLSCREEN; _screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags); #ifdef USE_OPENGL // If 32-bit with antialiasing failed, try 32-bit without antialiasing if (!_screen && _opengl && _antialiasing) { warning("Couldn't create 32-bit visual with AA, trying 32-bit without AA"); setAntialiasing(false); _screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags); } // If 32-bit failed, try 16-bit if (!_screen && _opengl) { warning("Couldn't create 32-bit visual, trying 16-bit"); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 1); setAntialiasing(true); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } // If 16-bit with antialiasing failed, try 16-bit without antialiasing if (!_screen && _opengl && _antialiasing) { warning("Couldn't create 16-bit visual with AA, trying 16-bit without AA"); setAntialiasing(false); _screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags); } #endif if (!_screen) { warning("Error: %s", SDL_GetError()); g_system->quit(); } #ifdef USE_OPENGL if (_opengl) { int glflag; const GLubyte *str; // apply atribute again for sure based on SDL docs SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); str = glGetString(GL_VENDOR); debug("INFO: OpenGL Vendor: %s", str); str = glGetString(GL_RENDERER); debug("INFO: OpenGL Renderer: %s", str); str = glGetString(GL_VERSION); debug("INFO: OpenGL Version: %s", str); SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &glflag); debug("INFO: OpenGL Red bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &glflag); debug("INFO: OpenGL Green bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &glflag); debug("INFO: OpenGL Blue bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &glflag); debug("INFO: OpenGL Alpha bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &glflag); debug("INFO: OpenGL Z buffer depth bits: %d", glflag); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &glflag); debug("INFO: OpenGL Double Buffer: %d", glflag); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &glflag); debug("INFO: OpenGL Stencil buffer bits: %d", glflag); #ifdef USE_OPENGL_SHADERS debug("INFO: GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); debug("INFO: GLEW Version: %s", glewGetString(GLEW_VERSION)); // GLEW needs to be initialized to use shaders GLenum err = glewInit(); if (err != GLEW_OK) { warning("Error: %s", glewGetErrorString(err)); g_system->quit(); } const GLfloat vertices[] = { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, }; // Setup the box shader used to render the overlay const char* attributes[] = { "position", "texcoord", NULL }; _boxShader = Graphics::Shader::fromStrings("box", Graphics::BuiltinShaders::boxVertex, Graphics::BuiltinShaders::boxFragment, attributes); _boxVerticesVBO = Graphics::Shader::createBuffer(GL_ARRAY_BUFFER, sizeof(vertices), vertices); _boxShader->enableVertexAttribute("position", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0); _boxShader->enableVertexAttribute("texcoord", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0); #endif } #endif _overlayWidth = screenW; _overlayHeight = screenH; #ifdef USE_OPENGL if (_opengl) { uint32 rmask, gmask, bmask, amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0x00001f00; gmask = 0x000007e0; bmask = 0x000000f8; amask = 0x00000000; #else rmask = 0x0000f800; gmask = 0x000007e0; bmask = 0x0000001f; amask = 0x00000000; #endif _overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16, rmask, gmask, bmask, amask); _overlayScreenGLFormat = GL_UNSIGNED_SHORT_5_6_5; } else #endif { _overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16, _screen->format->Rmask, _screen->format->Gmask, _screen->format->Bmask, _screen->format->Amask); } if (!_overlayscreen) { warning("Error: %s", SDL_GetError()); g_system->quit(); } /*_overlayFormat.bytesPerPixel = _overlayscreen->format->BytesPerPixel; // For some reason the values below aren't right, at least on my system _overlayFormat.rLoss = _overlayscreen->format->Rloss; _overlayFormat.gLoss = _overlayscreen->format->Gloss; _overlayFormat.bLoss = _overlayscreen->format->Bloss; _overlayFormat.aLoss = _overlayscreen->format->Aloss; _overlayFormat.rShift = _overlayscreen->format->Rshift; _overlayFormat.gShift = _overlayscreen->format->Gshift; _overlayFormat.bShift = _overlayscreen->format->Bshift; _overlayFormat.aShift = _overlayscreen->format->Ashift;*/ _overlayFormat = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0); _screenChangeCount++; SDL_PixelFormat *f = _screen->format; _screenFormat = Graphics::PixelFormat(f->BytesPerPixel, 8 - f->Rloss, 8 - f->Gloss, 8 - f->Bloss, 0, f->Rshift, f->Gshift, f->Bshift, f->Ashift); return Graphics::PixelBuffer(_screenFormat, (byte *)_screen->pixels); }
Renderer* Init(Settings vs) { assert(!initted); if (initted) return 0; // no mode set, find an ok one if ((vs.width <= 0) || (vs.height <= 0)) { const std::vector<VideoMode> modes = GetAvailableVideoModes(); assert(!modes.empty()); vs.width = modes.front().width; vs.height = modes.front().height; } const SDL_VideoInfo *info = SDL_GetVideoInfo(); //printf("SDL_GetVideoInfo says %d bpp\n", info->vfmt->BitsPerPixel); switch (info->vfmt->BitsPerPixel) { case 16: SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); break; case 24: case 32: SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); break; default: fprintf(stderr, "Invalid pixel depth: %d bpp\n", info->vfmt->BitsPerPixel); } SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, vs.requestedSamples ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, vs.requestedSamples); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vs.vsync); Uint32 flags = SDL_OPENGL; if (vs.fullscreen) flags |= SDL_FULLSCREEN; // attempt sequence is: // 1- requested mode SDL_Surface *scrSurface = SDL_SetVideoMode(vs.width, vs.height, info->vfmt->BitsPerPixel, flags); // 2- requested mode with no anti-aliasing (skipped if no AA was requested anyway) if (!scrSurface && vs.requestedSamples) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying without multisampling.\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); scrSurface = SDL_SetVideoMode(vs.width, vs.height, info->vfmt->BitsPerPixel, flags); } // 3- requested mode with 16 bit depth buffer if (!scrSurface) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying with 16-bit depth buffer\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, vs.requestedSamples ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, vs.requestedSamples); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); scrSurface = SDL_SetVideoMode(vs.width, vs.height, info->vfmt->BitsPerPixel, flags); } // 4- requested mode with 16-bit depth buffer and no anti-aliasing // (skipped if no AA was requested anyway) if (!scrSurface && vs.requestedSamples) { fprintf(stderr, "Failed to set video mode. (%s). Re-trying with 16-bit depth buffer and no multisampling\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); scrSurface = SDL_SetVideoMode(vs.width, vs.height, info->vfmt->BitsPerPixel, flags); } // 5- abort! if (!scrSurface) { OS::Error("Failed to set video mode: %s", SDL_GetError()); } // this valuable is not reliable if antialiasing settings are overridden by // nvidia/ati/whatever settings int actualSamples = 0; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &actualSamples); if (vs.requestedSamples != actualSamples) fprintf(stderr, "Requested AA mode: %dx, actual: %dx\n", vs.requestedSamples, actualSamples); glewInit(); if (!glewIsSupported("GL_ARB_vertex_buffer_object")) OS::Error("OpenGL extension ARB_vertex_buffer_object not supported. Pioneer can not run on your graphics card."); Renderer *renderer = 0; shadersAvailable = glewIsSupported("GL_VERSION_2_0"); shadersEnabled = vs.shaders && shadersAvailable; if (shadersEnabled) renderer = new RendererGL2(vs); else renderer = new RendererLegacy(vs); printf("Initialized %s\n", renderer->GetName()); initted = true; MaterialDescriptor desc; desc.vertexColors = true; vtxColorMaterial = renderer->CreateMaterial(desc); vtxColorMaterial->IncRefCount(); Graphics::settings = vs; return renderer; }
int SDLFrontend::init (int width, int height, bool fullscreen, EventHandler &eventHandler) { if (width == -1 && height == -1) fullscreen = true; info(LOG_CLIENT, String::format("initializing: %i:%i - fullscreen: %s", width, height, fullscreen ? "true" : "false")); INIT_Subsystem(SDL_INIT_VIDEO, true); INIT_Subsystem(SDL_INIT_JOYSTICK, false); INIT_Subsystem(SDL_INIT_GAMECONTROLLER, false); INIT_Subsystem(SDL_INIT_HAPTIC, false); initJoystickAndHaptic(); SDL_DisplayMode displayMode; SDL_GetDesktopDisplayMode(0, &displayMode); const char *name = SDL_GetPixelFormatName(displayMode.format); info(LOG_CLIENT, String::format("current desktop mode: %dx%d@%dHz (%s)", displayMode.w, displayMode.h, displayMode.refresh_rate, name)); if (width == -1) width = 800;//displayMode.w; if (height == -1) height = 480; //displayMode.h; setGLAttributes(); setHints(); int doubleBuffered = 0; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffered); info(LOG_CLIENT, String::format("doublebuffer: %s", doubleBuffered ? "activated" : "disabled")); int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; #ifdef __IPHONEOS__ flags |= SDL_WINDOW_RESIZABLE; #endif #if 1 //defined __IPHONEOS__ || defined __ANDROID__ if (fullscreen) flags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; #else if (fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_BORDERLESS; #endif const int videoDrivers = SDL_GetNumVideoDrivers(); for (int i = 0; i < videoDrivers; ++i) { info(LOG_CLIENT, String::format("available driver: %s", SDL_GetVideoDriver(i))); } info(LOG_CLIENT, String::format("driver: %s", SDL_GetCurrentVideoDriver())); const int displays = SDL_GetNumVideoDisplays(); info(LOG_CLIENT, String::format("found %i display(s)", displays)); if (fullscreen && displays > 1) { width = displayMode.w; height = displayMode.h; info(LOG_CLIENT, String::format("use fake fullscreen for the first display: %i:%i", width, height)); } _window = SDL_CreateWindow(Singleton<Application>::getInstance().getName().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags); if (!_window) { sdlCheckError(); return -1; } SDL_DisableScreenSaver(); initRenderer(); resetColor(); GLContext::get().init(); if (SDL_SetWindowBrightness(_window, 1.0f) == -1) sdlCheckError(); if (Config.isGrabMouse() && (!fullscreen || displays > 1)) { SDL_SetWindowGrab(_window, SDL_TRUE); } int screen = 0; int modes = SDL_GetNumDisplayModes(screen); info(LOG_CLIENT, "possible display modes:"); for (int i = 0; i < modes; i++) { SDL_GetDisplayMode(screen, i, &displayMode); name = SDL_GetPixelFormatName(displayMode.format); info(LOG_CLIENT, String::format("%dx%d@%dHz %s", displayMode.w, displayMode.h, displayMode.refresh_rate, name)); } // some platforms may override or hardcode the resolution - so // we have to query it here to get the actual resolution SDL_GetWindowSize(_window, &width, &height); if (SDL_SetRelativeMouseMode(SDL_TRUE) == -1) error(LOG_CLIENT, "no relative mouse mode support"); SDL_ShowCursor(0); info(LOG_CLIENT, String::format("actual resolution: %dx%d", width, height)); setVSync(ConfigManager::get().isVSync()); const int initState = IMG_Init(IMG_INIT_PNG); if (!(initState & IMG_INIT_PNG)) { sdlCheckError(); System.exit("No png support", 1); } _width = width; _height = height; updateViewport(0, 0, getWidth(), getHeight()); onInit(); _eventHandler = &eventHandler; _eventHandler->registerObserver(_console.get()); _eventHandler->registerObserver(this); info(LOG_CLIENT, "init the shader manager"); ShaderManager::get().init(); if (!Config.isSoundEnabled()) { info(LOG_CLIENT, "sound disabled"); } else if (!SoundControl.init(true)) { error(LOG_CLIENT, "sound initialization failed"); } return 0; }
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; }
SDL_Renderer * GLES_CreateRenderer(SDL_Window * window, Uint32 flags) { SDL_Renderer *renderer; GLES_RenderData *data; GLint value; int doublebuffer; if (!(window->flags & SDL_WINDOW_OPENGL)) { if (SDL_RecreateWindow(window, window->flags | SDL_WINDOW_OPENGL) < 0) { return NULL; } } renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); if (!renderer) { SDL_OutOfMemory(); return NULL; } data = (GLES_RenderData *) SDL_calloc(1, sizeof(*data)); if (!data) { GLES_DestroyRenderer(renderer); SDL_OutOfMemory(); return NULL; } renderer->ActivateRenderer = GLES_ActivateRenderer; renderer->DisplayModeChanged = GLES_DisplayModeChanged; renderer->CreateTexture = GLES_CreateTexture; renderer->QueryTexturePixels = GLES_QueryTexturePixels; renderer->SetTexturePalette = GLES_SetTexturePalette; renderer->GetTexturePalette = GLES_GetTexturePalette; renderer->SetTextureColorMod = GLES_SetTextureColorMod; renderer->SetTextureAlphaMod = GLES_SetTextureAlphaMod; renderer->SetTextureBlendMode = GLES_SetTextureBlendMode; renderer->SetTextureScaleMode = GLES_SetTextureScaleMode; renderer->UpdateTexture = GLES_UpdateTexture; renderer->LockTexture = GLES_LockTexture; renderer->UnlockTexture = GLES_UnlockTexture; renderer->DirtyTexture = GLES_DirtyTexture; renderer->RenderDrawPoints = GLES_RenderDrawPoints; renderer->RenderDrawLines = GLES_RenderDrawLines; renderer->RenderDrawRects = GLES_RenderDrawRects; renderer->RenderFillRects = GLES_RenderFillRects; renderer->RenderCopy = GLES_RenderCopy; renderer->RenderPresent = GLES_RenderPresent; renderer->DestroyTexture = GLES_DestroyTexture; renderer->DestroyRenderer = GLES_DestroyRenderer; renderer->info = GL_ES_RenderDriver.info; renderer->window = window; renderer->driverdata = data; renderer->info.flags = (SDL_RENDERER_PRESENTDISCARD | SDL_RENDERER_ACCELERATED); #if defined(__QNXNTO__) #if _NTO_VERSION<=641 /* QNX's OpenGL ES implementation is broken regarding */ /* packed textures support, affected versions 6.3.2, 6.4.0, 6.4.1 */ renderer->info.num_texture_formats = 2; renderer->info.texture_formats[0] = SDL_PIXELFORMAT_ABGR8888; renderer->info.texture_formats[1] = SDL_PIXELFORMAT_BGR24; #endif /* _NTO_VERSION */ #endif /* __QNXNTO__ */ if (GLES_LoadFunctions(data) < 0) { GLES_DestroyRenderer(renderer); return NULL; } data->context = SDL_GL_CreateContext(window); if (!data->context) { GLES_DestroyRenderer(renderer); return NULL; } if (SDL_GL_MakeCurrent(window, data->context) < 0) { GLES_DestroyRenderer(renderer); return NULL; } if (flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } if (SDL_GL_GetSwapInterval() > 0) { renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } if (SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doublebuffer) == 0) { if (!doublebuffer) { renderer->info.flags |= SDL_RENDERER_SINGLEBUFFER; } } #if SDL_VIDEO_DRIVER_PANDORA data->GL_OES_draw_texture_supported = SDL_FALSE; data->useDrawTexture = SDL_FALSE; #else if (SDL_GL_ExtensionSupported("GL_OES_draw_texture")) { data->GL_OES_draw_texture_supported = SDL_TRUE; data->useDrawTexture = SDL_TRUE; } else { data->GL_OES_draw_texture_supported = SDL_FALSE; data->useDrawTexture = SDL_FALSE; } #endif data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); renderer->info.max_texture_width = value; data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); renderer->info.max_texture_height = value; /* Set up parameters for rendering */ data->blendMode = -1; data->glDisable(GL_DEPTH_TEST); data->glDisable(GL_CULL_FACE); data->updateSize = SDL_TRUE; return renderer; }
SDL_Renderer * GLES_CreateRenderer(SDL_Window * window, Uint32 flags) { SDL_Renderer *renderer; GLES_RenderData *data; GLint value; Uint32 window_flags; int profile_mask = 0, major = 0, minor = 0; SDL_bool changed_window = SDL_FALSE; SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &major); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &minor); window_flags = SDL_GetWindowFlags(window); if (!(window_flags & SDL_WINDOW_OPENGL) || profile_mask != SDL_GL_CONTEXT_PROFILE_ES || major != RENDERER_CONTEXT_MAJOR || minor != RENDERER_CONTEXT_MINOR) { changed_window = SDL_TRUE; SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, RENDERER_CONTEXT_MAJOR); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, RENDERER_CONTEXT_MINOR); if (SDL_RecreateWindow(window, window_flags | SDL_WINDOW_OPENGL) < 0) { goto error; } } renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); if (!renderer) { SDL_OutOfMemory(); goto error; } data = (GLES_RenderData *) SDL_calloc(1, sizeof(*data)); if (!data) { GLES_DestroyRenderer(renderer); SDL_OutOfMemory(); goto error; } renderer->WindowEvent = GLES_WindowEvent; renderer->GetOutputSize = GLES_GetOutputSize; renderer->SupportsBlendMode = GLES_SupportsBlendMode; renderer->CreateTexture = GLES_CreateTexture; renderer->UpdateTexture = GLES_UpdateTexture; renderer->LockTexture = GLES_LockTexture; renderer->UnlockTexture = GLES_UnlockTexture; renderer->SetRenderTarget = GLES_SetRenderTarget; renderer->UpdateViewport = GLES_UpdateViewport; renderer->UpdateClipRect = GLES_UpdateClipRect; renderer->RenderClear = GLES_RenderClear; renderer->RenderDrawPoints = GLES_RenderDrawPoints; renderer->RenderDrawLines = GLES_RenderDrawLines; renderer->RenderFillRects = GLES_RenderFillRects; renderer->RenderCopy = GLES_RenderCopy; renderer->RenderCopyEx = GLES_RenderCopyEx; renderer->RenderReadPixels = GLES_RenderReadPixels; renderer->RenderPresent = GLES_RenderPresent; renderer->DestroyTexture = GLES_DestroyTexture; renderer->DestroyRenderer = GLES_DestroyRenderer; renderer->GL_BindTexture = GLES_BindTexture; renderer->GL_UnbindTexture = GLES_UnbindTexture; renderer->info = GLES_RenderDriver.info; renderer->info.flags = SDL_RENDERER_ACCELERATED; renderer->driverdata = data; renderer->window = window; data->context = SDL_GL_CreateContext(window); if (!data->context) { GLES_DestroyRenderer(renderer); goto error; } if (SDL_GL_MakeCurrent(window, data->context) < 0) { GLES_DestroyRenderer(renderer); goto error; } if (GLES_LoadFunctions(data) < 0) { GLES_DestroyRenderer(renderer); goto error; } if (flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } if (SDL_GL_GetSwapInterval() > 0) { renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } value = 0; data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); renderer->info.max_texture_width = value; value = 0; data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); renderer->info.max_texture_height = value; /* Android does not report GL_OES_framebuffer_object but the functionality seems to be there anyway */ if (SDL_GL_ExtensionSupported("GL_OES_framebuffer_object") || data->glGenFramebuffersOES) { data->GL_OES_framebuffer_object_supported = SDL_TRUE; renderer->info.flags |= SDL_RENDERER_TARGETTEXTURE; value = 0; data->glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &value); data->window_framebuffer = (GLuint)value; } data->framebuffers = NULL; if (SDL_GL_ExtensionSupported("GL_OES_blend_func_separate")) { data->GL_OES_blend_func_separate_supported = SDL_TRUE; } if (SDL_GL_ExtensionSupported("GL_OES_blend_equation_separate")) { data->GL_OES_blend_equation_separate_supported = SDL_TRUE; } if (SDL_GL_ExtensionSupported("GL_OES_blend_subtract")) { data->GL_OES_blend_subtract_supported = SDL_TRUE; } /* Set up parameters for rendering */ GLES_ResetState(renderer); return renderer; error: if (changed_window) { /* Uh oh, better try to put it back... */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile_mask); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); SDL_RecreateWindow(window, window_flags); } return NULL; }
int main( int argc, char *argv[] ) { projectMApp app; app.done = 0; int width = 784, height = 784; SDL_Init(SDL_INIT_VIDEO); // get an audio input device if (! selectAudioInput(&app)) { fprintf(stderr, "Failed to open audio input device\n"); return 1; } app.win = SDL_CreateWindow("projectM", 0, 0, width, height, 0); app.rend = SDL_CreateRenderer(app.win, 0, SDL_RENDERER_ACCELERATED); if (! app.rend) { fprintf(stderr, "Failed to create renderer: %s\n", SDL_GetError()); return PROJECTM_ERROR; } SDL_SetWindowTitle(app.win, "SDL Fun Party Time"); printf("SDL init version 2\n"); #ifdef PANTS if ( fsaa ) { SDL_GL_GetAttribute( SDL_GL_MULTISAMPLEBUFFERS, &value ); printf( "SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value ); SDL_GL_GetAttribute( SDL_GL_MULTISAMPLESAMPLES, &value ); printf( "SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value ); } #endif app.settings.meshX = 1; app.settings.meshY = 1; app.settings.fps = FPS; app.settings.textureSize = 2048; // idk? app.settings.windowWidth = width; app.settings.windowHeight = height; app.settings.smoothPresetDuration = 3; // seconds app.settings.presetDuration = 5; // seconds app.settings.beatSensitivity = 0.8; app.settings.aspectCorrection = 1; app.settings.easterEgg = 0; // ??? app.settings.shuffleEnabled = 1; app.settings.softCutRatingsEnabled = 1; // ??? app.settings.presetURL = "presets/presets_tryptonaut"; app.settings.menuFontURL = "fonts/Vera.ttf"; app.settings.titleFontURL = "fonts/Vera.ttf"; // init projectM app.pm = new projectM(app.settings); app.pm->selectRandom(true); app.pm->projectM_resetGL(width, height); // standard main loop const Uint32 frame_delay = 1000/FPS; Uint32 last_time = SDL_GetTicks(); while (! app.done) { renderFrame(&app); Uint32 elapsed = SDL_GetTicks() - last_time; if (elapsed < frame_delay) SDL_Delay(frame_delay - elapsed); last_time = SDL_GetTicks(); } return PROJECTM_SUCCESS; }