/*** Función inicializadora de SDL y OpenGL ***/ GLboolean InitOpenGL(int width, int height, // Dimensiones de la ventana int bpp, // Profundidad int depth, // Z-buffer GLboolean fullscreen) // Fullscreen? { /* Inicialización de SDL */ if( SDL_Init( SDL_INIT_VIDEO ) != 0 ) { Error_SDL( "Error initializing SDL" ); return GL_FALSE; } /* Pongo el fondo en 32 bits */ if( bpp == 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 ); } else if( bpp == 16 ) // 16 bits { SDL_GL_SetAttribute( SDL_GL_RED_SIZE , 4 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 4 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE , 4 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 4 ); } /* Framebuffer */ SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, bpp ); /* Z-buffer */ SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, depth ); /* Stencil buffer */ SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); /* Habilito el doble-buffering de OpengGL */ SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* Creo la ventana con soporte OpenGL */ if( SDL_SetVideoMode( width, height, bpp, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0) ) == NULL ) { Error_SDL( "Could not init OpenGL" ); return GL_FALSE; } /* Título de la ventana */ SDL_WM_SetCaption( "OpenGL", "OpenGL" ); /* Mensajes de Input directo a la aplicación */ SDL_WM_GrabInput( SDL_GRAB_ON ); /* Deshabilito la repetición del teclado */ SDL_EnableKeyRepeat( 0, SDL_DEFAULT_REPEAT_INTERVAL ); /* Inicializo los número aleatorios */ srand( time(NULL) ); return GL_TRUE; }
int main(int argc, char *argv[]) { std::string app_name; std::string app_name_nice; float zoom = 1.0f; bool tablet = false; bool aspect43 = false; const char *zoomenv = getenv("ZOOM"); const char *tabletenv = getenv("TABLET"); const char *ipad = getenv("IPAD"); if (zoomenv) { zoom = atof(zoomenv); } if (tabletenv) { tablet = atoi(tabletenv) ? true : false; } if (ipad) aspect43 = true; bool landscape; NativeGetAppInfo(&app_name, &app_name_nice, &landscape); // Change these to temporarily test other resolutions. aspect43 = false; tablet = false; float density = 1.0f; //zoom = 1.5f; if (landscape) { if (tablet) { pixel_xres = 1280 * zoom; pixel_yres = 800 * zoom; } else if (aspect43) { pixel_xres = 1024 * zoom; pixel_yres = 768 * zoom; } else { pixel_xres = 800 * zoom; pixel_yres = 480 * zoom; } } else { // PC development hack for more space //pixel_xres = 1580 * zoom; //pixel_yres = 1000 * zoom; if (tablet) { pixel_xres = 800 * zoom; pixel_yres = 1280 * zoom; } else if (aspect43) { pixel_xres = 768 * zoom; pixel_yres = 1024 * zoom; } else { pixel_xres = 480 * zoom; pixel_yres = 800 * zoom; } } net::Init(); #ifdef __APPLE__ // Make sure to request a somewhat modern GL context at least - the // latest supported by MacOSX (really, really sad...) // Requires SDL 2.0 (which is even more sad, as that hasn't been released yet) //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); #endif if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 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_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); if (SDL_SetVideoMode(pixel_xres, pixel_yres, 0, SDL_OPENGL) == NULL) { fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError()); SDL_Quit(); return(2); } SDL_WM_SetCaption(app_name_nice.c_str(), NULL); if (GLEW_OK != glewInit()) { printf("Failed to initialize glew!\n"); return 1; } if (GLEW_VERSION_2_0) { printf("OpenGL 2.0 or higher.\n"); } else { printf("Sorry, this program requires OpenGL 2.0.\n"); return 1; } #ifdef _MSC_VER // VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\")); TCHAR path[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path); PathAppend(path, (app_name + "\\").c_str()); #else // Mac / Linux char path[512]; const char *the_path = getenv("HOME"); if (!the_path) { struct passwd* pwd = getpwuid(getuid()); if (pwd) the_path = pwd->pw_dir; } strcpy(path, the_path); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef _WIN32 NativeInit(argc, (const char **)argv, path, "D:\\", "BADCOFFEE"); #else NativeInit(argc, (const char **)argv, path, "/tmp", "BADCOFFEE"); #endif dp_xres = (float)pixel_xres * density / zoom; dp_yres = (float)pixel_yres * density / zoom; pixel_in_dps = (float)pixel_xres / dp_xres; NativeInitGraphics(); float dp_xscale = (float)dp_xres / pixel_xres; float dp_yscale = (float)dp_yres / pixel_yres; printf("Pixels: %i x %i\n", pixel_xres, pixel_yres); printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres); SDL_AudioSpec fmt; fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 1024; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, NULL) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); return 1; } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); InputState input_state; int framecount = 0; bool nextFrameMD = 0; float t = 0; while (true) { input_state.accelerometer_valid = false; input_state.mouse_valid = true; int quitRequested = 0; SDL_Event event; while (SDL_PollEvent(&event)) { float mx = event.motion.x * dp_xscale; float my = event.motion.y * dp_yscale; if (event.type == SDL_QUIT) { quitRequested = 1; } else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { quitRequested = 1; } } else if (event.type == SDL_MOUSEMOTION) { input_state.pointer_x[0] = mx; input_state.pointer_y[0] = my; NativeTouch(0, mx, my, 0, TOUCH_MOVE); } else if (event.type == SDL_MOUSEBUTTONDOWN) { if (event.button.button == SDL_BUTTON_LEFT) { //input_state.mouse_buttons_down = 1; input_state.pointer_down[0] = true; nextFrameMD = true; NativeTouch(0, mx, my, 0, TOUCH_DOWN); } } else if (event.type == SDL_MOUSEBUTTONUP) { if (event.button.button == SDL_BUTTON_LEFT) { input_state.pointer_down[0] = false; nextFrameMD = false; //input_state.mouse_buttons_up = 1; NativeTouch(0, mx, my, 0, TOUCH_UP); } } } if (quitRequested) break; const uint8 *keys = (const uint8 *)SDL_GetKeyState(NULL); if (keys[SDLK_ESCAPE]) break; SimulateGamepad(keys, &input_state); UpdateInputState(&input_state); NativeUpdate(input_state); NativeRender(); EndInputState(&input_state); if (framecount % 60 == 0) { // glsl_refresh(); // auto-reloads modified GLSL shaders once per second. } SDL_GL_SwapBuffers(); // Simple frame rate limiting while (time_now() < t + 1.0f/60.0f) { sleep_ms(0); time_update(); } time_update(); t = time_now(); framecount++; } // Faster exit, thanks to the OS. Remove this if you want to debug shutdown // The speed difference is only really noticable on Linux. On Windows you do notice it though #ifdef _WIN32 exit(0); #endif NativeShutdownGraphics(); SDL_PauseAudio(1); SDL_CloseAudio(); NativeShutdown(); SDL_Quit(); net::Shutdown(); exit(0); return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow) { #else int main(int argc, char** argv) { #endif // Start by opening a debug log. Debug::openLog(true); Debug::logger->message("\n ----- Engine Loading -----"); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { Debug::logger->message("Error: Could not load SDL"); Destroy(); return 1; } else { Debug::logger->message("SDL loaded.."); } // Setup OpenGL. 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_DOUBLEBUFFER, 1); flags = SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE; screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, flags); Debug::logger->message("Video mode set.."); if(Mix_OpenAudio(44100, AUDIO_S16, 2, 4096)) { Debug::logger->message("Audio opened.."); } if(TTF_Init()) { Debug::logger->message("SDL_ttf initialized.\n"); } info = SDL_GetVideoInfo(); if(!info) { // This should never accur. Debug::logger->message("Video query failed!"); Destroy(); return 1; } SDL_WM_SetCaption("LibD", NULL); srand((unsigned int)time(NULL)); Debug::logger->message("\n ----- Engine Initialization Complete -----"); Debug::logger->message("\n ----- Logic -----"); Game game; game.Init(); CreateInput(); Uint32 timeStart = SDL_GetTicks(); float dt = 1.0f / 60.0f; // We need to give OnResize()'s width and height params an initial value // Otherwise it is just garbage, and the orthorgraphic view // screws up for me. -- Allanis. game.OnResize(windowWidth, windowHeight); while(game.IsRunning()) { while(SDL_PollEvent(&event)) { if((event.type == SDL_QUIT) || KeyStillDown(SDLK_ESCAPE)) { game.SetRunning(false); break; } if(event.type == SDL_VIDEORESIZE) { // Resize the window. ResizeWindow(game, event.resize.w, event.resize.h); break; } } UpdateInput(); game.Prepare(dt); game.ProcessEvents(dt); game.Render(); SDL_GL_SwapBuffers(); Uint32 timeEnd = SDL_GetTicks(); dt = (float)(timeEnd - timeStart) / 1000.0f; timeStart = timeEnd; } game.Shutdown(); Destroy(); Debug::closeLog(); return 0; }
static void PlatformInitOpenGL(void*& ContextPtr, void*& PrevContextPtr, int InMajorVersion, int InMinorVersion) { static bool bInitialized = (SDL_GL_GetCurrentWindow() != NULL) && (SDL_GL_GetCurrentContext() != NULL); if (!bInitialized) { check(InMajorVersion > 3 || (InMajorVersion == 3 && InMinorVersion >= 2)); if (SDL_WasInit(0) == 0) { SDL_Init(SDL_INIT_VIDEO); } else { Uint32 InitializedSubsystemsMask = SDL_WasInit(SDL_INIT_EVERYTHING); if ((InitializedSubsystemsMask & SDL_INIT_VIDEO) == 0) { SDL_InitSubSystem(SDL_INIT_VIDEO); } } if (SDL_GL_LoadLibrary(NULL)) { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("Unable to dynamically load libGL: %s"), ANSI_TO_TCHAR(SDL_GetError())); } if (SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, InMajorVersion)) { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("Failed to set GL major version: %s"), ANSI_TO_TCHAR(SDL_GetError())); } if (SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, InMinorVersion)) { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("Failed to set GL minor version: %s"), ANSI_TO_TCHAR(SDL_GetError())); } if (SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)) { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("Failed to set GL flags: %s"), ANSI_TO_TCHAR(SDL_GetError())); } if (SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)) { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("Failed to set GL mask/profile: %s"), ANSI_TO_TCHAR(SDL_GetError())); } // Create a dummy context to verify opengl support. FPlatformOpenGLContext DummyContext; _PlatformCreateDummyGLWindow(&DummyContext); _PlatformCreateOpenGLContextCore(&DummyContext); if (DummyContext.hGLContext) { _ContextMakeCurrent(DummyContext.hWnd, DummyContext.hGLContext); } else { UE_LOG(LogOpenGLShaderCompiler, Fatal, TEXT("OpenGL %d.%d not supported by driver"), InMajorVersion, InMinorVersion); return; } PrevContextPtr = NULL; ContextPtr = DummyContext.hGLContext; bInitialized = true; } PrevContextPtr = reinterpret_cast<void*>(SDL_GL_GetCurrentContext()); SDL_HGLContext NewContext = SDL_GL_CreateContext(SDL_GL_GetCurrentWindow()); SDL_GL_MakeCurrent(SDL_GL_GetCurrentWindow(), NewContext); ContextPtr = reinterpret_cast<void*>(NewContext); }
int main( int argc, char* argv[] ) { bool fullscreen = false; char* world = "world"; for (int i=0; i<argc; i++) { if (strcmp(argv[i], "-win") == 0) fullscreen = false; if (strcmp(argv[i], "-f") == 0) fullscreen = true; if (strcmp(argv[i], "-w") == 0) world = argv[i+1]; if (strcmp(argv[i], "-d") == 0) debug = true; } SetupWorld(world); you_x = getWorldX(); you_z = getWorldZ(); you_angle = getWorldAngle(); const SDL_VideoInfo* info = NULL; int width = 0; int height = 0; int bpp = 0; int flags = 0; if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) ); quit_app( 1 ); } info = SDL_GetVideoInfo( ); if( !info ) { fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) ); quit_app( 1 ); } width = 640; height = 480; bpp = info->vfmt->BitsPerPixel; 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 ); flags = SDL_OPENGL; if (fullscreen) flags |= SDL_FULLSCREEN; if( SDL_SetVideoMode( width, height, bpp, flags ) == 0 ) { fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); quit_app( 1 ); } setup_opengl( width, height ); bool init = true; while( 1 ) { process_events( ); draw_screen( ); if (init) { glEnable( GL_LIGHTING ); init=false; } } return 0; }
bool gl_initialize(int screen_wid,int screen_high,int fsaa_mode,char *err_str) { int sdl_flags; GLint ntxtsize; #if defined(D3_OS_LINUX) || defined(D3_OS_WINDOWS) GLenum glew_error; #endif #ifdef D3_OS_IPHONE const GLenum discards[]={GL_DEPTH_ATTACHMENT,GL_STENCIL_ATTACHMENT}; #endif // reset sizes to the desktop // if they are at default if ((screen_wid==-1) || (screen_high==-1)) { screen_wid=render_info.desktop.wid; screen_high=render_info.desktop.high; } // setup rendering sizes #ifndef D3_ROTATE_VIEW view.screen.x_sz=screen_wid; view.screen.y_sz=screen_high; #else view.screen.x_sz=screen_high; view.screen.y_sz=screen_wid; #endif view.screen.wide=gl_is_size_widescreen(view.screen.x_sz,view.screen.y_sz); // normal attributes 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_STENCIL_SIZE,8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); #ifdef D3_OPENGL_ES SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION,2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION,0); #endif #ifdef D3_OS_IPHONE SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING,1); #endif // full screen anti-aliasing attributes switch (fsaa_mode) { case fsaa_mode_2x: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,2); break; case fsaa_mode_4x: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,4); break; case fsaa_mode_8x: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,8); break; } // start window or full screen sdl_flags=SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN; if (!gl_in_window_mode()) sdl_flags|=(SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS); sdl_wind=SDL_CreateWindow("dim3",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,screen_wid,screen_high,sdl_flags); if (sdl_wind==NULL) { sprintf(err_str,"SDL: Could not create window (Error: %s)",SDL_GetError()); return(FALSE); } sdl_gl_ctx=SDL_GL_CreateContext(sdl_wind); // use glew on linux and windows #if defined(D3_OS_LINUX) || defined(D3_OS_WINDOWS) glew_error=glewInit(); if (glew_error!=GL_NO_ERROR) { strcpy(err_str,glewGetErrorString(glew_error)); return(FALSE); } #endif // grab openGL attributes strncpy(render_info.name,(char*)glGetString(GL_RENDERER),64); render_info.name[63]=0x0; strncpy(render_info.ext_string,(char*)glGetString(GL_EXTENSIONS),8192); render_info.ext_string[8191]=0x0; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&ntxtsize); render_info.texture_max_size=(int)ntxtsize; if (!gl_check_initialize(err_str)) return(FALSE); // stick refresh rate to 60 render_info.monitor_refresh_rate=60; #ifndef D3_ROTATE_VIEW gl_set_viewport(0,0,view.screen.x_sz,view.screen.y_sz); #else gl_set_viewport(0,0,view.screen.y_sz,view.screen.x_sz); #endif gl_setup_context(); #ifndef D3_OPENGL_ES if (fsaa_mode!=fsaa_mode_none) glEnable(GL_MULTISAMPLE); #endif // clear the entire window so it doesn't flash glClearColor(0.0f,0.0f,0.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT); #ifdef D3_OS_IPHONE glDiscardFramebufferEXT(GL_FRAMEBUFFER,2,discards); #endif SDL_GL_SwapWindow(sdl_wind); // texture utility initialize gl_texture_initialize(); return(TRUE); }
void SDLWindow::create(const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) { int colourDepth = 32; String title = name; if(miscParams) { // Parse miscellenous parameters NameValuePairList::const_iterator opt; // Bit depth opt = miscParams->find("colourDepth"); if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it... colourDepth = StringConverter::parseUnsignedInt(opt->second); // Full screen antialiasing opt = miscParams->find("FSAA"); if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it... { size_t fsaa_x_samples = StringConverter::parseUnsignedInt(opt->second); if(fsaa_x_samples>1) { // If FSAA is enabled in the parameters, enable the MULTISAMPLEBUFFERS // and set the number of samples before the render window is created. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,fsaa_x_samples); } } // Window title opt = miscParams->find("title"); if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it... title = opt->second; } LogManager::getSingleton().logMessage("SDLWindow::create", LML_TRIVIAL); SDL_Surface* screen; int flags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE; SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // request good stencil size if 32-bit colour if (colourDepth == 32) { SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8); } if (fullScreen) flags |= SDL_FULLSCREEN; LogManager::getSingleton().logMessage("Create window", LML_TRIVIAL); screen = SDL_SetVideoMode(width, height, colourDepth, flags); if (!screen) { LogManager::getSingleton().logMessage(LML_CRITICAL, String("Could not make screen: ") + SDL_GetError()); exit(1); } LogManager::getSingleton().logMessage("screen is valid", LML_TRIVIAL); mScreen = screen; mName = name; mWidth = width; mHeight = height; mActive = true; if (!fullScreen) SDL_WM_SetCaption(title.c_str(), 0); glXGetVideoSyncSGI = (int (*)(unsigned int *))SDL_GL_GetProcAddress("glXGetVideoSyncSGI"); glXWaitVideoSyncSGI = (int (*)(int, int, unsigned int *))SDL_GL_GetProcAddress("glXWaitVideoSyncSGI"); }
void check_gl_mode() { char str[400]; flags = SDL_OPENGL; if(full_screen) { flags |= SDL_FULLSCREEN; } SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8); #ifdef FSAA if (fsaa > 1) { if (!SDL_VideoModeOK(window_width, window_height, bpp, flags)) { safe_snprintf(str, sizeof(str), "Can't use fsaa mode x%d, disabling it.", fsaa); LOG_TO_CONSOLE(c_yellow1, str); LOG_WARNING("%s\n", str); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); fsaa = 0; } } #endif /* FSAA */ //now, test if the video mode is OK... if(!SDL_VideoModeOK(window_width, window_height, bpp, flags)) { char vid_mode_str[25]; safe_snprintf (vid_mode_str, sizeof (vid_mode_str), "%ix%ix%i", window_width, window_height, bpp); safe_snprintf(str,sizeof(str),no_stencil_str,vid_mode_str); LOG_TO_CONSOLE(c_red1,str); LOG_ERROR("%s\n",str); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0); have_stencil=0; //now, test if the video mode is OK... if(!SDL_VideoModeOK(window_width, window_height, bpp, flags)) { int old_width; int old_height; int old_bpp; old_width=window_width; old_height=window_height; old_bpp=bpp; window_width=640; window_height=480; bpp=32; safe_snprintf (vid_mode_str, sizeof (vid_mode_str), "%ix%ix%i", old_width, old_height, old_bpp); safe_snprintf(str,sizeof(str),safemode_str,vid_mode_str); LOG_TO_CONSOLE(c_red1,str); LOG_ERROR("%s\n",str); full_screen=1; video_mode=2; } } else have_stencil=1; }
void init_video() { char str[400]; int rgb_size[3]; setup_video_mode(full_screen, video_mode); /* Detect the display depth */ if(!bpp) { if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) { bpp = 8; } else if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 16 ) { bpp = 16; /* More doesn't seem to work */ } else bpp=32; } //adjust the video mode accordingly if (video_mode == 0) { //do nothing } else if(bpp==16) { if(!(video_mode%2)) video_mode-=1; } else { if(video_mode%2) video_mode+=1; } /* Initialize the display */ switch (bpp) { case 8: rgb_size[0] = 2; rgb_size[1] = 3; rgb_size[2] = 3; 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; } // Mac OS X will always use 8-8-8-8 ARGB for 32-bit screens and 5-5-5 RGB for 16-bit screens #ifndef OSX 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] ); #endif #ifdef OSX // enable V-SYNC SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1 ); #endif SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); #ifdef FSAA if (fsaa > 1) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa); glDisable(GL_MULTISAMPLE); } #endif /* FSAA */ check_gl_mode(); #ifdef OTHER_LIFE SDL_WM_SetIcon(SDL_LoadBMP("ol_icon.bmp"), NULL); #else SDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"), NULL); #endif /* Set the window manager title bar */ #ifdef FSAA if (fsaa > 1) { if (!SDL_SetVideoMode(window_width, window_height, bpp, flags)) { safe_snprintf(str, sizeof(str), "Can't use fsaa mode x%d, disabling it.", fsaa); LOG_TO_CONSOLE(c_yellow1, str); LOG_WARNING("%s\n", str); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); fsaa = 0; } } #endif /* FSAA */ //try to find a stencil buffer (it doesn't always work on Linux) if(!SDL_SetVideoMode(window_width, window_height, bpp, flags)) { LOG_TO_CONSOLE(c_red1,no_hardware_stencil_str); LOG_ERROR("%s\n",no_hardware_stencil_str); if(bpp!=32) { LOG_TO_CONSOLE(c_grey1,suggest_24_or_32_bit); LOG_ERROR("%s\n",suggest_24_or_32_bit); } SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,0); if(!SDL_SetVideoMode( window_width, window_height, bpp, flags)) { LOG_ERROR("%s: %s\n", fail_opengl_mode, SDL_GetError()); SDL_Quit(); exit(1); } have_stencil=0; } #ifdef WINDOWS //try to see if we get hardware acceleration, or the windows generic shit { int len; GLubyte *my_string; int have_hardware; my_string=(GLubyte *)glGetString(GL_RENDERER); if (my_string == NULL) { len = 0; have_hardware = 0; LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed"); LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed"); } else { len=strlen(my_string); have_hardware=get_string_occurance("gdi generic",my_string,len,0); } if(have_hardware != -1) { //let the user know there is a problem LOG_TO_CONSOLE(c_red1,stencil_falls_back_on_software_accel); LOG_ERROR("%s\n",stencil_falls_back_on_software_accel); //first, shut down this mode we have now. 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_ALPHA_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1); if(full_screen)flags=SDL_OPENGL|SDL_FULLSCREEN; SDL_SetVideoMode(window_width, window_height, bpp, flags); have_stencil=0; my_string=(GLubyte *)glGetString(GL_RENDERER); if (my_string == NULL) { len = 0; have_hardware = 0; LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed"); LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed"); } else { len=strlen(my_string); have_hardware=get_string_occurance("gdi generic",my_string,len,0); } if(have_hardware != -1) { //wtf, this really shouldn't happen.... //let's try a default mode, maybe Quake 2's mode, and pray it works LOG_TO_CONSOLE(c_red1,last_chance_str); LOG_ERROR("%s\n",last_chance_str); 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, 0); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1); flags=SDL_OPENGL|SDL_FULLSCREEN; full_screen=1; video_mode=2; window_width=640; window_height=480; bpp=32; SDL_SetVideoMode(window_width, window_height, bpp, flags); //see if it worked... my_string=(GLubyte *)glGetString(GL_RENDERER); if (my_string == NULL) { len = 0; have_hardware = 0; LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed"); LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed"); } else { len=strlen(my_string); have_hardware=get_string_occurance("gdi generic",my_string,len,0); } if(have_hardware != -1) { //wtf, this really shouldn't happen.... //let's try a default mode, maybe Quake 2's mode, and pray it works LOG_TO_CONSOLE(c_red1,software_mode_str); LOG_ERROR("%s\n",software_mode_str); } } } } #endif glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_NORMALIZE); glClearStencil(0); #ifdef ANTI_ALIAS if (anti_alias) { glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); } else { glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST); glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST); glDisable(GL_POINT_SMOOTH); glDisable(GL_LINE_SMOOTH); glDisable(GL_POLYGON_SMOOTH); } #endif SDL_EnableKeyRepeat(200, 100); SDL_EnableUNICODE(1); build_video_mode_array(); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &have_stencil); last_texture=-1; //no active texture #ifdef OPENGL_TRACE CHECK_GL_ERRORS(); #endif //OPENGL_TRACE change_minimap(); check_options(); }
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #else int main(int argc, char** argv) { #endif SDL_Surface *screen_sfc; F1SpiritApp *game; KEYBOARDSTATE *k; int time, act_time; SDL_Event event; bool quit = false; bool need_to_redraw = true; #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Application started\n"); #endif #ifdef HAVE_GLES fullscreen = true; #endif screen_sfc = initialization((fullscreen ? SDL_FULLSCREEN : 0)); if (screen_sfc == 0) return 0; k = new KEYBOARDSTATE(); game = new F1SpiritApp(); #if 0//ndef HAVE_GLES // why recreating the context ??? if (fullscreen) { #ifdef HAVE_GLES EGL_Close(); screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, (fullscreen ? SDL_FULLSCREEN : 0)); EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #else screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); #endif SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; #ifndef HAVE_GLES 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_DOUBLEBUFFER, 1); #endif } #endif time = init_time = SDL_GetTicks(); IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG); while (!quit) { while ( SDL_PollEvent( &event ) ) { switch ( event.type ) { /* Keyboard event */ case SDL_KEYDOWN: #ifdef __APPLE__ if (event.key.keysym.sym == SDLK_q) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers &KMOD_META) != 0) { quit = true; } } #else if (event.key.keysym.sym == SDLK_F12) { quit = true; } #endif if (event.key.keysym.sym == SDLK_F10) { game->save_configuration("f1spirit.cfg"); game->load_configuration("f1spirit.cfg"); } #ifdef _WIN32 if (event.key.keysym.sym == SDLK_F4) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) quit = true; } #endif #ifdef __APPLE__ if (event.key.keysym.sym == SDLK_f) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_META) != 0) { /* Toggle FULLSCREEN mode: */ if (fullscreen) fullscreen = false; else fullscreen = true; screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; 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_DOUBLEBUFFER, 1); } } #else if (event.key.keysym.sym == SDLK_RETURN) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) { /* Toggle FULLSCREEN mode: */ if (fullscreen) fullscreen = false; else fullscreen = true; #ifndef HAVE_GLES #ifdef HAVE_GLES EGL_Close(); screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #else screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); #endif calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; #ifndef HAVE_GLES 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_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #endif #endif } } #endif if (event.key.keysym.sym == SDLK_f) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) { /* toggle FPS mode: */ if (show_fps) show_fps = false; else show_fps = true; } } /* Keyboard event */ SDL_keysym *ks; ks = new SDL_keysym(); *ks = event.key.keysym; k->keyevents.Add(ks); break; /* SDL_QUIT event (window close) */ case SDL_QUIT: quit = true; break; } } act_time = SDL_GetTicks(); if (act_time - time >= REDRAWING_PERIOD) { int max_frame_step = 10; /* frames_per_sec_tmp+=1; if ((act_time-init_time)>=1000) { frames_per_sec=frames_per_sec_tmp; frames_per_sec_tmp=0; init_time=act_time; } // if */ // On PANDORA, let's target 25 fps... int min_frame=1; #ifdef PANDORA min_frame=2; #endif do { time += REDRAWING_PERIOD; if ((act_time - time) > 10*REDRAWING_PERIOD) time = act_time; /* cycle */ k->cycle(); if (!game->cycle(k)) quit = true; need_to_redraw = true; k->keyevents.Delete(); act_time = SDL_GetTicks(); max_frame_step--; min_frame--; } while (((act_time - time >= REDRAWING_PERIOD) && (max_frame_step > 0)) || (min_frame > 0)); } /* Redraw */ if (need_to_redraw) { game->draw(); need_to_redraw = false; frames_per_sec_tmp += 1; } if ((act_time - init_time) >= 1000) { frames_per_sec = frames_per_sec_tmp; frames_per_sec_tmp = 0; init_time = act_time; } #ifndef PANDORA SDL_Delay(1); #endif } delete k; k = 0; delete game; game = 0; Stop_playback(); finalization(); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Application finished\n"); close_debug_messages(); #endif return 0; } /* main */
SDL_Surface *initialization(int flags) { const SDL_VideoInfo* info = 0; int bpp = 0; SDL_Surface *screen; rg = new TRanrotBGenerator(0); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing SDL\n"); #endif if (SDL_Init(SDL_INIT_VIDEO | (sound ? SDL_INIT_AUDIO : 0) | SDL_INIT_JOYSTICK | SDL_INIT_EVENTTHREAD) < 0) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video initialization failed: %s\n", SDL_GetError()); #endif return 0; } #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("SDL initialized\n"); #endif info = SDL_GetVideoInfo(); if (!info) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video query failed: %s\n", SDL_GetError()); #endif return 0; } if (fullscreen) { bpp = COLOUR_DEPTH; } else { bpp = info->vfmt->BitsPerPixel; } desktopW = info->current_w; desktopH = info->current_h; #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Setting OpenGL attributes\n"); #endif #ifndef HAVE_GLES 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_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("OpenGL attributes set\n"); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing video mode\n"); #endif #ifdef HAVE_GLES fullscreen = true; flags = SDL_FULLSCREEN; #else flags = SDL_OPENGL | flags; #endif screen = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, bpp, flags); if (screen == 0) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video mode set failed: %s\n", SDL_GetError()); #endif return 0; } #ifdef HAVE_GLES EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video mode initialized\n"); #endif calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_WM_SetIcon(SDL_LoadBMP("graphics/f1sicon.bmp"), NULL); SDL_ShowCursor(SDL_DISABLE); if (sound) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing Audio\n"); #endif N_SFX_CHANNELS = Sound_initialization(N_SFX_CHANNELS, 0); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Audio initialized\n"); #endif } // Network: #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing SDL_net...\n"); #endif if (SDLNet_Init() == -1) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Error initializing SDL_net: %s.\n", SDLNet_GetError()); #endif network = false; } else { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("SDL_net initialized.\n"); #endif network = true; } SDL_EnableUNICODE(1); glGetIntegerv(GL_STENCIL_BITS, &g_stencil_bits); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("OpenGL stencil buffer bits: %i\n", g_stencil_bits); #endif return screen; } /* initialization */
void CreateDisplay( void ) { Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI; if ( SDL_Init( SDL_INIT_VIDEO ) != 0 ) { return; } if ( vid_noBorder->GetBool() ) { windowFlags |= SDL_WINDOW_BORDERLESS; } // targeting OpenGL 3.1 core SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); uint32_t contextFlags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; if ( Common::com_developer->GetBool() ) { contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; } #ifdef _DEBUG contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; #endif SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, contextFlags ); int multisample = r_multisample->GetInt32(); if ( multisample > 0 ) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); //TODO: find the highest significant bit to ensure samples^2 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, multisample ); } else { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 ); } int32_t width = vid_width->GetInt32(); int32_t height = vid_height->GetInt32(); window = SDL_CreateWindow( WINDOW_TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, windowFlags ); SDL_assert( window && "Failed to create window" ); // when creating a fullscreen window, the actual width/height may not be what was requested // certain drawing code relies on knowing the width/height of the display, so we'll update it with the // proper values SDL_GetWindowSize( window, &width, &height ); vid_width->Set( width ); vid_height->Set( height ); context = SDL_GL_CreateContext( window ); SDL_assert( context && "Failed to create OpenGL context on window" ); SDL_GL_MakeCurrent( window, context ); rdState.window.valid = true; rdState.window.width = static_cast<uint32_t>( width ); rdState.window.height = static_cast<uint32_t>( height ); rdState.window.aspectRatio = vid_width->GetReal64() / vid_height->GetReal64(); SDL_GL_SetSwapInterval( r_swapInterval->GetInt32() ); #if defined(XS_OS_MAC) //TODO: force vsync flag in CGL, seems to only have an Obj-C API? /* CGLContextObj cglContext = CGLGetCurrentContext(); if ( cglContext ) { // ... } */ #endif rdState.driver.vendor = reinterpret_cast<const char *>( glGetString( GL_VENDOR ) ); rdState.driver.renderer = reinterpret_cast<const char *>( glGetString( GL_RENDERER ) ); rdState.driver.coreVersion = reinterpret_cast<const char *>( glGetString( GL_VERSION ) ); rdState.driver.shaderVersion = reinterpret_cast<const char *>( glGetString( GL_SHADING_LANGUAGE_VERSION ) ); console.Print( PrintLevel::Normal, "OpenGL device: %s %s\n", rdState.driver.vendor, rdState.driver.renderer ); console.Print( PrintLevel::Normal, "OpenGL version: %s with GLSL %s\n", rdState.driver.coreVersion, rdState.driver.shaderVersion ); }
void conn::conecta(std::string server,std::string port){ bot::team_id id = 1000; boost::asio::io_service io_service; tcp::resolver resolver(io_service); auto endpoint_iterator = resolver.resolve({ server, port }); std::shared_ptr<tcp::socket> socket(new tcp::socket(io_service)); boost::asio::connect(*socket, endpoint_iterator); bot::field_size field_width; bot::field_size field_height; int win_width = 500; int win_height = 500; bots Mundo; boost::mutex state_mutex; SDL_Init(SDL_INIT_VIDEO); atexit(SDL_Quit); SDL_WM_SetCaption("Superbots", "Superbots"); 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 ); MYscreen.set_screen(win_width, win_height); SDL_Event event; bool gameover = false; bool connected = false; boost::thread t = boost::thread([this,socket, &state_mutex, &gameover, &connected, &Mundo, &id, &field_width, &field_height, &win_width, &win_height] () { game_thread(socket, gameover, Mundo, id, state_mutex, field_width, field_height, win_width, win_height, connected); } ); while (!gameover) { if(connected) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: gameover = true; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: case SDLK_q: gameover = true; break; default: break; } break; case SDL_VIDEORESIZE: win_width = event.resize.w; win_height = event.resize.h; MYscreen.set_screen(win_width, win_height, field_width, field_height); break; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); { boost::mutex::scoped_lock lock(state_mutex); Mundo.for_each_bot([&Mundo] (const bot & the_bot) { auto t = the_bot.get_team() + 1; glColor3f(t * 0.2, 1 - t * 0.3, t * 0.1); const bot::position & pos = the_bot.get_position(); glLoadIdentity(); glTranslatef(pos.first, pos.second, 0); glBegin(GL_QUADS); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glEnd(); }); } SDL_GL_SwapBuffers(); } } if(Mundo.bot_count().size() != 1) { std::cout << "Shit!" << std::endl; } else { for(auto inmortal : Mundo.bot_count()) { std::cout << inmortal.first << " se ha pulido a todos!" << std::endl; } } }
void RenderManagerGL2D::init(int xResolution, int yResolution, bool fullscreen) { mCurrentFlags.insert(GL_DEPTH_TEST); mCurrentFlags.insert(GL_MULTISAMPLE); 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_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); Uint32 screenFlags = SDL_OPENGL; if (fullscreen) screenFlags |= SDL_FULLSCREEN; SDL_WM_SetCaption(AppTitle, ""); SDL_WM_SetIcon(SDL_LoadBMP("data/Icon.bmp"), NULL); SDL_SetVideoMode(xResolution, yResolution, 0, screenFlags); SDL_ShowCursor(0); glDisable(GL_MULTISAMPLE); mLeftBlobColor = Color(255, 0, 0); mRightBlobColor = Color(0, 255, 0); SDL_Surface* bgSurface = loadSurface("backgrounds/strand2.bmp"); BufferedImage* bgBufImage = new BufferedImage; bgBufImage->w = getNextPOT(bgSurface->w); bgBufImage->h = getNextPOT(bgSurface->h); bgBufImage->glHandle = loadTexture(bgSurface, false); mBackground = bgBufImage->glHandle; mImageMap["background"] = bgBufImage; mBallShadow = loadTexture(loadSurface("gfx/schball.bmp"), false); mScroll = loadTexture(loadSurface("gfx/scrollbar.bmp"), false); for (int i = 1; i <= 16; ++i) { char filename[64]; sprintf(filename, "gfx/ball%02d.bmp", i); GLuint ballImage = loadTexture(loadSurface(filename), false); mBall.push_back(ballImage); } for (int i = 1; i <= 5; ++i) { char filename[64]; sprintf(filename, "gfx/blobbym%d.bmp", i); GLuint blobImage = loadTexture(loadSurface(filename), false); mBlob.push_back(blobImage); sprintf(filename, "gfx/blobbym%d.bmp", i); GLuint blobSpecular = loadTexture(loadSurface(filename), true); mBlobSpecular.push_back(blobSpecular); sprintf(filename, "gfx/sch1%d.bmp", i); GLuint blobShadow = loadTexture(loadSurface(filename), false); mBlobShadow.push_back(blobShadow); } // create text base textures SDL_Surface* textbase = createEmptySurface(2048, 32); SDL_Surface* hltextbase = createEmptySurface(2048, 32); SDL_Surface* smalltextbase = createEmptySurface(1024, 16); SDL_Surface* hlsmalltextbase = createEmptySurface(1024, 16); int x = 0; int sx = 0; for (int i = 0; i <= 53; ++i) { char filename[64], filename2[64]; sprintf(filename, "gfx/font%02d.bmp", i); sprintf(filename2, "gfx/font_small/font%02d.bmp", i); SDL_Surface* fontSurface = loadSurface(filename); SDL_Surface* fontSurface2 = loadSurface(filename2); GLuint newFont = loadTexture(loadSurface(filename), false); GLuint newFont2 = loadTexture(loadSurface(filename2), false); SDL_Surface* highlight = highlightSurface(fontSurface, 60); SDL_Surface* highlight2 = highlightSurface(fontSurface2, 60); SDL_FreeSurface(fontSurface); SDL_FreeSurface(fontSurface2); fontSurface = loadSurface(filename); fontSurface2 = loadSurface(filename2); SDL_Rect r = {x, 0, fontSurface->w, fontSurface->h}; SDL_BlitSurface(fontSurface, 0, textbase, &r); SDL_BlitSurface(highlight, 0, hltextbase, &r); r = {sx, 0, fontSurface2->w, fontSurface2->h}; SDL_BlitSurface(fontSurface2, 0, smalltextbase, &r); SDL_BlitSurface(highlight2, 0, hlsmalltextbase, &r); //GLuint ballImage = loadTexture(sf, false); //mBall.push_back(ballImage); Texture s = Texture(0, x, 0, fontSurface->w, fontSurface->h, 2048, 32); mFont.push_back(s); mHighlightFont.push_back(s); s = Texture(0, sx, 0, fontSurface2->w, fontSurface2->h, 1024, 16); //mFont.push_back(newFont); //mHighlightFont.push_back(loadTexture(highlight, false)); mSmallFont.push_back( s ); mHighlightSmallFont.push_back( s ); x += fontSurface->w; sx += fontSurface2->w; SDL_FreeSurface(fontSurface); SDL_FreeSurface(fontSurface2); } GLuint texture = loadTexture(textbase, false); GLuint hltexture = loadTexture(hltextbase, false); GLuint smalltexture = loadTexture(smalltextbase, false); GLuint hlsmalltexture = loadTexture(hlsmalltextbase, false); for (int i = 0; i < mFont.size(); ++i) { mFont[i].texture = texture; mHighlightFont[i].texture = hltexture; mSmallFont[i].texture = smalltexture; mHighlightSmallFont[i].texture = hlsmalltexture; } mParticle = loadTexture(loadSurface("gfx/blood.bmp"), false); glViewport(0, 0, xResolution, yResolution); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 800, 600, 0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearDepth(1.0); glDepthFunc(GL_LEQUAL); glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glAlphaFunc(GL_GREATER, 0.5); glEnable(GL_ALPHA_TEST); }
/* ================== GL_SetupAttributes ================== */ void GL_SetupAttributes() { int samples; SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_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); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, gl_stencilbits->integer ); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #ifdef XASH_NANOGL SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #endif #if defined XASH_WES || defined XASH_REGAL SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif switch( gl_msaa->integer ) { case 2: case 4: case 8: case 16: samples = gl_msaa->integer; break; default: samples = 0; // don't use, because invalid parameter is passed } if( samples ) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples); } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } }
void Renderer::init() { for (int i = 0;i < 10;i++) { effectList[i].duration = 0; } if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Impossible d'initialiser SDL: %s\n", SDL_GetError()); exit(1); } //atexit(SDL_Quit); SDL_Init(SDL_INIT_VIDEO); // Version d'OpenGL SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); // Double Buffer SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); displayWindow = SDL_CreateWindow("Test SDL 2.0", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Renderer::screenWidth, Renderer::screenHeight, SDL_WINDOW_OPENGL); // Création du contexte OpenGL contexteOpenGL = SDL_GL_CreateContext(displayWindow); if(contexteOpenGL == 0) { std::cout << SDL_GetError() << std::endl; //// >> AFFICHE : " the specified window isn't an OpenGL window" SDL_DestroyWindow(displayWindow); SDL_Quit(); exit(-1); //// >> PLANTE ICI : return -1 .. } if (TTF_Init() < 0) { puts("ERROR : unable to initialize font library"); exit(1); } //this->font = TTF_OpenFont( "INSPIRAT.ttf", 28 ); this->font = TTF_OpenFont( "digital display tfb.ttf",28); if (this->font == NULL) { puts("ERROR : unable to load font"); exit(1); } #if SDL_BYTEORDER == SDL_BIG_ENDIAN unsigned int rmask = 0xff000000; unsigned int gmask = 0x00ff0000; unsigned int bmask = 0x0000ff00; unsigned int amask = 0x000000ff; #else unsigned int rmask = 0x000000ff; unsigned int gmask = 0x0000ff00; unsigned int bmask = 0x00ff0000; unsigned int amask = 0xff000000; #endif this->textSurface = SDL_CreateRGBSurface( 0, Renderer::screenWidth, Renderer::screenHeight, 32, rmask, gmask, bmask, amask); OGLRenderableFactory factory = OGLRenderableFactory(); this->game = GameFactory::loadGame("game.xml"); this->game->loadCurrentLevel(&factory); bExit = false; soundManager = new SoundManager(); soundManager->init(); //soundManager->loadMusic("A991Project.ogg"); //soundManager->playCurrentMusic(); //soundManager->loadExplosionSound("Grenade-SoundBible.com-1777900486.wav"); particleManager = new ParticleManager(); /* drawthread = SDL_CreateThread(thread_func, this); if ( drawthread == NULL ) { fprintf(stderr, "Unable to create draw thread: %s\n", SDL_GetError()); exit(0); } */ this->game->setOnDestroyCallback(onDestroyCallback,this); this->game->setOnHitCallback(onHitCallback,this); this->fbAccumulation = NULL; this->fbDrawing = NULL; this->fbHalfRes1 = NULL; this->fbHalfRes2 = NULL; shaderTexturing = new Shader(); shaderTexturing->load_fragment("fragment_texturing.gl"); shaderTexturing->load_vertex("test.gl"); shaderDistort = new Shader(); shaderDistort->load_fragment("fragment_distort.gl"); shaderDistort->load_vertex("test.gl"); shaderGaussianBlurVertical = new Shader(); shaderGaussianBlurVertical->load_fragment("fragment_gaussian_vertical.gl"); shaderGaussianBlurVertical->load_vertex("test02.gl"); shaderGaussianBlurHorizontal = new Shader(); shaderGaussianBlurHorizontal->load_fragment("fragment_gaussian_horizontal.gl"); shaderGaussianBlurHorizontal->load_vertex("test02.gl"); Texture * texture = new Texture(2,2,(unsigned char*)g_texdata); unsigned int * pixels = (unsigned int *)malloc(sizeof(unsigned int)*30*30); TextureGenerator::generateTriangle(10,4,pixels,30,0xffffffff); this->spriteAccumulation = new Sprite(texture,100.f,100.f,0,0,1,1); this->spriteBullet = new Sprite(texture,5.f,5.f,1,1,0,0); this->spriteDrawing = new Sprite(texture,100.f,100.f,0,0,1,1); this->spriteDummy = new Sprite(texture,100.f,100.f,0,0,1,1); this->spriteCovering = new Sprite(texture,Renderer::screenWidth,Renderer::screenHeight,0,0,1,1); this->spriteRectangle = new Sprite(texture,10.f,1.f,0,0,1,1); unsigned int * pixels2 = (unsigned int *)malloc(sizeof(unsigned int)*30*30); TextureGenerator::generateCircle(0,0,pixels2,30,0xffffffff); this->spriteCircle = new Sprite(new Texture(30,30,(unsigned char*)pixels2),10.f,10.f,1,1,0,0); //this->spriteCircle = this->spriteBullet; Texture * textSurfaceTexture = new Texture(Renderer::screenWidth,Renderer::screenHeight,(unsigned char*)this->textSurface->pixels); this->spriteTextSurface = new Sprite(textSurfaceTexture,Renderer::screenWidth,Renderer::screenHeight,0,1,1,0); this->spriteShip = new Sprite(new Texture(30,30,(unsigned char*)pixels),30.f,30.f,1,1,0,0); unsigned int * pixelsgrid = (unsigned int*)malloc(sizeof(unsigned int)* 100 * 100); TextureGenerator::generateGrid(pixelsgrid,100,100,20,0xff0909aa); this->spriteGrid = new Sprite(new Texture(100,100,(unsigned char*)pixelsgrid),100.f,100.f,0,0,1,1); BackgroundLayer * backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight); backgroundLayer->addElement(this->spriteGrid,100,100); this->backgroundManager.addLayer(backgroundLayer); unsigned int * pixelsStarfield = (unsigned int*)calloc(sizeof(unsigned int), 100 * 100); TextureGenerator::generateStarfield(pixelsStarfield,100,100,10); backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight,0.0,-1.5f); backgroundLayer->addElement(new Sprite(new Texture(100,100,(unsigned char*)pixelsStarfield),100.f,100.f,0,0,1,1),100,100); this->backgroundManager.addLayer(backgroundLayer); unsigned int * pixelsStarfield2 = (unsigned int*)calloc(sizeof(unsigned int), 100 * 100); TextureGenerator::generateStarfield(pixelsStarfield2,100,100,10); backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight,0.0,-1.0f); backgroundLayer->addElement(new Sprite(new Texture(100,100,(unsigned char*)pixelsStarfield2),100.f,100.f,0,0,1,1),100,100); this->backgroundManager.addLayer(backgroundLayer); }
int rgssThreadFun(void *userdata) { RGSSThreadData *threadData = static_cast<RGSSThreadData*>(userdata); const Config &conf = threadData->config; SDL_Window *win = threadData->window; SDL_GLContext glCtx; /* Setup GL context */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (conf.debugMode) SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); glCtx = SDL_GL_CreateContext(win); if (!glCtx) { rgssThreadError(threadData, std::string("Error creating context: ") + SDL_GetError()); return 0; } try { initGLFunctions(); } catch (const Exception &exc) { rgssThreadError(threadData, exc.msg); SDL_GL_DeleteContext(glCtx); return 0; } gl.ClearColor(0, 0, 0, 1); gl.Clear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapWindow(win); printGLInfo(); bool vsync = conf.vsync || conf.syncToRefreshrate; SDL_GL_SetSwapInterval(vsync ? 1 : 0); GLDebugLogger dLogger; /* Setup AL context */ ALCcontext *alcCtx = alcCreateContext(threadData->alcDev, 0); if (!alcCtx) { rgssThreadError(threadData, "Error creating OpenAL context"); SDL_GL_DeleteContext(glCtx); return 0; } alcMakeContextCurrent(alcCtx); try { SharedState::initInstance(threadData); } catch (const Exception &exc) { rgssThreadError(threadData, exc.msg); alcDestroyContext(alcCtx); SDL_GL_DeleteContext(glCtx); return 0; } /* Start script execution */ scriptBinding->execute(); threadData->rqTermAck.set(); threadData->ethread->requestTerminate(); SharedState::finiInstance(); alcDestroyContext(alcCtx); SDL_GL_DeleteContext(glCtx); return 0; }
int main() { SDL_Window* window; SDL_GLContext context; if (SDL_Init(0) != 0) { std::cout << "SDL could not initialize! SDL_Error:" << SDL_GetError() << std::endl; exit(1); } if (SDL_VideoInit(NULL) != 0) { std::cout << "SDL could not initialize video! SDL_Error:" << SDL_GetError() << std::endl; exit(1); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); window = SDL_CreateWindow( "Crossplatform", 100, 100, 800, 600, SDL_WINDOW_OPENGL ); if ( window == NULL ) { std::cout << "Window could not be created! SDL_Error:" << SDL_GetError() << std::endl; exit(1); } context = SDL_GL_CreateContext(window); if ( context == NULL ) { std::cout << "Context could not be created! SDL_Error:" << SDL_GetError() << std::endl; exit(1); } glewExperimental=true; GLenum status = glewInit(); // Throw away GL_INVALID_ENUM here glGetError(); if (status != GLEW_OK) { std::cerr << "GLEW Error: " << glewGetErrorString(status) << "\n"; print_error(); exit(1); } // get version info const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string print_error(); const GLubyte* version = glGetString(GL_VERSION); // version as a string print_error(); std::cout << "Renderer: " << renderer << std::endl; std::cout << "OpenGL version supported: " << version << std::endl; glEnable(GL_DEPTH_TEST); // enable depth-testing print_error(); glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer" print_error(); // glEnable (GL_CULL_FACE); // cull face // glCullFace (GL_BACK); // cull back face // glFrontFace (GL_CW); // GL_CCW for counter clock-wise GLfloat points[] = { -10.f, 10.f, 0.0f, 10.f, -10.f, 0.0f, -10.f, -10.f, 0.0f }; GLuint vertexBufferObject; glGenBuffers(1, &vertexBufferObject); print_error(); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); print_error(); glBufferData(GL_ARRAY_BUFFER, sizeof(points), &points[0], GL_STATIC_DRAW); print_error(); GLuint vertexArrayObject; glGenVertexArrays(1, &vertexArrayObject); print_error(); glBindVertexArray(vertexArrayObject); print_error(); GLuint shaderProgram = loadShaders(); const char* attribute_name = "vertexposition"; GLuint attribute_position = glGetAttribLocation(shaderProgram, attribute_name); print_error(); if (attribute_position == -1) { std::cout << "Could not bind attribute " << attribute_name << std::endl; exit(1); } glEnableVertexAttribArray(attribute_position); print_error(); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); print_error(); glVertexAttribPointer( attribute_position, // attribute 3, // number of elements per vertex, here (x,y,z) GL_FLOAT, // the type of each element GL_FALSE, // take our values as-is 0, // no extra data between each position 0 // offset of first element ); print_error(); glBindBuffer(GL_ARRAY_BUFFER, 0); print_error(); while (true) { glClearColor(.0f, .0f, .0f, .0f); print_error(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); print_error(); glUseProgram(shaderProgram); print_error(); glDrawArrays(GL_TRIANGLES, 0, 3); print_error(); glDisableVertexAttribArray(attribute_position); print_error(); SDL_GL_SwapWindow(window); } }
int main(int argc, char *argv[]) { SDL_Surface *screen; if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL ); if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); // Create a texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte textureData[16*16*4]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData ); // Create a second texture GLuint texture2; glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte texture2Data[] = { 0xff, 0, 0, 0xff, 0, 0xff, 0, 0xaa, 0, 0, 0xff, 0x55, 0x80, 0x90, 0x70, 0 }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2Data ); // BEGIN #if USE_GLEW glewInit(); #endif glMatrixMode(GL_PROJECTION); glLoadIdentity(); // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048); glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048); glRotatef(-30, 1, 1, 1); //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 }; //glLoadMatrixf(pm); glMatrixMode(GL_MODELVIEW); GLfloat matrixData[] = { -1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; glLoadMatrixf(matrixData); //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture(GL_TEXTURE0); glEnableClientState(GL_VERTEX_ARRAY); GLuint arrayBuffer, elementBuffer; glGenBuffers(1, &arrayBuffer); glGenBuffers(1, &elementBuffer); GLubyte arrayData[] = { /* [0, 0, 0, 67] ==> 128 float [0, 0, 128, 67] ==> 256 float [0, 0, 0, 68] ==> 512 float [0, 0, 128, 68] ==> 1024 float [vertex x ] [vertex y ] [vertex z ] [nr] [texture u ] [texture v ] [lm u ] [lm v ] [color r,g,b,a ] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 0 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 23, 20, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 1 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 35, 30, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 2 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 47, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 3 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 51, 50, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 4 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 64, 60, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 5 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 70, 70, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 6 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 89, 80, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 7 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 94, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 8 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 20, 10, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 9 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 31, 20, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 10 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 42, 30, 0, 0, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 11 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 53, 40, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 12 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 64, 50, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 13 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 75, 60, 0, 0, 0, 0, 128, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 14 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 86, 70, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 15 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128 }; assert(sizeof(arrayData) == 1408); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 }; assert(sizeof(elementData) == 48); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound glTexCoordPointer(2, GL_FLOAT, 32, (void*)16); glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build glTexCoordPointer(2, GL_SHORT, 32, (void*)24); glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup glNormalPointer(GL_BYTE, 32, (void*)12); glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28); glBindTexture(GL_TEXTURE_2D, texture); // diffuse? glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // lightmap? glActiveTexture(GL_TEXTURE0); GLint ok; const char *vertexShader = "uniform vec4 texgenscroll;\n" "void main(void)\n" "{\n" " gl_Position = ftransform();\n" " gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here " gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n" "}\n"; const char *fragmentShader = "uniform vec4 colorparams;\n" "uniform sampler2D diffusemap, lightmap;\n" "void main(void)\n" "{\n" " vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n" " vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n" " diffuse *= colorparams;\n" " gl_FragColor = diffuse * lm;\n" "}\n"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertexShader, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragmentShader, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); assert(ok); glUseProgram(program); GLint lightmapLocation = glGetUniformLocation(program, "lightmap"); assert(lightmapLocation >= 0); glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit? GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap"); assert(diffusemapLocation >= 0); glUniform1i(diffusemapLocation, 0); GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll"); assert(texgenscrollLocation >= 0); GLint colorparamsLocation = glGetUniformLocation(program, "colorparams"); assert(colorparamsLocation >= 0); GLfloat texgenscrollData[] = { 0, 0, 0, 0 }; glUniform4fv(texgenscrollLocation, 1, texgenscrollData); GLfloat colorparamsData[] = { 2, 2, 2, 1 }; glUniform4fv(colorparamsLocation, 1, colorparamsData); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[12/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[ 0/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[24/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[36/sizeof(GLushort)]); // END SDL_GL_SwapBuffers(); #if !EMSCRIPTEN SDL_Delay(1500); #endif SDL_Quit(); return 0; }
// ============================================================================== // Sets the video mode, and opens a window with the specified settings // ============================================================================== int SetVideoMode(int width, int height, int depth, bool fullscreen, bool resizable) { int bpp; VideoFlags = SDL_OPENGL; PrintDebug("VIDEO: OpenGL flag set."); VideoFlags |= SDL_GL_DOUBLEBUFFER; PrintDebug("VIDEO: Double Buffer flag set."); VideoFlags |= SDL_HWPALETTE; PrintDebug("VIDEO: Hardware Palette flag set."); if(fullscreen == true) { VideoFlags |= SDL_FULLSCREEN; PrintDebug("VIDEO: OpenGL flag set."); } if(resizable == true) { VideoFlags |= SDL_RESIZABLE; PrintDebug("VIDEO: Resizable flag set."); } if (VideoInfo->hw_available == 1) { VideoFlags |= SDL_HWSURFACE; PrintDebug("VIDEO: [Good] Surfaces can be stored in hardware memory."); } else { VideoFlags |= SDL_SWSURFACE; PrintDebug("VIDEO: [Bad] Surfaces cannot be stored in hardware memory."); } if (VideoInfo->blit_hw) { VideoFlags |= SDL_HWACCEL; PrintDebug("VIDEO: [Good] Hardware blitting can be done"); if(VideoInfo->blit_hw_CC) { PrintDebug("VIDEO: [Good] Hardware color keys are accelerated"); } else { PrintDebug("VIDEO: [Bad] Hardware color keys aren't accelerated"); } if(VideoInfo->blit_hw_A) { PrintDebug("VIDEO: [Good] Hardware alpha blits are accelerated"); } else { PrintDebug("VIDEO: [Bad] Hardware alpha blits aren't accelerated"); } } else { PrintDebug("VIDEO: [Bad] Hardware blitting cannot be done"); PrintDebug("VIDEO: [Good] Software blitting can be done"); if(VideoInfo->blit_sw_CC) { PrintDebug("VIDEO: [Good] Software color keys are accelerated"); } else { PrintDebug("VIDEO: [Bad] Software color keys aren't accelerated"); } if(VideoInfo->blit_sw_A) { PrintDebug("VIDEO: [Good] Software alpha blits are accelerated"); } else { PrintDebug("VIDEO: [Bad] Software alpha blits aren't accelerated"); } } if( SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ) != 0) { PrintDebug("<ERROR> SetVideoMode() -> OpenGL cannot use double buffering!\nError string:\n\n",SDL_GetError()); return -1; } else { PrintDebug("VIDEO: [Good] OpenGL set to double buffering"); } // TODO: Pass the "VIDEO: Checking mode %i x %i @ %i bpp",width,height,depth" to PrintDebug // PrintDebug(); bpp=SDL_VideoModeOK(width, height, depth, VideoFlags); if(!bpp) { // TODO: Pass the "VIDEO: Unable to use the video mode %i x %i @ %i bpp",width,height,depth" to PrintDebug // PrintDebug(); return -1; } else { Screen = SDL_SetVideoMode(width, height, depth, VideoFlags); if( !Screen ) { PrintDebug("<ERROR> SetVideoMode -> Surface not available. Video mode set failed.\nError string:\n\n",SDL_GetError()); return -1; } else { // TODO: Pass the "VIDEO: Using mode %ix%i@%ibpp\n",width,height,depth" to PrintDebug // PrintDebug(); return 1; } } }
void init_video() { if(texture_manager != NULL) texture_manager->save_textures(); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); int flags = SDL_OPENGL; if(config->use_fullscreen) flags |= SDL_FULLSCREEN; int width = config->screenwidth; int height = config->screenheight; int bpp = 0; screen = SDL_SetVideoMode(width, height, bpp, flags); if(screen == 0) { std::stringstream msg; msg << "Couldn't set video mode (" << width << "x" << height << "-" << bpp << "bpp): " << SDL_GetError(); throw std::runtime_error(msg.str()); } SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0); // set icon SDL_Surface* icon = IMG_Load_RW( get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true); if(icon != 0) { SDL_WM_SetIcon(icon, 0); SDL_FreeSurface(icon); } #ifdef DEBUG else { log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl; } #endif // setup opengl state and transform glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, screen->w, screen->h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // logical resolution here not real monitor resolution glOrtho(0, 800, 600, 0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, 0); check_gl_error("Setting up view matrices"); if(texture_manager != NULL) texture_manager->reload_textures(); else texture_manager = new TextureManager(); }
int main() { int width = 640; int height = 480; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) { std::cerr << "failed to init SDL" << std::endl; return 1; } // select opengl version SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); // create a window SDL_Window *window; if((window = SDL_CreateWindow("SDL2", 0, 0, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN)) == 0) { std::cerr << "failed to open window" << std::endl; SDL_Quit(); return 1; } SDL_GLContext context = SDL_GL_CreateContext(window); if(gl3wInit()) { std::cerr << "failed to init GL3W" << std::endl; SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // shader source code std::string vertex_source = "#version 330\n" "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec4 vcolor;\n" "out vec4 fcolor;\n" "void main() {\n" " fcolor = vcolor;\n" " gl_Position = vposition;\n" "}\n"; std::string fragment_source = "#version 330\n" "in vec4 fcolor;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = fcolor;\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); if(!check_program_link_status(shader_program)) { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // vao and vbo handle GLuint vao, vbo; // generate and bind the vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); // generate and bind the buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // data for a fullscreen quad GLfloat vertexData[] = { // X Y Z R G B 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // vertex 0 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // vertex 1 1.0f,-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // vertex 2 1.0f,-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // vertex 3 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // vertex 4 -1.0f,-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // vertex 5 }; // 6 vertices with 6 components (floats) each // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*6, vertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); bool closed = false; while(!closed) { SDL_Event event; while(SDL_PollEvent(&event)) { if(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE) { closed = true; } } // clear first glClear(GL_COLOR_BUFFER_BIT); // use the shader program glUseProgram(shader_program); // bind the vao glBindVertexArray(vao); // draw glDrawArrays(GL_TRIANGLES, 0, 6); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << error << std::endl; break; } // finally swap buffers SDL_GL_SwapWindow(window); } // delete the created objects glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
void graphics_init(int width, int height) { SDL_Init(SDL_INIT_VIDEO); //#ifdef EMSCRIPTEN // moduleData.surface = SDL_SetVideoMode(width, height, 0, SDL_OPENGL); //#else #ifndef EMSCRIPTEN SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #else 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); #endif SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #if EMSCRIPTEN char const * title = emscripten_run_script_string("document.title"); #else char const * title = "Motor2D"; #endif moduleData.window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL); moduleData.context = SDL_GL_CreateContext(moduleData.window); SDL_GL_MakeCurrent(moduleData.window, moduleData.context); moduleData.surface = SDL_GetWindowSurface(moduleData.window); glewExperimental = GL_TRUE; printf("%d\n", glewInit()); #ifndef EMSCRIPTEN SDL_GL_SetSwapInterval(1); #endif //#endif // glViewport(0,0,width,height); matrixstack_init(); graphics_canvas_init(width, height); graphics_setColor(1.0f, 1.0f, 1.0f, 1.0f); graphics_geometry_init(); graphics_font_init(); graphics_batch_init(); graphics_image_init(); graphics_shader_init(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ALIGNMENT, 1); graphics_setColorMask(true, true, true, true); graphics_setBlendMode(graphics_BlendMode_alpha); glEnable(GL_BLEND); graphics_clearScissor(); glGenVertexArrays(1, &moduleData.polygonVAO); glBindVertexArray(moduleData.polygonVAO); glGenBuffers(1, &moduleData.polygonVBO); glGenBuffers(1, &moduleData.polygonIBO); }
Camera::Camera() { m_pAssociatedScene = NULL; //initialise OpenGL const SDL_VideoInfo* VideoInfo = SDL_GetVideoInfo(); int bpp = VideoInfo->vfmt->BitsPerPixel; int width = 1024; int height = 768; if( SDL_SetVideoMode( width, height, bpp, SDL_OPENGL /*| SDL_FULLSCREEN*/ ) == 0) { fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError() ); SDL_Quit(); exit(1); } float ratio = (float) width / (float) height; //attributes of camera should be configured dynamically glShadeModel( GL_SMOOTH ); glCullFace( GL_BACK ); glFrontFace(GL_CCW); // glEnable( GL_CULL_FACE ); glEnable( GL_DEPTH_TEST ); 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 ); // glClearColor(1, 1, 1, 1); glClearColor(0, 0, 0, 0); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glEnable(GL_RENDER); glEnable(GL_LIGHTING); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0); //FOG /* glEnable(GL_FOG); GLfloat rgba[] = {1, 1, 1, 1}; glFogfv(GL_FOG_COLOR, rgba); glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_DENSITY, .5); glFogf(GL_FOG_START, .5); glFogf(GL_FOG_END, .6); glHint(GL_FOG_HINT, GL_FASTEST|GL_NICEST|GL_DONT_CARE);*/ gluPerspective(60.0, ratio, 1.0, 1024.0); }
int main(int argc, char *argv[]) { SDL_Surface *screen; static struct option long_options[] = { {"no-kinect", no_argument, 0, 'k'}, {"fullscreen", optional_argument, 0, 'f'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int option_index = 0, opt; bool init_kinect = true; bool fullscreen_mode = false; char *fullscreen_resolution = NULL; while ((opt = getopt_long(argc, argv, "khf:", long_options, &option_index)) != -1) { switch (opt) { case 'k': init_kinect = false; printf("Not initializing kinect (-k passed)\n"); break; case 'f': printf("Starting in fullscreen mode\n"); fullscreen_mode = true; if (optarg) fullscreen_resolution = strdup(optarg); break; case 'h': printf("Syntax: %s [-k] [-h]\n", argv[0]); printf("\t--no-kinect\tDisables initializing kinect\n"); printf("\t--fullscreen\tEnable fullscreen mode (default is windowed)\n"); printf("\t\t\t(--fullscreen=1024x768 to overwrite the resolution)\n"); exit(0); break; } } median_filter_init(); glow_filter_init(); if (init_kinect) kinect_init(); mask_rgb_init(); loadimg_init(); /* Initialize SDL */ SDL_Init(SDL_INIT_VIDEO); TTF_Init(); 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_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); /* Initialize the screen / window */ if (fullscreen_mode && fullscreen_resolution != NULL) { if (sscanf(fullscreen_resolution, "%dx", &SCREEN_WIDTH) != 1) { fprintf(stderr, "Invalid resolution specified: %s (needs to be WxH, e.g. 1024x768)\n", fullscreen_resolution); exit(1); } printf("Setting width to %d\n", SCREEN_WIDTH); } int flags = SDL_OPENGL | SDL_HWSURFACE | SDL_NOFRAME | SDL_DOUBLEBUF; if (fullscreen_mode) flags |= SDL_FULLSCREEN; screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH, flags); if (screen == 0) { printf("set failed: %s\n", SDL_GetError()); return 1; } SDL_WM_SetCaption("kinectboard", ""); glewInit(); /* Setup viewport */ glEnable(GL_TEXTURE_2D); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); kb_ui_init(); // Register callbacks kb_ui_register_void_callback("Exit",exit_callback); kb_ui_register_void_callback("Calibrate",run_calibration_callback); kb_ui_register_void_callback("StartCalibration",start_calibration_callback); kb_ui_register_void_callback("EndCalibration",end_calibration_callback); kb_ui_register_void_callback("ImageRight",kb_images_scroll_right); kb_ui_register_void_callback("ImageLeft",kb_images_scroll_left); kb_ui_register_value_callback("SetDistanceThreshold", set_distance_threshold_callback); kb_ui_register_value_callback("SetDepthMultiplier", set_depth_multiplier_callback); kb_ui_register_value_callback("SetDepthDifferenceThreshold", set_depth_difference_threshold_callback); kb_ui_register_value_callback("SetGlowAreaStart", set_glow_area_start_callback); kb_ui_register_value_callback("SetGlowAreaEnd", set_glow_area_end_callback); kb_ui_call_javascript("SetRGB", "142,51,19"); // The CUDA Device Info requires a valid UI since the info is displayed there print_cuda_device_info(); /* Allocate textures and buffers to draw into (from the GPU) */ allocateGLTexture(&rawDepthBufferID, &rawDepthTextureID); allocateGLTexture(&medianBufferID, &medianTextureID); allocateGLTexture(&maskedMedianBufferID, &maskedMedianTextureID); allocateGLTexture(&glowBufferID, &glowTextureID); allocateGLTexture(&rawRgbBufferID, &rawRgbTextureID); allocateGLTexture(&maskRgbBufferID, &maskRgbTextureID); allocateGLTexture(&contRgbBufferID, &contRgbTextureID); kb_image_create("Raw depth image", rawDepthBufferID, rawDepthTextureID); kb_image_create("Median-filtered depth image", medianBufferID, medianTextureID); kb_image_create("Masked depth image", maskedMedianBufferID, maskedMedianTextureID); kb_image_create("Glowing depth", glowBufferID, glowTextureID); kb_image_create("Raw RGB image", rawRgbBufferID, rawRgbTextureID); kb_image_create("Masked kinect RGB image", maskRgbBufferID, maskRgbTextureID); kb_image_create("Cont RGB image", contRgbBufferID, contRgbTextureID); // Load a Texture //loadTextureFromFile("../data/calibration.bmp", &calibrationBufferID, &calibrationTextureID); //kb_image_create("Calibration", calibrationBufferID, calibrationTextureID); SDL_Surface* surface = SDL_LoadBMP("../data/calibration.bmp"); cudaMalloc((void**)&(backgrounds[1]), 640 * 480 * 3 * sizeof(uint8_t)); loadimg_convert((uint8_t*)surface->pixels, backgrounds[1]); surface = SDL_LoadBMP("../data/malen_haus.bmp"); cudaMalloc((void**)&(backgrounds[2]), 640 * 480 * 3 * sizeof(uint8_t)); loadimg_convert((uint8_t*)surface->pixels, backgrounds[2]); surface = SDL_LoadBMP("../data/malen_stern.bmp"); cudaMalloc((void**)&(backgrounds[3]), 640 * 480 * 3 * sizeof(uint8_t)); loadimg_convert((uint8_t*)surface->pixels, backgrounds[3]); surface = SDL_LoadBMP("../data/empty.bmp"); cudaMalloc((void**)&(backgrounds[4]), 640 * 480 * 3 * sizeof(uint8_t)); loadimg_convert((uint8_t*)surface->pixels, backgrounds[4]); printf("gl set up.\n"); uchar4 *gpu_median_output, *gpu_masked_median_output, *gpu_glow_output, *gpu_mask_rgb_output, *gpu_raw_depth_output, *gpu_raw_rgb_output, *gpu_cont_rgb_output; int fps = 0; int last_time = 0; int current_time; while (1) { /* FPS counter */ current_time = SDL_GetTicks(); if ((current_time - last_time) >= 1000) { static char buffer[20] = {0}; sprintf(buffer, "%d FPS", fps); SDL_WM_SetCaption(buffer, 0); kb_ui_call_javascript("SetFPS",buffer); fps = 0; last_time = current_time; } //kb_poll_events(list); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); /* Reset viewport for rendering our images, it was modified by * kb_ui_render(). */ glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); kb_poll_events(); gpu_median_output = NULL; gpu_masked_median_output = NULL; gpu_glow_output = NULL; gpu_mask_rgb_output = NULL; gpu_raw_depth_output = NULL; gpu_raw_rgb_output = NULL; gpu_cont_rgb_output = NULL; cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_raw_depth_output, rawDepthBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_median_output, medianBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_masked_median_output, maskedMedianBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_glow_output, glowBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_mask_rgb_output, maskRgbBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_raw_rgb_output, rawRgbBufferID)); cutilSafeCall(cudaGLMapBufferObject((void**)&gpu_cont_rgb_output, contRgbBufferID)); // XXX: Potential for optimization: We currently call functions like // median_filter(), median_mask() and mask_rgb() which are all // blocking. However, we could launch the kernel and perform more work // on the CPU while waiting for the kernel to complete (or maybe even // launch some in parallel and/or use async events). median_filter(take_depth_image(), gpu_median_output, gpu_raw_depth_output); done_depth_image(); median_mask(calibration, gpu_median_output, gpu_masked_median_output); glow_filter(gpu_masked_median_output, gpu_glow_output, glow_start, glow_end); mask_rgb(gpu_glow_output, take_rgb_image(), gpu_mask_rgb_output, gpu_raw_rgb_output, gpu_cont_rgb_output, reference_color, FILTER_DISTANCE, backgrounds[current_background], calibrated_offset); done_rgb_image(); cutilSafeCall(cudaGLUnmapBufferObject(maskedMedianBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(medianBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(glowBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(maskRgbBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(rawDepthBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(rawRgbBufferID)); cutilSafeCall(cudaGLUnmapBufferObject(contRgbBufferID)); if(fullscreen_canvas) { kb_images_render_canvas_only(); } else { kb_images_render(); kb_ui_update(); kb_ui_render(); } SDL_GL_SwapBuffers(); fps++; } }
int sdl_window_info::complete_create() { osd_dim temp(0,0); // clear out original mode. Needed on OSX if (fullscreen()) { // default to the current mode exactly temp = monitor()->position_size().dim(); // if we're allowed to switch resolutions, override with something better if (video_config.switchres) temp = pick_best_mode(); } else if (m_windowed_dim.width() > 0) { // if we have a remembered size force the new window size to it temp = m_windowed_dim; } else if (m_startmaximized) temp = get_max_bounds(video_config.keepaspect ); else temp = get_min_bounds(video_config.keepaspect ); // create the window ..... /* FIXME: On Ubuntu and potentially other Linux OS you should use * to disable panning. This has to be done before every invocation of mame. * * xrandr --output HDMI-0 --panning 0x0+0+0 --fb 0x0 * */ osd_printf_verbose("Enter sdl_info::create\n"); if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL) && !video_config.novideo) { SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* FIXME: A reminder that gamma is wrong throughout MAME. Currently, SDL2.0 doesn't seem to * support the following attribute although my hardware lists GL_ARB_framebuffer_sRGB as an extension. * * SDL_GL_SetAttribute( SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1 ); * */ m_extra_flags = SDL_WINDOW_OPENGL; } else m_extra_flags = 0; #ifdef SDLMAME_MACOSX /* FIMXE: On OSX, SDL_WINDOW_FULLSCREEN_DESKTOP seems to be more reliable. * It however creates issues with white borders, i.e. the screen clear * does not work. This happens both with opengl and accel. */ #endif // We need to workaround an issue in SDL 2.0.4 for OS X where setting the // relative mode on the mouse in fullscreen mode makes mouse events stop // It is fixed in the latest revisions so we'll assume it'll be fixed // in the next public SDL release as well #if defined(SDLMAME_MACOSX) && SDL_VERSION_ATLEAST(2, 0, 2) // SDL_HINT_MOUSE_RELATIVE_MODE_WARP is introduced in 2.0.2 SDL_version linked; SDL_GetVersion(&linked); int revision = SDL_GetRevisionNumber(); // If we're running the exact version of SDL 2.0.4 (revision 10001) from the // SDL web site, we need to work around this issue and send the warp mode hint if (SDL_VERSION_EQUALS(linked, SDL_VERSIONNUM(2, 0, 4)) && revision == 10001) { osd_printf_verbose("Using warp mode for relative mouse in OS X SDL 2.0.4\n"); SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); } #endif // create the SDL window // soft driver also used | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_MOUSE_FOCUS m_extra_flags |= (fullscreen() ? SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE); #if defined(SDLMAME_WIN32) SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); #endif // get monitor work area for centering osd_rect work = monitor()->usuable_position_size(); // create the SDL window auto sdlwindow = SDL_CreateWindow(m_title, work.left() + (work.width() - temp.width()) / 2, work.top() + (work.height() - temp.height()) / 2, temp.width(), temp.height(), m_extra_flags); //window().sdl_window() = SDL_CreateWindow(window().m_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, // width, height, m_extra_flags); if (sdlwindow == nullptr ) { if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL)) osd_printf_error("OpenGL not supported on this driver: %s\n", SDL_GetError()); else osd_printf_error("Window creation failed: %s\n", SDL_GetError()); return 1; } set_platform_window(sdlwindow); if (fullscreen() && video_config.switchres) { SDL_DisplayMode mode; //SDL_GetCurrentDisplayMode(window().monitor()->handle, &mode); SDL_GetWindowDisplayMode(platform_window(), &mode); m_original_mode->mode = mode; mode.w = temp.width(); mode.h = temp.height(); if (m_win_config.refresh) mode.refresh_rate = m_win_config.refresh; SDL_SetWindowDisplayMode(platform_window(), &mode); // Try to set mode #ifndef SDLMAME_WIN32 /* FIXME: Warp the mouse to 0,0 in case a virtual desktop resolution * is in place after the mode switch - which will most likely be the case * This is a hack to work around a deficiency in SDL2 */ SDL_WarpMouseInWindow(platform_window(), 1, 1); #endif } else { //SDL_SetWindowDisplayMode(window().sdl_window(), nullptr); // Use desktop } // show window SDL_ShowWindow(platform_window()); //SDL_SetWindowFullscreen(window->sdl_window(), 0); //SDL_SetWindowFullscreen(window->sdl_window(), window->fullscreen()); SDL_RaiseWindow(platform_window()); #ifdef SDLMAME_WIN32 if (fullscreen()) SDL_SetWindowGrab(platform_window(), SDL_TRUE); #endif // set main window if (m_index > 0) { for (auto w : osd_common_t::s_window_list) { if (w->m_index == 0) { set_main_window(std::dynamic_pointer_cast<osd_window>(w)); break; } } } else { // We must be the main window set_main_window(shared_from_this()); } // update monitor resolution after mode change to ensure proper pixel aspect monitor()->refresh(); if (fullscreen() && video_config.switchres) monitor()->update_resolution(temp.width(), temp.height()); // initialize the drawing backend if (renderer().create()) return 1; // Make sure we have a consistent state SDL_ShowCursor(0); SDL_ShowCursor(1); return 0; }
int main(int argc, char *argv[]) { SDL_Surface *screen; // Slightly different SDL initialization if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // *new* screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL ); // *changed* if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } // Check extensions const char *exts = (const char *)glGetString(GL_EXTENSIONS); assert(hasext(exts, "GL_ARB_texture_compression")); assert(hasext(exts, "GL_EXT_texture_compression_s3tc")); // Set the OpenGL state after creating the context with SDL_SetVideoMode glClearColor( 0, 0, 0, 0 ); #if !EMSCRIPTEN glEnable( GL_TEXTURE_2D ); // Need this to display a texture XXX unnecessary in OpenGL ES 2.0/WebGL #endif glViewport( 0, 0, 640, 480 ); glMatrixMode( GL_PROJECTION ); GLfloat matrixData[] = { 2.0/640, 0, 0, 0, 0, -2.0/480, 0, 0, 0, 0, -1, 0, -1, 1, 0, 1 }; glLoadMatrixf(matrixData); // test loadmatrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // Load the OpenGL textures GLuint texture; { #define DDS_SIZE 65664 FILE *dds = fopen("ship.dds", "rb"); assert(dds); char *ddsdata = (char*)malloc(DDS_SIZE); assert(fread(ddsdata, 1, DDS_SIZE, dds) == DDS_SIZE); fclose(dds); glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); assert(!glGetError()); glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 256, 256, 0, DDS_SIZE-128, ddsdata+128); assert(!glGetError()); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); } // second texture GLuint texture2; { #define DDS_SIZE 32896 FILE *dds = fopen("bloom.dds", "rb"); assert(dds); char *ddsdata = (char*)malloc(DDS_SIZE); assert(fread(ddsdata, 1, DDS_SIZE, dds) == DDS_SIZE); fclose(dds); glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); assert(!glGetError()); glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 256, 256, 0, DDS_SIZE-128, ddsdata+128); assert(!glGetError()); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); } // Prepare and Render // Clear the screen before drawing glClear( GL_COLOR_BUFFER_BIT ); // Bind the texture to which subsequent calls refer to glBindTexture( GL_TEXTURE_2D, texture ); // Use clientside vertex pointers to render two items GLfloat vertexData[] = { 0, 0, 10, 10, // texture2, position2 1, 0, 300, 10, 1, 1, 300, 128, 0, 1, 10, 128, 0, 0.5, 410, 10, 1, 0.5, 600, 10, 1, 1, 630, 200, 0.5, 1, 310, 250 }; glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 4*4, &vertexData[0]); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 4*4, &vertexData[2]); glDrawArrays(GL_QUADS, 0, 8); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); // Render the last item using oldschool glBegin etc glBindTexture( GL_TEXTURE_2D, texture2 ); glBegin( GL_TRIANGLE_STRIP ); glTexCoord2i( 0, 0 ); glVertex3f( 100, 300, 0 ); glTexCoord2i( 1, 0 ); glVertex3f( 300, 300, 0 ); glTexCoord2i( 1, 1 ); glVertex3f( 300, 400, 0 ); glTexCoord2i( 0, 1 ); glVertex3f( 500, 410, 0 ); glEnd(); SDL_GL_SwapBuffers(); #if !EMSCRIPTEN // Wait for 3 seconds to give us a chance to see the image SDL_Delay(1500); #endif // Now we can delete the OpenGL texture and close down SDL glDeleteTextures( 1, &texture ); SDL_Quit(); return 0; }
int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // init SDL if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } // Starting with SDL 1.2.10, passing in 0 will use the system's current resolution. unsigned int windowWidth = 0; unsigned int windowHeight = 0; // Passing in 0 for bitdepth also uses the system's current bitdepth. This works before 1.2.10 too. unsigned int bitDepth = 0; // If not linked to SDL 1.2.10+, then we must use hardcoded values const SDL_version* linked_version = SDL_Linked_Version(); if(linked_version->major == 1 && linked_version->minor == 2) { if(linked_version->patch < 10) { windowWidth = 1280; windowHeight = 1024; } } 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 ); // set up the surface to render to SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, bitDepth, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE); if ( screen == NULL ) { std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl; exit(1); } SDL_EnableUNICODE(1); // If we used 0 to set the fields, query the values so we can pass it to osgViewer windowWidth = screen->w; windowHeight = screen->h; osgViewer::Viewer viewer; osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> gw = viewer.setUpViewerAsEmbeddedInWindow(0,0,windowWidth,windowHeight); viewer.setSceneData(loadedModel.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator); viewer.addEventHandler(new osgViewer::StatsHandler); viewer.realize(); bool done = false; while( !done ) { SDL_Event event; while ( SDL_PollEvent(&event) ) { // pass the SDL event into the viewers event queue convertEvent(event, *(gw->getEventQueue())); switch (event.type) { case SDL_VIDEORESIZE: SDL_SetVideoMode(event.resize.w, event.resize.h, bitDepth, SDL_OPENGL | SDL_RESIZABLE); gw->resized(0, 0, event.resize.w, event.resize.h ); break; case SDL_KEYUP: if (event.key.keysym.sym==SDLK_ESCAPE) done = true; if (event.key.keysym.sym=='f') { SDL_WM_ToggleFullScreen(screen); gw->resized(0, 0, screen->w, screen->h ); } break; case SDL_QUIT: done = true; } } if (done) continue; // draw the new frame viewer.frame(); // Swap Buffers SDL_GL_SwapBuffers(); } return 0; }
void SDLAppDisplay::setVideoMode(int width, int height, bool fullscreen) { int gl_depth = 24; int colour_depth = 32; #ifndef _WIN32 if(!enable_shaders) { gl_depth = 16; colour_depth = 24; } #endif bool no_cursor = false; #ifdef SDLAPP_XWINDOWS /* check for window_id in ENV */ if(xwindow == 0) { char* xscreensaver_window_env = getenv("XSCREENSAVER_WINDOW"); if(xscreensaver_window_env != 0) { //parse xscreensaver window id sscanf(xscreensaver_window_env, "0x%lx", &xwindow); if (!xwindow) sscanf(xscreensaver_window_env, "%lu", &xwindow); if (!xwindow) throw SDLInitException("Invalid window"); } } if(xwindow != 0) { char sdl_window_env[100]; snprintf(sdl_window_env, 100, "SDL_WINDOWID=%d", xwindow); putenv(sdl_window_env); Display* dpy = XOpenDisplay(0); if(!dpy) { throw SDLInitException("Cannot get display"); } XWindowAttributes win_attributes; if (!XGetWindowAttributes(dpy, xwindow, &win_attributes)) { throw SDLInitException("Cannot get window attributes"); } width = win_attributes.width; height = win_attributes.height; colour_depth = win_attributes.depth; screensaver = true; fullscreen = false; // assume window opened at y=0 by xscreensaver is actually running as a screensaver and not a preview if(win_attributes.y == 0) no_cursor = true; } #endif #if SDL_VERSION_ATLEAST(1,3,0) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; if(resizable && !fullscreen) flags |= SDL_WINDOW_RESIZABLE; if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN; if(gl_context != 0) SDL_GL_DeleteContext(gl_context); if(sdl_window != 0) SDL_DestroyWindow(sdl_window); sdl_window = SDL_CreateWindow( gSDLAppTitle.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags); if (!sdl_window) { std::string sdlerr(SDL_GetError()); throw SDLInitException(sdlerr); } gl_context = SDL_GL_CreateContext(sdl_window); if(vsync) SDL_GL_SetSwapInterval(1); #else int depth = 32; int flags = SDLFlags(fullscreen); if(no_cursor) SDL_ShowCursor(false); if(vsync) SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); else SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0); if(multi_sample > 0) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, (GLuint) multi_sample); } if(enable_alpha) { SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); } #ifdef _WIN32 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); surface = SDL_SetVideoMode(width, height, depth, flags); #else if(enable_shaders) { SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); surface = SDL_SetVideoMode(width, height, depth, flags); } else { depth = 24; SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); surface = SDL_SetVideoMode(width, height, depth, flags); } #endif SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, gl_depth); surface = SDL_SetVideoMode(width, height, colour_depth, flags); if (!surface) { if (multi_sample > 0) { #ifndef _WIN32 // Retry without multi-sampling before failing std::cerr << "Failed to set video mode: " << SDL_GetError() << std::endl << "Trying again without multi-sampling" << std::endl; #endif multi_sample = 0; SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); surface = SDL_SetVideoMode(width, height, depth, flags); } if (!surface) { std::string sdlerr(SDL_GetError()); throw SDLInitException(sdlerr); } } #endif setupExtensions(); }
bool Sdl2Application::tryCreateContext(const Configuration& configuration) { CORRADE_ASSERT(_context->version() == Version::None, "Platform::Sdl2Application::tryCreateContext(): context already created", false); /* Enable double buffering and 24bt depth buffer */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); /* Multisampling */ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration.sampleCount() > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration.sampleCount()); #ifndef CORRADE_TARGET_EMSCRIPTEN /* sRGB */ SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, configuration.isSRGBCapable()); #endif /* Flags: if not hidden, set as shown */ Uint32 windowFlags(configuration.windowFlags()); if(!(configuration.windowFlags() & Configuration::WindowFlag::Hidden)) windowFlags |= SDL_WINDOW_SHOWN; /** @todo Remove when Emscripten has proper SDL2 support */ #ifndef CORRADE_TARGET_EMSCRIPTEN /* Set context version, if user-specified */ if(configuration.version() != Version::None) { Int major, minor; std::tie(major, minor) = version(configuration.version()); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); #ifndef MAGNUM_TARGET_GLES SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, configuration.version() >= Version::GL310 ? SDL_GL_CONTEXT_PROFILE_CORE : SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())); /* Request usable version otherwise */ } else { #ifndef MAGNUM_TARGET_GLES /* First try to create core context. This is needed mainly on OS X and Mesa, as support for recent OpenGL versions isn't implemented in compatibility contexts (which are the default). At least GL 3.2 is needed on OSX, at least GL 3.1 is needed on Mesa. Bite the bullet and try 3.1 also elsewhere. */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #ifdef CORRADE_TARGET_APPLE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())|SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); #else /* For ES the major context version is compile-time constant */ #ifdef MAGNUM_TARGET_GLES3 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #elif defined(MAGNUM_TARGET_GLES2) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); #else #error unsupported OpenGL ES version #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif } /* Create window */ if(!(_window = SDL_CreateWindow(configuration.title().data(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, configuration.size().x(), configuration.size().y(), SDL_WINDOW_OPENGL|windowFlags))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create window:" << SDL_GetError(); return false; } /* Create context */ _glContext = SDL_GL_CreateContext(_window); #ifndef MAGNUM_TARGET_GLES /* Fall back to (forward compatible) GL 2.1, if version is not user-specified and either core context creation fails or we are on binary NVidia/AMD drivers on Linux/Windows. Instead of creating forward- compatible context with highest available version, they force the version to the one specified, which is completely useless behavior. */ #ifndef CORRADE_TARGET_APPLE constexpr static const char nvidiaVendorString[] = "NVIDIA Corporation"; constexpr static const char amdVendorString[] = "ATI Technologies Inc."; const char* vendorString; #endif if(configuration.version() == Version::None && (!_glContext #ifndef CORRADE_TARGET_APPLE /* Sorry about the UGLY code, HOPEFULLY THERE WON'T BE MORE WORKAROUNDS */ || (vendorString = reinterpret_cast<const char*>(glGetString(GL_VENDOR)), (std::strncmp(vendorString, nvidiaVendorString, sizeof(nvidiaVendorString)) == 0 || std::strncmp(vendorString, amdVendorString, sizeof(amdVendorString)) == 0) && !_context->isDriverWorkaroundDisabled("amd-nv-no-forward-compatible-core-context")) #endif )) { /* Don't print any warning when doing the NV workaround, because the bug will be there probably forever */ if(!_glContext) Warning() << "Platform::Sdl2Application::tryCreateContext(): cannot create core context:" << SDL_GetError() << "(falling back to compatibility context)"; else SDL_GL_DeleteContext(_glContext); SDL_DestroyWindow(_window); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())); if(!(_window = SDL_CreateWindow(configuration.title().data(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, configuration.size().x(), configuration.size().y(), SDL_WINDOW_OPENGL|windowFlags))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create window:" << SDL_GetError(); return false; } /* Create compatibility context */ _glContext = SDL_GL_CreateContext(_window); } #endif /* Cannot create context (or fallback compatibility context on desktop) */ if(!_glContext) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create context:" << SDL_GetError(); SDL_DestroyWindow(_window); _window = nullptr; return false; } #else /* Emscripten-specific initialization */ _glContext = SDL_SetVideoMode(configuration.size().x(), configuration.size().y(), 24, SDL_OPENGL|SDL_HWSURFACE|SDL_DOUBLEBUF); #endif /* Return true if the initialization succeeds */ return _context->tryCreate(); }