int glutmain(int argc, char **argv,int width,int height,const char* title,DemoApplication* demoApp, int posX, int posY, bool showWindow) { gDemoApplication = demoApp; glutInit(&argc, argv); //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowPosition(posX, posY); glutInitWindowSize(width, height); glutCreateWindow(title); #ifdef BT_USE_FREEGLUT glutSetOption (GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif gDemoApplication->myinit(); glutKeyboardFunc(glutKeyboardCallback); glutKeyboardUpFunc(glutKeyboardUpCallback); glutSpecialFunc(glutSpecialKeyboardCallback); glutSpecialUpFunc(glutSpecialKeyboardUpCallback); glutReshapeFunc(glutReshapeCallback); //createMenu(); glutIdleFunc(glutMoveAndDisplayCallback); glutMouseFunc(glutMouseFuncCallback); glutPassiveMotionFunc(glutMotionFuncCallback); glutMotionFunc(glutMotionFuncCallback); glutDisplayFunc( glutDisplayCallback ); glutMoveAndDisplayCallback(); //enable vsync to avoid tearing on Apple (todo: for Windows) #if defined(__APPLE__) && !defined (VMDMESA) int swap_interval = 1; CGLContextObj cgl_context = CGLGetCurrentContext(); CGLSetParameter(cgl_context, kCGLCPSwapInterval, &swap_interval); #endif if (!showWindow) glutHideWindow(); glutMainLoop(); return 0; }
void zl_glx_vsync(zl_glx *x, bool sync) { #ifdef TARGET_WIN32 if (sync) { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (1); } else { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (0); } #endif #ifdef TARGET_OSX long sync = sync ? 1 : 0; CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); #endif #ifdef TARGET_LINUX int interval = sync ? 2 : 0; glXSwapIntervalSGIFunc glXSwapIntervalSGI = 0; glXSwapIntervalMESAFunc glXSwapIntervalMESA = 0; if (GLXExtensionSupported(x->xdpy->dpy, "GLX_MESA_swap_control")) { glXSwapIntervalMESA = (glXSwapIntervalMESAFunc) glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA"); if (glXSwapIntervalMESA) { ZL_LOG("glXSwapIntervalMESA(%d)", interval); glXSwapIntervalMESA (interval); } else { ZL_LOG("Could not get glXSwapIntervalMESA()\n"); } } else if (GLXExtensionSupported(x->xdpy->dpy, "GLX_SGI_swap_control")) { glXSwapIntervalSGI = (glXSwapIntervalSGIFunc) glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalSGI"); if (glXSwapIntervalSGI) { ZL_LOG("glXSwapIntervalSGI(%d)", interval, glXSwapIntervalSGI); glXSwapIntervalSGI (interval); } else { ZL_LOG("Could not get glXSwapIntervalSGI()\n"); } } else { ZL_LOG("can't change vblank settings"); } #endif }
void GLWidget::initializeGL() { // For VSYNC problem under Mac OS X #if defined(Q_OS_MAC) const GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif // OpenGL initialisation from NEHE production m_GlView.initGl(); // Reframe the scene m_GlView.reframe(m_ShuttleBoundingBox); glEnable(GL_NORMALIZE); m_MotionTimer.start(60); }
static CGLContextObj gfx_ctx_cgl_init_create(void) { GLint num, params = 1; CGLPixelFormatObj pix; CGLContextObj glCtx = NULL; CGLPixelFormatAttribute attributes[] = { kCGLPFAAccelerated, kCGLPFADoubleBuffer, (CGLPixelFormatAttribute)0 }; CGLChoosePixelFormat(attributes, &pix, &num); CGLCreateContext(pix, NULL, &glCtx); CGLDestroyPixelFormat(pix); CGLSetParameter(glCtx, kCGLCPSwapInterval, ¶ms); return glCtx; }
/* PsychOSSetVBLSyncLevel - Enable or disable synchronization of bufferswaps to * onset of vertical retrace. This is the OS-X version... */ void PsychOSSetVBLSyncLevel(PsychWindowRecordType *windowRecord, int swapInterval) { CGLError error; GLint myinterval = (GLint) swapInterval; psych_bool oldStyle = (PsychPrefStateGet_ConserveVRAM() & kPsychUseOldStyleAsyncFlips) ? TRUE : FALSE; // Store new setting also in internal helper variable, e.g., to allow workarounds to work: windowRecord->vSynced = (swapInterval > 0) ? TRUE : FALSE; error=CGLSetParameter((oldStyle || PsychIsMasterThread()) ? windowRecord->targetSpecific.contextObject : windowRecord->targetSpecific.glswapcontextObject, kCGLCPSwapInterval, &myinterval); if (error) { if (PsychPrefStateGet_Verbosity()>1) printf("\nPTB-WARNING: FAILED to %s synchronization to vertical retrace!\n\n", (swapInterval>0) ? "enable" : "disable"); } error=CGLGetParameter((oldStyle || PsychIsMasterThread()) ? windowRecord->targetSpecific.contextObject : windowRecord->targetSpecific.glswapcontextObject, kCGLCPSwapInterval, &myinterval); if (error || (myinterval != (GLint) swapInterval)) { if (PsychPrefStateGet_Verbosity()>1) printf("\nPTB-WARNING: FAILED to %s synchronization to vertical retrace (System ignored setting)!\n\n", (swapInterval>0) ? "enable" : "disable"); } }
//----------------------------------------------------------------// void _AKUOpenWindowFunc ( const char* title, int width, int height ) { sWinX = 180; sWinY = 100; sWinWidth = width; sWinHeight = height; sWinWidth = width; sWinHeight = height; if ( !sHasWindow ) { glutInitDisplayMode ( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glutInitWindowSize ( sWinWidth, sWinHeight ); glutInitWindowPosition ( sWinX, sWinY ); glutCreateWindow ( title ); sHasWindow = true; } glutIgnoreKeyRepeat ( 1 ); glutKeyboardFunc ( _onKeyDown ); glutKeyboardUpFunc ( _onKeyUp ); glutSpecialFunc ( _onSpecialDown ); glutSpecialUpFunc ( _onSpecialUp ); glutMouseFunc ( _onMouseButton ); glutMotionFunc ( _onMouseDrag ); glutPassiveMotionFunc ( _onMouseMove ); glutDisplayFunc ( _onPaint ); glutReshapeFunc ( _onReshape ); AKUDetectGfxContext (); AKUSetScreenSize ( width, height ); #ifdef __APPLE__ GLint sync = 1; CGLContextObj ctx = CGLGetCurrentContext(); CGLSetParameter (ctx, kCGLCPSwapInterval, &sync); #endif }
//// Private functions //// void ModelViewGadgetWidget::initializeGL() { // For VSYNC problem under Mac OS X #if defined(Q_OS_MAC) const GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif // OpenGL initialization m_GlView.initGl(); // Reframe the scene m_GlView.reframe(m_ModelBoundingBox); glEnable(GL_NORMALIZE); // Enable antialiasing glEnable(GL_MULTISAMPLE); m_MotionTimer.start(100); setFocusPolicy(Qt::StrongFocus); // keyboard capture for camera switching }
void _glfwPlatformSwapInterval( int interval ) { GLint AGLparameter = interval; // CGL doesn't seem to like intervals other than 0 (vsync off) or 1 (vsync on) long CGLparameter = ( interval == 0 ? 0 : 1 ); if( !_glfwWin.Fullscreen ) { // Don't care if we fail here.. (void)aglSetInteger( _glfwWin.AGLContext, AGL_SWAP_INTERVAL, &AGLparameter ); } else { // ..or here (void)CGLSetParameter( _glfwWin.CGLContext, kCGLCPSwapInterval, &CGLparameter ); } }
//-------------------------------------- void ofSetVerticalSync(bool bSync){ //---------------------------- #ifdef TARGET_WIN32 //---------------------------- if (bSync) { if (WGL_EXT_swap_control) wglSwapIntervalEXT (1); } else { if (WGL_EXT_swap_control) wglSwapIntervalEXT (0); } //---------------------------- #endif //---------------------------- //-------------------------------------- #ifdef TARGET_OSX //-------------------------------------- GLint sync = bSync == true ? 1 : 0; CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); //-------------------------------------- #endif //-------------------------------------- //-------------------------------------- #ifdef TARGET_LINUX //-------------------------------------- //if (GLEW_GLX_SGI_swap_control) #warning "JVC" /*void (*swapInterval)(int) = (void (*)(int)) glXGetProcAddress((const GLubyte*) "glXSwapIntervalSGI"); if(!swapInterval) swapInterval = (void (*)(int)) glXGetProcAddress((const GLubyte*) "glXSwapIntervalMESA"); if(swapInterval) swapInterval(bSync ? 1 : 0);*/ //glXSwapIntervalSGI(bSync ? 1 : 0); //-------------------------------------- #endif //-------------------------------------- }
void sdlwrap_set_swap_interval(unsigned interval, bool inited) { g_interval = interval; bool success = true; #if SDL_MODERN if (g_window) success = SDL_GL_SetSwapInterval(g_interval) == 0; #else if (inited) { #if defined(_WIN32) static BOOL (APIENTRY *wgl_swap_interval)(int) = NULL; if (!wgl_swap_interval) SDL_SYM_WRAP(wgl_swap_interval, "wglSwapIntervalEXT"); if (wgl_swap_interval) success = wgl_swap_interval(g_interval); #elif defined(__APPLE__) && defined(HAVE_OPENGL) GLint val = g_interval; success = CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &val) == 0; #else static int (*glx_swap_interval)(int) = NULL; if (!glx_swap_interval) SDL_SYM_WRAP(glx_swap_interval, "glXSwapIntervalSGI"); if (!glx_swap_interval) SDL_SYM_WRAP(glx_swap_interval, "glXSwapIntervalMESA"); if (glx_swap_interval) success = glx_swap_interval(g_interval) == 0; else RARCH_WARN("Could not find GLX VSync call.\n"); #endif } #endif if (!success) RARCH_WARN("Failed to set swap interval.\n"); }
static bool create_gl_context(struct MPGLContext *ctx, int vo_flags) { struct cgl_context *p = ctx->priv; CGLError err; CGLOpenGLProfile gl_versions[] = { kCGLOGLPVersion_3_2_Core, kCGLOGLPVersion_Legacy, }; for (int n = 0; n < MP_ARRAY_SIZE(gl_versions); n++) { err = test_gl_version(ctx->vo, &p->ctx, &p->pix, gl_versions[n]); if (err == kCGLNoError) break; } if (err != kCGLNoError) { MP_FATAL(ctx->vo, "error creating CGL context: %s (%d)\n", CGLErrorString(err), err); return false; } vo_cocoa_set_opengl_ctx(ctx->vo, p->ctx); CGLSetCurrentContext(p->ctx); if (vo_flags & VOFLAG_ALPHA) CGLSetParameter(p->ctx, kCGLCPSurfaceOpacity, &(GLint){0}); mpgl_load_functions(ctx->gl, (void *)cocoa_glgetaddr, NULL, ctx->vo->log); ctx->gl->fb_r = ctx->gl->fb_g = ctx->gl->fb_b = cgl_color_size(ctx); ctx->gl->fb_premultiplied = true; CGLReleasePixelFormat(p->pix); return true; }
/* enableSync true means synchronize buffer swaps to monitor refresh; false means do NOT synchornize. */ void requestSynchornizedSwapBuffers(int enableSync) { #if defined(__APPLE__) #ifdef GL_VERSION_1_2 const GLint sync = enableSync; #else const GLint sync = enableSync; #endif CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); #elif defined(_WIN32) PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapIntervalEXT) { wglSwapIntervalEXT(enableSync); } #else PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalSGI"); if (glXSwapIntervalSGI) { glXSwapIntervalSGI(enableSync); } #endif }
// Setup function for GLUT parameters and loop //***************************************************************************** void InitGL(int* argc, char **argv) { // init GLUT glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowPosition (glutGet(GLUT_SCREEN_WIDTH)/2 - iGraphicsWinWidth/2, glutGet(GLUT_SCREEN_HEIGHT)/2 - iGraphicsWinHeight/2); glutInitWindowSize(iGraphicsWinWidth, iGraphicsWinHeight); iGLUTWindowHandle = glutCreateWindow("OpenCL for GPU Nbody Demo"); #if !(defined (__APPLE__) || defined(MACOSX) || defined(__EMSCRIPTEN__)) glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif // init GLEW #ifndef __EMSCRIPTEN__ glewInit(); GLboolean bGlew = glewIsSupported("GL_VERSION_2_0 " "GL_VERSION_1_5 " "GL_ARB_multitexture " "GL_ARB_vertex_buffer_object"); oclCheckErrorEX(bGlew, shrTRUE, pCleanup); #endif glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); renderer = new ParticleRenderer(); // check GL errors GLenum error; while ((error = glGetError()) != GL_NO_ERROR) { #ifdef __EMSCRIPTEN__ shrLog("InitGL: error - %d\n", error); #else shrLog("InitGL: error - %s\n", (char *)gluErrorString(error)); #endif } // Disable vertical sync, if supported #ifdef _WIN32 if (wglewIsSupported("WGL_EXT_swap_control")) { iVsyncState = wglGetSwapIntervalEXT(); wglSwapIntervalEXT(0); } #else #if defined (__APPLE__) || defined(MACOSX) GLint VBL = 0; CGLGetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &iVsyncState); CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); #elif __EMSCRIPTEN__ #else if(glxewIsSupported("GLX_SGI_swap_control")) { glXSwapIntervalSGI(0); } #endif #endif // create a new parameter list paramlist = new ParamListGL("sliders"); paramlist->bar_col_outer[0] = 0.8f; paramlist->bar_col_outer[1] = 0.8f; paramlist->bar_col_outer[2] = 0.0f; paramlist->bar_col_inner[0] = 0.8f; paramlist->bar_col_inner[1] = 0.8f; paramlist->bar_col_inner[2] = 0.0f; // add parameters to the list // Point Size paramlist->AddParam(new Param<float>("Point Size", activeParams.m_pointSize, 0.0f, 10.0f, 0.01f, &activeParams.m_pointSize)); // Velocity Damping paramlist->AddParam(new Param<float>("Velocity Damping", activeParams.m_damping, 0.5f, 1.0f, .0001f, &(activeParams.m_damping))); // Softening Factor paramlist->AddParam(new Param<float>("Softening Factor", activeParams.m_softening, 0.001f, 1.0f, .0001f, &(activeParams.m_softening))); // Time step size paramlist->AddParam(new Param<float>("Time Step", activeParams.m_timestep, 0.0f, 1.0f, .0001f, &(activeParams.m_timestep))); // Cluster scale (only affects starting configuration paramlist->AddParam(new Param<float>("Cluster Scale", activeParams.m_clusterScale, 0.0f, 10.0f, 0.01f, &(activeParams.m_clusterScale))); // Velocity scale (only affects starting configuration) paramlist->AddParam(new Param<float>("Velocity Scale", activeParams.m_velocityScale, 0.0f, 1000.0f, 0.1f, &activeParams.m_velocityScale)); }
int main(int argc, char ** argv) { unsigned int displayMode; #ifdef __APPLE__ GLint VBL = 1; #endif char workingDir[PATH_MAX]; int chdirReturn; char * getcwdReturn; getcwdReturn = getcwd(workingDir, PATH_MAX); glutInit(&argc, argv); chdirReturn = chdir(workingDir); configuration.windowX = 2; configuration.windowY = 28; configuration.windowWidth = 800; configuration.windowHeight = 600; configuration.windowTitle = "GLUTShell"; configuration.displayMode.doubleBuffer = true; configuration.displayMode.depthBuffer = false; configuration.displayMode.stencilBuffer = false; configuration.displayMode.accumBuffer = false; configuration.displayMode.multisample = false; GLUTTarget_configure(argc, (const char **) argv, &configuration); displayMode = GLUT_RGBA; if (configuration.displayMode.doubleBuffer) { displayMode |= GLUT_DOUBLE; } if (configuration.displayMode.depthBuffer) { displayMode |= GLUT_DEPTH; } if (configuration.displayMode.stencilBuffer) { displayMode |= GLUT_STENCIL; } if (configuration.displayMode.accumBuffer) { displayMode |= GLUT_ACCUM; } if (configuration.displayMode.multisample) { displayMode |= GLUT_MULTISAMPLE; } glutInitDisplayMode(displayMode); glutInitWindowPosition(configuration.windowX, configuration.windowY); glutInitWindowSize(configuration.windowWidth, configuration.windowHeight); glutCreateWindow(configuration.windowTitle); glutReshapeFunc(reshapeFunc); glutDisplayFunc(displayFunc); glutKeyboardFunc(keyDownFunc); glutKeyboardUpFunc(keyUpFunc); glutSpecialFunc(specialDownFunc); glutSpecialUpFunc(specialUpFunc); glutMouseFunc(mouseFunc); glutMotionFunc(motionFunc); glutPassiveMotionFunc(motionFunc); #ifdef __APPLE__ CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); #endif GLGraphics_init(GL_API_VERSION_DESKTOP_1); Target_init(argc, argv); return EXIT_SUCCESS; }
void CocoaVideoDriver::loop(Card* initial) { CGLPixelFormatAttribute attrs[] = { kCGLPFAOpenGLProfile, (CGLPixelFormatAttribute)kCGLOGLPVersion_3_2_Core, kCGLPFADisplayMask, static_cast<CGLPixelFormatAttribute>( CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)), kCGLPFAColorSize, static_cast<CGLPixelFormatAttribute>(24), kCGLPFADoubleBuffer, kCGLPFAAccelerated, static_cast<CGLPixelFormatAttribute>(0), }; cgl::PixelFormat pixel_format(attrs); cgl::Context context(pixel_format.c_obj(), NULL); unique_ptr<CocoaFullscreen> fullscreen; unique_ptr<CocoaWindowed> windowed; if (_fullscreen) { fullscreen.reset(new CocoaFullscreen(pixel_format, context, _screen_size)); antares_event_translator_set_window(_translator.c_obj(), fullscreen->window()); _viewport_size = fullscreen->viewport_size(); } else { windowed.reset(new CocoaWindowed(pixel_format, context, _screen_size, false, true)); antares_event_translator_set_window(_translator.c_obj(), windowed->window()); _viewport_size = windowed->viewport_size(); } GLint swap_interval = 1; CGLSetParameter(context.c_obj(), kCGLCPSwapInterval, &swap_interval); CGLSetCurrentContext(context.c_obj()); MainLoop main_loop(*this, initial); main_loop.draw(); CGLFlushDrawable(context.c_obj()); EventBridge bridge = {_event_tracker, main_loop, context, _translator}; antares_event_translator_set_mouse_down_callback( _translator.c_obj(), EventBridge::mouse_down, &bridge); antares_event_translator_set_mouse_up_callback( _translator.c_obj(), EventBridge::mouse_up, &bridge); antares_event_translator_set_mouse_move_callback( _translator.c_obj(), EventBridge::mouse_move, &bridge); antares_event_translator_set_caps_lock_callback( _translator.c_obj(), EventBridge::caps_lock, &bridge); antares_event_translator_set_caps_unlock_callback( _translator.c_obj(), EventBridge::caps_unlock, &bridge); cf::MutableDictionary keyboard(CFDictionaryCreateMutable( NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); keyboard.set(CFSTR(kIOHIDDeviceUsagePageKey), cf::wrap(kHIDPage_GenericDesktop).c_obj()); keyboard.set(CFSTR(kIOHIDDeviceUsageKey), cf::wrap(kHIDUsage_GD_Keyboard).c_obj()); cf::MutableDictionary gamepad(CFDictionaryCreateMutable( NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); gamepad.set(CFSTR(kIOHIDDeviceUsagePageKey), cf::wrap(kHIDPage_GenericDesktop).c_obj()); gamepad.set(CFSTR(kIOHIDDeviceUsageKey), cf::wrap(kHIDUsage_GD_GamePad).c_obj()); cf::MutableArray criteria(CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks)); criteria.append(keyboard.c_obj()); criteria.append(gamepad.c_obj()); auto hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); IOHIDManagerSetDeviceMatchingMultiple(hid_manager, criteria.c_obj()); IOHIDManagerScheduleWithRunLoop(hid_manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); IOReturn r = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone); if (r != 0) { throw Exception("IOHIDManagerOpen"); } IOHIDManagerRegisterInputValueCallback(hid_manager, EventBridge::hid_event, &bridge); while (!main_loop.done()) { int64_t at; if (main_loop.top()->next_timer(at)) { at += _start_time; if (antares_event_translator_next(_translator.c_obj(), at)) { bridge.send_all(); } else { main_loop.top()->fire_timer(); main_loop.draw(); CGLFlushDrawable(context.c_obj()); } } else { at = std::numeric_limits<int64_t>::max(); antares_event_translator_next(_translator.c_obj(), at); bridge.send_all(); } } }
bool Graphics::setOpenGLMode() { #ifdef USE_OPENGL SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (!(mWindow = graphicsManager.createWindow( mActualWidth, mActualHeight, mBpp, getOpenGLFlags()))) { logger->log("Window/context creation failed"); mRect.w = 0; mRect.h = 0; return false; } #if defined(USE_X11) Glx::initFunctions(); #endif #ifdef USE_SDL2 int w1 = 0; int h1 = 0; SDL_GetWindowSize(mWindow, &w1, &h1); mRect.w = static_cast<int32_t>(w1 / mScale); mRect.h = static_cast<int32_t>(h1 / mScale); createGLContext(); #else // USE_SDL2 createGLContext(); mRect.w = static_cast<uint16_t>(mWindow->w / mScale); mRect.h = static_cast<uint16_t>(mWindow->h / mScale); #endif // USE_SDL2 #ifdef __APPLE__ if (mSync) { const GLint VBL = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); } #endif graphicsManager.setGLVersion(); graphicsManager.logVersion(); // Setup OpenGL glViewport(0, 0, mActualWidth, mActualHeight); int gotDoubleBuffer = 0; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &gotDoubleBuffer); logger->log("Using OpenGL %s double buffering.", (gotDoubleBuffer ? "with" : "without")); graphicsManager.initOpenGL(); initArrays(graphicsManager.getMaxVertices()); graphicsManager.updateTextureCompressionFormat(); graphicsManager.updateTextureFormat(); updateMemoryInfo(); GLint texSize; bool rectTex = graphicsManager.supportExtension( "GL_ARB_texture_rectangle"); if (rectTex && OpenGLImageHelper::getInternalTextureType() == 4 && getOpenGL() != RENDER_GLES_OPENGL && getOpenGL() != RENDER_MODERN_OPENGL && config.getBoolValue("rectangulartextures") && !graphicsManager.isUseTextureSampler()) { logger->log1("using GL_ARB_texture_rectangle"); OpenGLImageHelper::mTextureType = GL_TEXTURE_RECTANGLE_ARB; glEnable(GL_TEXTURE_RECTANGLE_ARB); glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &texSize); OpenGLImageHelper::mTextureSize = texSize; logger->log("OpenGL texture size: %d pixels (rectangle textures)", OpenGLImageHelper::mTextureSize); } else { OpenGLImageHelper::mTextureType = GL_TEXTURE_2D; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); OpenGLImageHelper::mTextureSize = texSize; logger->log("OpenGL texture size: %d pixels", OpenGLImageHelper::mTextureSize); } return videoInfo(); #else // USE_OPENGL return false; #endif // USE_OPENGL }
extern "C" int main(int argcount, char* argvec[]) #endif { #if defined(__native_client__) std::cerr << "Running game_main" << std::endl; chdir("/frogatto"); { char buf[256]; const char* const res = getcwd(buf,sizeof(buf)); std::cerr << "Current working directory: " << res << std::endl; } #endif #if defined(__APPLE__) && TARGET_OS_MAC chdir([[[NSBundle mainBundle] resourcePath] fileSystemRepresentation]); #endif #ifdef NO_STDERR std::freopen("/dev/null", "w", stderr); std::cerr.sync_with_stdio(true); #endif std::cerr << "Frogatto engine version " << preferences::version() << "\n"; LOG( "After print engine version" ); #if defined(TARGET_BLACKBERRY) chdir("app/native"); std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl; #endif game_logic::init_callable_definitions(); std::string level_cfg = "titlescreen.cfg"; bool unit_tests_only = false, skip_tests = false; bool run_benchmarks = false; std::vector<std::string> benchmarks_list; std::string utility_program; std::vector<std::string> util_args; std::string server = "wesnoth.org"; #if defined(UTILITY_IN_PROC) bool create_utility_in_new_process = false; std::string utility_name; #endif bool is_child_utility = false; const char* profile_output = NULL; std::string profile_output_buf; #if defined(__ANDROID__) //monstartup("libapplication.so"); #endif std::string orig_level_cfg = level_cfg; std::string override_level_cfg = ""; int modules_loaded = 0; std::vector<std::string> argv; for(int n = 1; n < argcount; ++n) { #if defined(UTILITY_IN_PROC) std::string sarg(argvec[n]); if(sarg.compare(0, 15, "--utility-proc=") == 0) { create_utility_in_new_process = true; utility_name = "--utility-child=" + sarg.substr(15); } else { argv.push_back(argvec[n]); } #else argv.push_back(argvec[n]); #endif if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") { //XCode passes these arguments by default when debugging -- make sure they are ignored. argv.resize(argv.size()-2); } } #if defined(UTILITY_IN_PROC) if(create_utility_in_new_process) { argv.push_back(utility_name); #if defined(_MSC_VER) // app name is ignored for windows, we get windows to tell us. is_child_utility = create_utility_process("", argv); #else is_child_utility = create_utility_process(argvec[0], argv); #endif if(!is_child_utility) { argv.pop_back(); } #if defined(_MSC_VER) atexit(terminate_utility_process); #endif } #endif if(sys::file_exists("./master-config.cfg")) { std::cerr << "LOADING CONFIGURATION FROM master-config.cfg" << std::endl; variant cfg = json::parse_from_file("./master-config.cfg"); if(cfg.is_map()) { if( cfg["id"].is_null() == false) { std::cerr << "SETTING MODULE PATH FROM master-config.cfg: " << cfg["id"].as_string() << std::endl; preferences::set_preferences_path_from_module(cfg["id"].as_string()); //XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string()); } if(cfg["arguments"].is_null() == false) { std::vector<std::string> additional_args = cfg["arguments"].as_list_string(); argv.insert(argv.begin(), additional_args.begin(), additional_args.end()); std::cerr << "ADDING ARGUMENTS FROM master-config.cfg:"; for(size_t n = 0; n < cfg["arguments"].num_elements(); ++n) { std::cerr << " " << cfg["arguments"][n].as_string(); } std::cerr << std::endl; } } } stats::record_program_args(argv); for(size_t n = 0; n < argv.size(); ++n) { const int argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } if(arg_name == "--module") { if(load_module(arg_value, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n"; return -1; } ++modules_loaded; } } if(modules_loaded == 0) { if(load_module(DEFAULT_MODULE, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n"; return -1; } } preferences::load_preferences(); LOG( "After load_preferences()" ); // load difficulty settings after module, before rest of args. difficulty::manager(); for(size_t n = 0; n < argv.size(); ++n) { const size_t argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } std::cerr << "ARGS: " << arg << std::endl; if(arg_name == "--module") { // ignore already processed. } else if(arg_name == "--profile" || arg == "--profile") { profile_output_buf = arg_value; profile_output = profile_output_buf.c_str(); } else if(arg_name == "--utility" || arg_name == "--utility-child") { if(arg_name == "--utility-child") { is_child_utility = true; } utility_program = arg_value; for(++n; n < argc; ++n) { const std::string arg(argv[n]); util_args.push_back(arg); } break; } else if(arg == "--benchmarks") { run_benchmarks = true; } else if(arg_name == "--benchmarks") { run_benchmarks = true; benchmarks_list = util::split(arg_value); } else if(arg == "--tests") { unit_tests_only = true; } else if(arg == "--no-tests") { skip_tests = true; } else if(arg_name == "--width") { std::string w(arg_value); preferences::set_actual_screen_width(boost::lexical_cast<int>(w)); } else if(arg == "--width" && n+1 < argc) { std::string w(argv[++n]); preferences::set_actual_screen_width(boost::lexical_cast<int>(w)); } else if(arg_name == "--height") { std::string h(arg_value); preferences::set_actual_screen_height(boost::lexical_cast<int>(h)); } else if(arg == "--height" && n+1 < argc) { std::string h(argv[++n]); preferences::set_actual_screen_height(boost::lexical_cast<int>(h)); } else if(arg_name == "--level") { override_level_cfg = arg_value; } else if(arg == "--level" && n+1 < argc) { override_level_cfg = argv[++n]; } else if(arg_name == "--host") { server = arg_value; } else if(arg == "--host" && n+1 < argc) { server = argv[++n]; } else if(arg == "--compiled") { preferences::set_load_compiled(true); #ifndef NO_EDITOR } else if(arg == "--edit") { preferences::set_edit_on_start(true); #endif } else if(arg == "--no-compiled") { preferences::set_load_compiled(false); #if defined(TARGET_PANDORA) } else if(arg == "--no-fbo") { preferences::set_fbo(false); } else if(arg == "--no-bequ") { preferences::set_bequ(false); #endif } else if(arg == "--help" || arg == "-h") { print_help(std::string(argvec[0])); return 0; } else { const bool res = preferences::parse_arg(argv[n].c_str()); if(!res) { std::cerr << "unrecognized arg: '" << arg << "'\n"; return -1; } } } checksum::manager checksum_manager; #ifndef NO_EDITOR sys::filesystem_manager fs_manager; #endif // NO_EDITOR preferences::expand_data_paths(); background_task_pool::manager bg_task_pool_manager; LOG( "After expand_data_paths()" ); std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n'; //make sure that the user data path exists. if(!preferences::setup_preferences_dir()) { std::cerr << "cannot create preferences dir!\n"; } std::cerr << "\n"; if(preferences::internal_tbs_server()) { tbs::internal_server::init(); } if(utility_program.empty() == false && test::utility_needs_video(utility_program) == false) { #if defined(UTILITY_IN_PROC) if(is_child_utility) { ASSERT_LOG(ipc::semaphore::create(shared_sem_name, 1) != false, "Unable to create shared semaphore: " << errno); std::cerr.sync_with_stdio(true); } #endif test::run_utility(utility_program, util_args); return 0; } #if defined(TARGET_PANDORA) EGL_Open(); #endif #if defined(__ANDROID__) std::freopen("stdout.txt","w",stdout); std::freopen("stderr.txt","w",stderr); std::cerr.sync_with_stdio(true); #endif LOG( "Start of main" ); #if !defined(__native_client__) Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK; #if defined(_WINDOWS) || defined(TARGET_OS_IPHONE) sdl_init_flags |= SDL_INIT_TIMER; #endif if(SDL_Init(sdl_init_flags) < 0) { std::cerr << "could not init SDL\n"; return -1; } LOG( "After SDL_Init" ); #endif #ifdef TARGET_OS_HARMATTAN g_type_init(); #endif i18n::init (); LOG( "After i18n::init()" ); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); #if defined(TARGET_OS_IPHONE) || defined(TARGET_BLACKBERRY) || defined(__ANDROID__) //on the iPhone and PlayBook, try to restore the auto-save if it exists if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") { level_cfg = "autosave.cfg"; sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0"); } #endif if(override_level_cfg.empty() != true) { level_cfg = override_level_cfg; orig_level_cfg = level_cfg; } #if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(USE_GLES2) wm.create_window(preferences::actual_screen_width(), preferences::actual_screen_height(), 0, (preferences::resizable() ? SDL_RESIZABLE : 0) | (preferences::fullscreen() ? SDL_FULLSCREEN : 0)); #else #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR int width, height; iphone_screen_res(&width, &height); preferences::set_actual_screen_width(width); preferences::set_actual_screen_height(height); int multiplier = 2; if (width > 320) { //preferences::set_use_pretty_scaling(true); multiplier = 1; } preferences::set_virtual_screen_width(height*multiplier); preferences::set_virtual_screen_height(width*multiplier); preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d"); SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(), SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); if (windowID == 0) { std::cerr << "Could not create window: " << SDL_GetError() << "\n"; return -1; } // if (SDL_GL_CreateContext(windowID) == 0) { // std::cerr << "Could not create GL context: " << SDL_GetError() << "\n"; // return -1; // } if (SDL_CreateRenderer(windowID, -1, 0) != 0) { std::cerr << "Could not create renderer\n"; return -1; } #else #ifdef TARGET_OS_HARMATTAN SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } preferences::init_oes(); SDL_ShowCursor(0); #else #if defined(TARGET_PANDORA) if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } EGL_Init(); preferences::init_oes(); #elif defined(TARGET_TEGRA) //if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) { if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } EGL_Init(); preferences::init_oes(); #elif defined(TARGET_BLACKBERRY) if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } preferences::init_oes(); #elif defined(__ANDROID__) #if SDL_VERSION_ATLEAST(2, 0, 0) int num_video_displays = SDL_GetNumVideoDisplays(); SDL_Rect r; if(num_video_displays < 0) { std::cerr << "no video displays available" << std::endl; return -1; } if(SDL_GetDisplayBounds(0, &r) < 0) { preferences::set_actual_screen_width(r.w); preferences::set_actual_screen_height(r.h); if(r.w < 640) { preferences::set_virtual_screen_width(r.w*2); preferences::set_virtual_screen_height(r.h*2); } else { preferences::set_virtual_screen_width(r.w); preferences::set_virtual_screen_height(r.h); } preferences::set_control_scheme(r.h >= 1024 ? "ipad_2d" : "android_med"); } #else SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL); if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) { preferences::set_actual_screen_width(r[0]->w); preferences::set_actual_screen_height(r[0]->h); if(r[0]->w < 640) { preferences::set_virtual_screen_width(r[0]->w*2); preferences::set_virtual_screen_height(r[0]->h*2); } else { preferences::set_virtual_screen_width(r[0]->w); preferences::set_virtual_screen_height(r[0]->h); } preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med"); } #endif #if SDL_VERSION_ATLEAST(2, 0, 0) if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height())) { #else if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN|SDL_OPENGL) == NULL) { #endif std::cerr << "could not set video mode\n"; return -1; } #elif defined(__native_client__) SDL_Rect** r = SDL_ListModes(NULL, SDL_OPENGL); std::cerr << "Video modes"; if(r == (SDL_Rect**)0) { std::cerr << "No modes available"; return -1; } if(r == (SDL_Rect**)-1) { std::cerr << "All modes available"; } else { for(int i = 0; r[i]; ++i) { std::cerr << r[i]->w << r[i]->h << std::endl; } } if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,0) == NULL) { std::cerr << "could not set video mode\n"; return -1; } #else #if SDL_VERSION_ATLEAST(2, 0, 0) if(preferences::auto_size_window()) { const SDL_DisplayMode mode = graphics::set_video_mode_auto_select(); preferences::set_actual_screen_width(mode.w); preferences::set_actual_screen_height(mode.h); preferences::set_virtual_screen_width(mode.w); preferences::set_virtual_screen_height(mode.h); } else if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height())) { #else if(SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) { #endif std::cerr << "could not set video mode\n"; return -1; } #ifndef __APPLE__ graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png"); if(!wm_icon.null()) { #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_SetWindowIcon(graphics::get_window(), wm_icon.get()); #else SDL_WM_SetIcon(wm_icon, NULL); #endif } #endif // __APPLE__ #endif #endif #endif #endif #if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(__GLEW_H__) GLenum glew_status = glewInit(); ASSERT_EQ(glew_status, GLEW_OK); #endif #if defined(USE_GLES2) if(glCreateShader == NULL) { const GLubyte* glstrings; if(glGetString != NULL && (glstrings = glGetString(GL_VERSION)) != NULL) { std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl; } std::cerr << "glCreateShader is NULL. Check that your current video card drivers support " << "an OpenGL version >= 2. Exiting." << std::endl; return 0; } // Has to happen after the call to glewInit(). gles2::init_default_shader(); #endif // srand(time(NULL)); const stats::manager stats_manager; #ifndef NO_EDITOR const external_text_editor::manager editor_manager; #endif // NO_EDITOR #if defined(USE_BOX2D) box2d::manager b2d_manager; #endif std::cerr << std::endl; const GLubyte* glstrings; if((glstrings = glGetString(GL_VENDOR)) != NULL) { std::cerr << "OpenGL vendor: " << reinterpret_cast<const char *>(glstrings) << std::endl; } else { GLenum err = glGetError(); std::cerr << "Error in vendor string: " << std::hex << err << std::endl; } if((glstrings = glGetString(GL_VERSION)) != NULL) { std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl; } else { GLenum err = glGetError(); std::cerr << "Error in version string: " << std::hex << err << std::endl; } if((glstrings = glGetString(GL_EXTENSIONS)) != NULL) { std::cerr << "OpenGL extensions: " << reinterpret_cast<const char *>(glstrings) << std::endl; } else { GLenum err = glGetError(); std::cerr << "Error in extensions string: " << std::hex << err << std::endl; } #ifdef GL_SHADING_LANGUAGE_VERSION if((glstrings = glGetString(GL_SHADING_LANGUAGE_VERSION)) != NULL) { std::cerr << "GLSL Version: " << reinterpret_cast<const char *>(glstrings) << std::endl; } else { GLenum err = glGetError(); std::cerr << "Error in GLSL string: " << std::hex << err << std::endl; } #endif std::cerr << std::endl; GLint stencil_bits = 0; glGetIntegerv(GL_STENCIL_BITS, &stencil_bits); std::cerr << "Stencil bits: " << stencil_bits << std::endl; #if defined(USE_GLES2) GLfloat min_pt_sz; glGetFloatv(GL_POINT_SIZE_MIN, &min_pt_sz); GLfloat max_pt_sz; glGetFloatv(GL_POINT_SIZE_MAX, &max_pt_sz); std::cerr << "Point size range: " << min_pt_sz << " < size < " << max_pt_sz << std::endl; #if !defined(GL_ES_VERSION_2_0) glEnable(GL_POINT_SPRITE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif #endif glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); #if !defined(USE_GLES2) glEnable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n"; const load_level_manager load_manager; { //manager scope const font::manager font_manager; const sound::manager sound_manager; #if !defined(__native_client__) const joystick::manager joystick_manager; #endif graphics::texture::manager texture_manager; #ifndef NO_EDITOR editor::manager editor_manager; #endif variant preloads; loading_screen loader; try { sound::init_music(json::parse_from_file("data/music.cfg")); graphical_font::init_for_locale(i18n::get_locale()); preloads = json::parse_from_file("data/preload.cfg"); int preload_items = preloads["preload"].num_elements(); loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below custom_object::init(); loader.draw_and_increment(_("Initializing custom object functions")); init_custom_object_functions(json::parse_from_file("data/functions.cfg")); loader.draw_and_increment(_("Initializing textures")); loader.load(preloads); loader.draw_and_increment(_("Initializing tiles")); tile_map::init(json::parse_from_file("data/tiles.cfg")); loader.draw_and_increment(_("Initializing GUI")); variant gui_node = json::parse_from_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg"); gui_section::init(gui_node); loader.draw_and_increment(_("Initializing GUI")); framed_gui_element::init(gui_node); preferences::set_edit_and_continue(true); game_logic::formula_object::load_all_classes(); } catch(const json::parse_error& e) { std::cerr << "ERROR PARSING: " << e.error_message() << "\n"; return 0; } loader.draw(_("Loading level")); #if defined(__native_client__) while(1) { } #endif if(!skip_tests && !test::run_tests()) { return -1; } if(unit_tests_only) { return 0; } #if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) && !defined(USE_GLES2) GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif loader.finish_loading(); //look to see if we got any quit events while loading. { SDL_Event event; while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { return 0; } } } formula_profiler::manager profiler(profile_output); #ifdef USE_GLES2 texture_frame_buffer::init(preferences::actual_screen_width(), preferences::actual_screen_height()); #else texture_frame_buffer::init(); #endif if(run_benchmarks) { if(benchmarks_list.empty() == false) { test::run_benchmarks(&benchmarks_list); } else { test::run_benchmarks(); } return 0; } else if(utility_program.empty() == false && test::utility_needs_video(utility_program) == true) { test::run_utility(utility_program, util_args); return 0; } bool quit = false; while(!quit && !show_title_screen(level_cfg)) { boost::intrusive_ptr<level> lvl(load_level(level_cfg)); #if !defined(__native_client__) //see if we're loading a multiplayer level, in which case we //connect to the server. multiplayer::manager mp_manager(lvl->is_multiplayer()); if(lvl->is_multiplayer()) { multiplayer::setup_networked_game(server); } if(lvl->is_multiplayer()) { last_draw_position() = screen_position(); std::string level_cfg = "waiting-room.cfg"; boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg)); wait_lvl->finish_loading(); wait_lvl->set_multiplayer_slot(0); if(wait_lvl->player()) { wait_lvl->player()->set_current_level(level_cfg); } wait_lvl->set_as_current_level(); level_runner runner(wait_lvl, level_cfg, orig_level_cfg); multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner)); lvl->set_multiplayer_slot(multiplayer::slot()); } #endif last_draw_position() = screen_position(); assert(lvl.get()); if(!lvl->music().empty()) { sound::play_music(lvl->music()); } if(lvl->player() && level_cfg != "autosave.cfg") { lvl->player()->set_current_level(level_cfg); lvl->player()->get_entity().save_game(); } set_scene_title(lvl->title()); try { quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level(); level_cfg = orig_level_cfg; } catch(multiplayer_exception&) { } } level::clear_current_level(); } //end manager scope, make managers destruct before calling SDL_Quit // controls::debug_dump_controls(); #if defined(TARGET_PANDORA) || defined(TARGET_TEGRA) EGL_Destroy(); #endif #if SDL_VERSION_ATLEAST(2, 0, 0) // Be nice and destroy the GL context and the window. graphics::set_video_mode(0, 0, CLEANUP_WINDOW_CONTEXT); #elif defined(USE_GLES2) wm.destroy_window(); #endif SDL_Quit(); preferences::save_preferences(); std::cerr << SDL_GetError() << "\n"; #if !defined(TARGET_OS_HARMATTAN) && !defined(TARGET_TEGRA) && !defined(TARGET_BLACKBERRY) && !defined(__ANDROID__) && !defined(USE_GLES2) std::cerr << gluErrorString(glGetError()) << "\n"; #endif #if !defined(_MSC_VER) && defined(UTILITY_IN_PROC) if(create_utility_in_new_process) { terminate_utility_process(); } #endif #ifdef _MSC_VER ExitProcess(0); #endif return 0; }
BOOL OsToggleVsyncSwap(int sync) { /* FIXME:成功かどうか返す? */ CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); return TRUE; }
//-------------------------------------------------------------------------------------------------// void OSXWindow::createCGLFullscreen(unsigned int width, unsigned int height, unsigned int depth, unsigned int fsaa, CGLContextObj sharedContext) { // Find the best match to what was requested boolean_t exactMatch = 0; int reqWidth, reqHeight, reqDepth; #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // Get a copy of the current display mode CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay); // Loop through all display modes to determine the closest match. // CGDisplayBestModeForParameters is deprecated on 10.6 so we will emulate it's behavior // Try to find a mode with the requested depth and equal or greater dimensions first. // If no match is found, try to find a mode with greater depth and same or greater dimensions. // If still no match is found, just use the current mode. CFArrayRef allModes = CGDisplayCopyAllDisplayModes(kCGDirectMainDisplay, NULL); for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); String modeString = StringConverter::toString(CGDisplayModeGetWidth(mode)) + String(" x ") + StringConverter::toString(CGDisplayModeGetHeight(mode)) + String(" @ ") + StringConverter::toString(bitDepthFromDisplayMode(mode)) + "bpp."; LogManager::getSingleton().logMessage(modeString); if(bitDepthFromDisplayMode(mode) != depth) continue; if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height)) { displayMode = mode; exactMatch = 1; break; } } // No depth match was found if(!exactMatch) { for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); if(bitDepthFromDisplayMode(mode) >= depth) continue; if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height)) { displayMode = mode; exactMatch = 1; break; } } } reqWidth = CGDisplayModeGetWidth(displayMode); reqHeight = CGDisplayModeGetHeight(displayMode); reqDepth = bitDepthFromDisplayMode(displayMode); #else CFDictionaryRef displayMode = CGDisplayBestModeForParameters(kCGDirectMainDisplay, depth, width, height, &exactMatch); const void *value = NULL; value = CFDictionaryGetValue(displayMode, kCGDisplayWidth); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqWidth); value = CFDictionaryGetValue(displayMode, kCGDisplayHeight); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqHeight); value = CFDictionaryGetValue(displayMode, kCGDisplayBitsPerPixel); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqDepth); #endif if(!exactMatch) { // TODO: Report the size difference // That mode is not available, using the closest match String request = StringConverter::toString(width) + String(" x ") + StringConverter::toString(height) + String(" @ ") + StringConverter::toString(depth) + "bpp. "; String received = StringConverter::toString(reqWidth) + String(" x ") + StringConverter::toString(reqHeight) + String(" @ ") + StringConverter::toString(reqDepth) + "bpp. "; LogManager::getSingleton().logMessage(String("RenderSystem Warning: You requested a fullscreen mode of ") + request + String(" This mode is not available and you will receive the closest match. The best display mode for the parameters requested is: ") + received); } // Do the fancy display fading CGDisplayFadeReservationToken reservationToken; CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &reservationToken); CGDisplayFade(reservationToken, 0.5, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, true); // Grab the main display and save it for later. // You could render to any display, but picking what display // to render to could be interesting. CGDisplayCapture(kCGDirectMainDisplay); // Switch to the correct resolution #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGDisplaySetDisplayMode(kCGDirectMainDisplay, displayMode, NULL); #else CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode); #endif // Get a pixel format that best matches what we are looking for CGLPixelFormatAttribute attribs[] = { kCGLPFADoubleBuffer, kCGLPFAAlphaSize, (CGLPixelFormatAttribute)8, kCGLPFADepthSize, (CGLPixelFormatAttribute)reqDepth, kCGLPFAStencilSize, (CGLPixelFormatAttribute)8, kCGLPFASampleBuffers, (CGLPixelFormatAttribute)0, kCGLPFASamples, (CGLPixelFormatAttribute)0, kCGLPFAFullScreen, kCGLPFASingleRenderer, kCGLPFAAccelerated, kCGLPFADisplayMask, (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay), (CGLPixelFormatAttribute)0 }; // Set up FSAA if it was requested if(fsaa > 1) { // turn on kCGLPFASampleBuffers attribs[8] = (CGLPixelFormatAttribute)1; // set the samples for kCGLPFASamples attribs[10] = (CGLPixelFormatAttribute)fsaa; } CGLError err; CGLPixelFormatObj pixelFormatObj; #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #else long numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #endif if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Create the CGLcontext from our pixel format, share it with the sharedContext passed in err = CGLCreateContext(pixelFormatObj, sharedContext, &mCGLContext); if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Once we have the context we can destroy the pixel format // In order to share contexts you must keep a pointer to the context object around // Our context class will now manage the life of the pixelFormatObj //CGLDestroyPixelFormat(pixelFormatObj); // Set the context to full screen #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)); #else CGLSetFullScreen(mCGLContext); #endif // Set the context as current CGLSetCurrentContext(mCGLContext); // This synchronizes CGL with the vertical retrace // Apple docs suggest that OpenGL blocks rendering calls when waiting for // a vertical retrace anyhow. #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #else long swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #endif // Give a copy of our context to the rendersystem mContext = new OSXCGLContext(mCGLContext, pixelFormatObj); // Let everyone know we are fullscreen now mIsFullScreen = true; // Set some other variables. Just in case we got a different value from CGDisplayBestModeForParameters than we requested mWidth = reqWidth; mHeight = reqHeight; mColourDepth = reqDepth; CGDisplayFade(reservationToken, 2.0, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, false); CGReleaseDisplayFadeReservation(reservationToken); }
int art_init(int width, int height, int fullScreen, int colorDepth, int resizable, int windowDecorations, int vsync) { _art_sessionInit(); if (SDL_Init(SDL_INIT_VIDEO) != 0) { return -1; //TODO: Set error SDL_GetError() } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); unsigned int flags = SDL_OPENGL; if (fullScreen) { flags |= SDL_FULLSCREEN; } if (resizable) { flags |= SDL_RESIZABLE; } if (!windowDecorations) { flags |= SDL_NOFRAME; } if (SDL_SetVideoMode(width, height, colorDepth, flags) == NULL) { return -1; //TODO: Set error SDL_GetError() } artG_session.windowWidth = width; artG_session.windowHeight = height; Art_Layer* rootLayer = malloc(sizeof(Art_Layer)); _art_initLayer(rootLayer); _art_setRoot(rootLayer, width, height); art_setClearLayerOnUpdate(rootLayer, artG_session.clearOnUpdate); artG_session.rootLayer = rootLayer; artG_session.currentLayer = NULL; art_drawToRoot(); if (vsync) { // Activate vertical refresh synch on macs #if defined (__ARTIST_OS_OSX) GLint VBL = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); #endif } return 0; }
static int RLXAPI CreateSurface(int numberOfSparePages) { CGOpenGLDisplayMask displayMask = CGDisplayIDToOpenGLDisplayMask( g_cgDisplayID ) ; static CGLPixelFormatAttribute attribs[32]; CGLPixelFormatAttribute *pAttrib = attribs; CGLPixelFormatObj pixelFormatObj ; long numPixelFormats = 0; *pAttrib = kCGLPFAFullScreen; pAttrib++; *pAttrib = kCGLPFASingleRenderer; pAttrib++; *pAttrib = kCGLPFADisplayMask; pAttrib++; *pAttrib = (CGLPixelFormatAttribute)displayMask; pAttrib++; *pAttrib = kCGLPFADoubleBuffer; pAttrib++; *pAttrib = kCGLPFAColorSize; pAttrib++; *pAttrib = (CGLPixelFormatAttribute)gl_bpp; pAttrib++; if ((g_pRLX->pGX->View.Flags & GX_CAPS_MULTISAMPLING)) { *pAttrib = kCGLPFASampleBuffers; pAttrib++; *pAttrib = (CGLPixelFormatAttribute)1; pAttrib++; *pAttrib = kCGLPFASamples; pAttrib++; *pAttrib = (CGLPixelFormatAttribute)g_pRLX->pGX->View.Multisampling; pAttrib++; } if (SYS_CGLTRACE(CGLChoosePixelFormat( attribs, &pixelFormatObj, &numPixelFormats ))) return -1; if (!numPixelFormats) return -2; DEBUG_PIXEL_FORMAT(pixelFormatObj); if (SYS_CGLTRACE(CGLCreateContext( pixelFormatObj, NULL, &g_pCGLC ))) return -3; CGLDestroyPixelFormat( pixelFormatObj ) ; long swapInterval = !!(g_pRLX->pGX->View.Flags & GX_CAPS_VSYNC); SYS_CGLTRACE(CGLSetParameter( g_pCGLC, kCGLCPSwapInterval, &swapInterval)); SYS_CGLTRACE(CGLSetCurrentContext( g_pCGLC )); if (SYS_CGLTRACE(CGLSetFullScreen( g_pCGLC ))) { CGDisplaySwitchToMode(g_cgDisplayID, g_cgPrevDisplayMode); CGReleaseAllDisplays(); return -5; } HideMenuBar(); // Reset engine GL_InstallExtensions(); GL_ResetViewport(); g_pRLX->pGX->Surfaces.maxSurface = numberOfSparePages;; if (g_pRLX->pGX->View.Flags & GX_CAPS_MULTISAMPLING) { glEnable(GL_MULTISAMPLE_ARB); } return 0; }
bool gl_initialize(int screen_wid,int screen_high,bool lock_fps_refresh,int fsaa_mode,bool reset,char *err_str) { GLint ntxtunit,ntxtsize; #ifdef D3_OS_MAC long swapint,rect[4]; CGLContextObj current_ctx; CFDictionaryRef mode_info; CFNumberRef cf_rate; #else GLenum glew_error; #endif // setup rendering sizes setup.screen.x_sz=screen_wid; setup.screen.y_sz=screen_high; // 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,16); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); // full screen anti-aliasing attributes switch (fsaa_mode) { case fsaa_mode_low: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,2); break; case fsaa_mode_medium: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,4); break; case fsaa_mode_high: SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,6); break; } // start window or full screen if (gl_in_window_mode()) { surface=SDL_SetVideoMode(setup.screen.x_sz,setup.screen.y_sz,32,SDL_OPENGL|SDL_HWSURFACE); SDL_WM_SetCaption("dim3",NULL); } else { surface=SDL_SetVideoMode(setup.screen.x_sz,setup.screen.y_sz,32,SDL_OPENGL|SDL_FULLSCREEN); } if (surface==NULL) { sprintf(err_str,"SDL: Could not set video mode (Error: %s)",SDL_GetError()); return(FALSE); } // work around the dock losing minimize buttons because // of SDL luncancy #ifdef D3_OS_MAC if (!gl_in_window_mode()) SetSystemUIMode(kUIModeContentSuppressed,0); #endif // use glew on linux and windows #ifndef D3_OS_MAC 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_UNITS,&ntxtunit); render_info.texture_unit_count=(int)ntxtunit; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&ntxtsize); render_info.texture_max_size=(int)ntxtsize; // in case screen is bigger than desired drawing surface render_info.monitor_x_sz=surface->w; render_info.monitor_y_sz=surface->h; render_info.view_x=(render_info.monitor_x_sz-setup.screen.x_sz)>>1; render_info.view_y=(render_info.monitor_y_sz-setup.screen.y_sz)>>1; // determine the referesh rate render_info.monitor_refresh_rate=60; // windows XP has a stuck refresh rate of 60 #ifdef D3_OS_MAC mode_info=CGDisplayCurrentMode(CGMainDisplayID()); if (mode_info!=NULL) { cf_rate=(CFNumberRef)CFDictionaryGetValue(mode_info,kCGDisplayRefreshRate); if (cf_rate) { CFNumberGetValue(cf_rate,kCFNumberIntType,&render_info.monitor_refresh_rate); if (render_info.monitor_refresh_rate==0) render_info.monitor_refresh_rate=60; } } #endif // clear the entire window so it doesn't flash glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapBuffers(); // setup renderer #ifdef D3_OS_MAC current_ctx=CGLGetCurrentContext(); rect[0]=render_info.view_x; rect[1]=render_info.view_y; rect[2]=setup.screen.x_sz; rect[3]=setup.screen.y_sz; CGLSetParameter(current_ctx,kCGLCPSwapRectangle,rect); CGLEnable(current_ctx,kCGLCESwapRectangle); if (lock_fps_refresh) { swapint=1; CGLSetParameter(current_ctx,kCGLCPSwapInterval,&swapint); } #endif glViewport(render_info.view_x,render_info.view_y,setup.screen.x_sz,setup.screen.y_sz); // perspective correction glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); // smoothing and anti-aliasing glDisable(GL_DITHER); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT,GL_NICEST); if (fsaa_mode!=fsaa_mode_none) glEnable(GL_MULTISAMPLE); // texture compression glHint(GL_TEXTURE_COMPRESSION_HINT,GL_NICEST); glHint(GL_GENERATE_MIPMAP_HINT,GL_NICEST); // all alphas by 8 bit component glDisable(GL_ALPHA_TEST); // texture utility initialize gl_texture_initialize(); // do an initial draw if (!reset) { glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapBuffers(); } return(TRUE); }
bool wglSwapIntervalEXT(int swapInterval) { /* I really have no idea what the expected return value for success. If it was an int * I would return 0, since it is a bool, I'm going to guess that true is success. */ return !CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, (long*)(&swapInterval)); }
void sys_create_display(int width,int height,int _fullscreen) { fullscreen = _fullscreen; /* Information about the current video settings. */ const SDL_VideoInfo* info = NULL; int vidmode_flags=0, samplingerror = 0; /* First, initialize SDL's video subsystem. */ #ifdef USE_SOUND if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0 ) { error_print("Video or Audio initialization failed: %s",SDL_GetError()); #else if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 ) { error_print("Video initialization failed: %s",SDL_GetError()); #endif sys_exit(1); } sdl_on = 1 ; /* Let's get some video information. */ info = SDL_GetVideoInfo( ); if( !info ) { /* This should probably never happen. */ error_print("Video query failed: %s",SDL_GetError()); sys_exit(1); } vidmode_bpp = info->vfmt->BitsPerPixel; /* * Now, we want to setup our requested * window attributes for our OpenGL window. * We want *at least* 5 bits of red, green * and blue. We also want at least a 16-bit * depth buffer. * * The last thing we do is request a VMfloat * buffered window. '1' turns on VMfloat * buffering, '0' turns it off. * * Note that we do not use SDL_DOUBLEBUF in * the flags to SDL_SetVideoMode. That does * not affect the GL attribute state, only * the standard 2D blitting setup. */ 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 ); if (SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ) <0) { fprintf(stderr, "SDL_GL_DOUBLEBUFFER error: %s\n", SDL_GetError()); options_vsync = 0; } else { #ifdef __APPLE__ const GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif //compile without errors, if SDL is < Version 1.2.10 at compile time // on windows with patchlevel 15 only, rest of the world with higher 9 #ifdef USE_WIN #define CHECK_LEVEL 14 #else #define CHECK_LEVEL 9 #endif #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL > CHECK_LEVEL // The next works only with fsaa options off!!! and not stable on win Patchlevel < 15 #ifndef USE_WIN if(!options_fsaa_value) { if(SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ) < 0 ) { fprintf( stderr, "Unable to guarantee accelerated visual with libSDL < 1.2.10\n"); } } #endif if(vsync_supported()) { if(options_vsync) { if (SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1) < 0) { // since SDL v1.2.10 fprintf(stderr, "SDL_GL_SWAP_CONTROL error: %s\n", SDL_GetError()); options_vsync = 0; } } } else { fprintf(stderr,"SDL-System without control of vsync. Scrolling may stutter\n"); } #endif } #ifndef WETAB if(options_fsaa_value) { samplingerror = SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1); if(!samplingerror) { samplingerror = SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES,options_fsaa_value); } } if (samplingerror == -1) { #endif options_fsaa_value = 0; fprintf(stderr,"FSAA Multisample not available\n"); #ifndef WETAB } #endif SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL ); /* key repeat caused problem when toggling fullscreen !!! */ vidmode_flags = SDL_OPENGL; if ( info->hw_available ) { vidmode_flags |= SDL_HWSURFACE; vidmode_flags |= SDL_HWPALETTE; /* Store the palette in hardware */ } else { vidmode_flags |= SDL_SWSURFACE; } if ( info->blit_hw ) { /* checks if hardware blits can be done */ vidmode_flags |= SDL_HWACCEL; } #ifndef WETAB if (fullscreen) { vidmode_flags |= SDL_FULLSCREEN; } else { #ifndef __APPLE__ vidmode_flags |= SDL_RESIZABLE; #endif } #else vidmode_flags |= SDL_FULLSCREEN; #endif //Set the window icon SDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"),NULL); #ifndef WETAB if(options_fsaa_value > options_maxfsaa) { options_fsaa_value = options_maxfsaa; } while (vid_surface == NULL) { #endif if((vid_surface=SDL_SetVideoMode( width, height, vidmode_bpp, vidmode_flags )) == NULL) { if(!options_fsaa_value) { error_print("Video mode set failed. Please restart Foobillard++",NULL); sys_exit(1); } #ifndef WETAB fprintf( stderr, "Video mode set failed: %s\nSwitch to other mode\n", SDL_GetError()); if(options_fsaa_value) { options_fsaa_value >>= 1; fprintf(stderr,"FSAA %i\n",options_fsaa_value); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, options_fsaa_value); } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,0); } #endif } #ifndef WETAB }
extern "C" int main(int argcount, char* argvec[]) #endif { #if defined(__native_client__) std::cerr << "Running game_main" << std::endl; chdir("/frogatto"); { char buf[256]; const char* const res = getcwd(buf,sizeof(buf)); std::cerr << "Current working directory: " << res << std::endl; } #endif #ifdef _MSC_VER freopen("CON", "w", stderr); freopen("CON", "w", stdout); #endif #if defined(__APPLE__) && TARGET_OS_MAC chdir([[[NSBundle mainBundle] resourcePath] fileSystemRepresentation]); #endif #ifdef NO_STDERR std::freopen("/dev/null", "w", stderr); std::cerr.sync_with_stdio(true); #endif std::cerr << "Frogatto engine version " << preferences::version() << "\n"; LOG( "After print engine version" ); #if defined(TARGET_BLACKBERRY) chdir("app/native"); std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl; #endif game_logic::init_callable_definitions(); std::string level_cfg = "titlescreen.cfg"; bool unit_tests_only = false, skip_tests = false; bool run_benchmarks = false; std::vector<std::string> benchmarks_list; std::string utility_program; std::vector<std::string> util_args; std::string server = "wesnoth.org"; #if defined(UTILITY_IN_PROC) bool create_utility_in_new_process = false; std::string utility_name; #endif bool is_child_utility = false; const char* profile_output = NULL; std::string profile_output_buf; #if defined(__ANDROID__) //monstartup("libapplication.so"); #endif std::string orig_level_cfg = level_cfg; std::string override_level_cfg = ""; int modules_loaded = 0; std::vector<std::string> argv; for(int n = 1; n < argcount; ++n) { #if defined(UTILITY_IN_PROC) std::string sarg(argvec[n]); if(sarg.compare(0, 15, "--utility-proc=") == 0) { create_utility_in_new_process = true; utility_name = "--utility-child=" + sarg.substr(15); } else { argv.push_back(argvec[n]); } #else argv.push_back(argvec[n]); #endif if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") { //XCode passes these arguments by default when debugging -- make sure they are ignored. argv.resize(argv.size()-2); } } std::cerr << "Build Options:"; for(auto bo : preferences::get_build_options()) { std::cerr << " " << bo; } std::cerr << std::endl; #if defined(UTILITY_IN_PROC) if(create_utility_in_new_process) { argv.push_back(utility_name); #if defined(_MSC_VER) // app name is ignored for windows, we get windows to tell us. is_child_utility = create_utility_process("", argv); #else is_child_utility = create_utility_process(argvec[0], argv); #endif if(!is_child_utility) { argv.pop_back(); } #if defined(_MSC_VER) atexit(terminate_utility_process); #endif } #endif if(sys::file_exists("./master-config.cfg")) { std::cerr << "LOADING CONFIGURATION FROM master-config.cfg" << std::endl; variant cfg = json::parse_from_file("./master-config.cfg"); if(cfg.is_map()) { if( cfg["id"].is_null() == false) { std::cerr << "SETTING MODULE PATH FROM master-config.cfg: " << cfg["id"].as_string() << std::endl; preferences::set_preferences_path_from_module(cfg["id"].as_string()); //XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string()); } if(cfg["arguments"].is_null() == false) { std::vector<std::string> additional_args = cfg["arguments"].as_list_string(); argv.insert(argv.begin(), additional_args.begin(), additional_args.end()); std::cerr << "ADDING ARGUMENTS FROM master-config.cfg:"; for(size_t n = 0; n < cfg["arguments"].num_elements(); ++n) { std::cerr << " " << cfg["arguments"][n].as_string(); } std::cerr << std::endl; } } } stats::record_program_args(argv); for(size_t n = 0; n < argv.size(); ++n) { const int argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } if(arg_name == "--module") { if(load_module(arg_value, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n"; return -1; } ++modules_loaded; } else if(arg == "--tests") { unit_tests_only = true; } } if(modules_loaded == 0 && !unit_tests_only) { if(load_module(DEFAULT_MODULE, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n"; return -1; } } preferences::load_preferences(); LOG( "After load_preferences()" ); // load difficulty settings after module, before rest of args. difficulty::manager(); for(size_t n = 0; n < argv.size(); ++n) { const size_t argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } std::cerr << "ARGS: " << arg << std::endl; if(arg.substr(0,4) == "-psn") { // ignore. } else if(arg_name == "--module") { // ignore already processed. } else if(arg_name == "--profile" || arg == "--profile") { profile_output_buf = arg_value; profile_output = profile_output_buf.c_str(); } else if(arg_name == "--utility" || arg_name == "--utility-child") { if(arg_name == "--utility-child") { is_child_utility = true; } utility_program = arg_value; for(++n; n < argc; ++n) { const std::string arg(argv[n]); util_args.push_back(arg); } break; } else if(arg == "--benchmarks") { run_benchmarks = true; } else if(arg_name == "--benchmarks") { run_benchmarks = true; benchmarks_list = util::split(arg_value); } else if(arg == "--tests") { // ignore as already processed. } else if(arg == "--no-tests") { skip_tests = true; } else if(arg_name == "--width") { std::string w(arg_value); preferences::set_actual_screen_width(boost::lexical_cast<int>(w)); } else if(arg == "--width" && n+1 < argc) { std::string w(argv[++n]); preferences::set_actual_screen_width(boost::lexical_cast<int>(w)); } else if(arg_name == "--height") { std::string h(arg_value); preferences::set_actual_screen_height(boost::lexical_cast<int>(h)); } else if(arg == "--height" && n+1 < argc) { std::string h(argv[++n]); preferences::set_actual_screen_height(boost::lexical_cast<int>(h)); } else if(arg_name == "--level") { override_level_cfg = arg_value; } else if(arg == "--level" && n+1 < argc) { override_level_cfg = argv[++n]; } else if(arg_name == "--host") { server = arg_value; } else if(arg == "--host" && n+1 < argc) { server = argv[++n]; } else if(arg == "--compiled") { preferences::set_load_compiled(true); #ifndef NO_EDITOR } else if(arg == "--edit") { preferences::set_edit_on_start(true); #endif } else if(arg == "--no-compiled") { preferences::set_load_compiled(false); #if defined(TARGET_PANDORA) } else if(arg == "--no-fbo") { preferences::set_fbo(false); } else if(arg == "--no-bequ") { preferences::set_bequ(false); #endif } else if(arg == "--help" || arg == "-h") { print_help(std::string(argvec[0])); return 0; } else { const bool res = preferences::parse_arg(argv[n].c_str()); if(!res) { std::cerr << "unrecognized arg: '" << arg << "'\n"; return -1; } } } checksum::manager checksum_manager; #ifndef NO_EDITOR sys::filesystem_manager fs_manager; #endif // NO_EDITOR preferences::expand_data_paths(); background_task_pool::manager bg_task_pool_manager; LOG( "After expand_data_paths()" ); std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n'; //make sure that the user data path exists. if(!preferences::setup_preferences_dir()) { std::cerr << "cannot create preferences dir!\n"; } std::cerr << "\n"; const tbs::internal_server_manager internal_server_manager_scope(preferences::internal_tbs_server()); if(utility_program.empty() == false && test::utility_needs_video(utility_program) == false) { #if defined(UTILITY_IN_PROC) if(is_child_utility) { ASSERT_LOG(ipc::semaphore::create(shared_sem_name, 1) != false, "Unable to create shared semaphore: " << errno); std::cerr.sync_with_stdio(true); } #endif test::run_utility(utility_program, util_args); return 0; } #if defined(TARGET_PANDORA) EGL_Open(); #endif #if defined(__ANDROID__) std::freopen("stdout.txt","w",stdout); std::freopen("stderr.txt","w",stderr); std::cerr.sync_with_stdio(true); #endif LOG( "Start of main" ); if(!skip_tests && !test::run_tests()) { return -1; } if(unit_tests_only) { return 0; } // Create the main window. // Initalise SDL and Open GL. main_window = graphics::window_manager_ptr(new graphics::window_manager()); main_window->create_window(preferences::actual_screen_width(), preferences::actual_screen_height()); #ifdef TARGET_OS_HARMATTAN g_type_init(); #endif i18n::init (); LOG( "After i18n::init()" ); #if TARGET_OS_IPHONE || defined(TARGET_BLACKBERRY) || defined(__ANDROID__) //on the iPhone and PlayBook, try to restore the auto-save if it exists if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") { level_cfg = "autosave.cfg"; sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0"); } #endif if(override_level_cfg.empty() != true) { level_cfg = override_level_cfg; orig_level_cfg = level_cfg; } const stats::manager stats_manager; #ifndef NO_EDITOR const external_text_editor::manager editor_manager; #endif // NO_EDITOR #if defined(USE_BOX2D) box2d::manager b2d_manager; #endif const load_level_manager load_manager; { //manager scope const font::manager font_manager; const sound::manager sound_manager; #if !defined(__native_client__) const joystick::manager joystick_manager; #endif graphics::texture::manager texture_manager; #ifndef NO_EDITOR editor::manager editor_manager; #endif variant preloads; loading_screen loader; try { variant gui_node = json::parse_from_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg"); gui_section::init(gui_node); loader.draw_and_increment(_("Initializing GUI")); framed_gui_element::init(gui_node); sound::init_music(json::parse_from_file("data/music.cfg")); graphical_font::init_for_locale(i18n::get_locale()); preloads = json::parse_from_file("data/preload.cfg"); int preload_items = preloads["preload"].num_elements(); loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below custom_object::init(); loader.draw_and_increment(_("Initializing custom object functions")); init_custom_object_functions(json::parse_from_file("data/functions.cfg")); loader.draw_and_increment(_("Initializing textures")); loader.load(preloads); loader.draw_and_increment(_("Initializing tiles")); tile_map::init(json::parse_from_file("data/tiles.cfg")); game_logic::formula_object::load_all_classes(); } catch(const json::parse_error& e) { std::cerr << "ERROR PARSING: " << e.error_message() << "\n"; return 0; } loader.draw(_("Loading level")); #if defined(__native_client__) while(1) { } #endif #if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) && !defined(USE_SHADERS) GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif loader.finish_loading(); //look to see if we got any quit events while loading. { SDL_Event event; while(input::sdl_poll_event(&event)) { if(event.type == SDL_QUIT) { return 0; } } } formula_profiler::manager profiler(profile_output); #ifdef USE_SHADERS texture_frame_buffer::init(preferences::actual_screen_width(), preferences::actual_screen_height()); #else texture_frame_buffer::init(); #endif if(run_benchmarks) { if(benchmarks_list.empty() == false) { test::run_benchmarks(&benchmarks_list); } else { test::run_benchmarks(); } return 0; } else if(utility_program.empty() == false && test::utility_needs_video(utility_program) == true) { test::run_utility(utility_program, util_args); return 0; } bool quit = false; while(!quit && !show_title_screen(level_cfg)) { boost::intrusive_ptr<level> lvl(load_level(level_cfg)); #if !defined(__native_client__) //see if we're loading a multiplayer level, in which case we //connect to the server. multiplayer::manager mp_manager(lvl->is_multiplayer()); if(lvl->is_multiplayer()) { multiplayer::setup_networked_game(server); } if(lvl->is_multiplayer()) { last_draw_position() = screen_position(); std::string level_cfg = "waiting-room.cfg"; boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg)); wait_lvl->finish_loading(); wait_lvl->set_multiplayer_slot(0); if(wait_lvl->player()) { wait_lvl->player()->set_current_level(level_cfg); } wait_lvl->set_as_current_level(); level_runner runner(wait_lvl, level_cfg, orig_level_cfg); multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner)); lvl->set_multiplayer_slot(multiplayer::slot()); } #endif last_draw_position() = screen_position(); assert(lvl.get()); if(!lvl->music().empty()) { sound::play_music(lvl->music()); } if(lvl->player() && level_cfg != "autosave.cfg") { lvl->player()->set_current_level(level_cfg); lvl->player()->get_entity().save_game(); } set_scene_title(lvl->title()); try { quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level(); level_cfg = orig_level_cfg; } catch(multiplayer_exception&) { } } level::clear_current_level(); } //end manager scope, make managers destruct before calling SDL_Quit // controls::debug_dump_controls(); #if defined(TARGET_PANDORA) || defined(TARGET_TEGRA) EGL_Destroy(); #endif preferences::save_preferences(); #if !defined(_MSC_VER) && defined(UTILITY_IN_PROC) if(create_utility_in_new_process) { terminate_utility_process(); } #endif std::set<variant*> loading; swap_variants_loading(loading); if(loading.empty() == false) { fprintf(stderr, "Illegal object: %p\n", (void*)(*loading.begin())->as_callable_loading()); ASSERT_LOG(false, "Unresolved unserialized objects: " << loading.size()); } //#ifdef _MSC_VER // ExitProcess(0); //#endif return 0; }
static int set_swap_interval(int enabled) { CGLContextObj ctx = CGLGetCurrentContext(); CGLError err = CGLSetParameter(ctx, kCGLCPSwapInterval, &enabled); return (err == kCGLNoError) ? 0 : -1; }
BOOL LLWindowMacOSX::createContext(int x, int y, int width, int height, int bits, BOOL fullscreen, BOOL disable_vsync) { BOOL glNeedsInit = FALSE; mFullscreen = fullscreen; if (mWindow == NULL) { mWindow = getMainAppWindow(); } if(mContext == NULL) { // Our OpenGL view is already defined within SecondLife.xib. // Get the view instead. mGLView = createOpenGLView(mWindow, mFSAASamples, !disable_vsync); mContext = getCGLContextObj(mGLView); // Since we just created the context, it needs to be set up. glNeedsInit = TRUE; gGLManager.mVRAM = getVramSize(mGLView); } // This sets up our view to recieve text from our non-inline text input window. setupInputWindow(mWindow, mGLView); // Hook up the context to a drawable if(mContext != NULL) { // <FS:CR> Mac OpenGL //U32 err = CGLSetCurrentContext(mContext); CGLError err = CGLSetCurrentContext(mContext); if (err != kCGLNoError) { setupFailure("Can't activate GL rendering context", "Error", OSMB_OK); return FALSE; } } // Disable vertical sync for swap GLint frames_per_swap = 0; if (disable_vsync) { frames_per_swap = 0; } else { frames_per_swap = 1; } CGLSetParameter(mContext, kCGLCPSwapInterval, &frames_per_swap); //enable multi-threaded OpenGL if (sUseMultGL) { CGLError cgl_err; CGLContextObj ctx = CGLGetCurrentContext(); cgl_err = CGLEnable( ctx, kCGLCEMPEngine); if (cgl_err != kCGLNoError ) { LL_DEBUGS("GLInit") << "Multi-threaded OpenGL not available." << LL_ENDL; } else { LL_DEBUGS("GLInit") << "Multi-threaded OpenGL enabled." << LL_ENDL; } } makeFirstResponder(mWindow, mGLView); return TRUE; }
bool OpenGLGraphics::setVideoMode(int w, int h, int bpp, bool fs, bool hwaccel) { logger->log("Setting video mode %dx%d %s", w, h, fs ? "fullscreen" : "windowed"); int displayFlags = SDL_ANYFORMAT | SDL_OPENGL; mWidth = w; mHeight = h; mBpp = bpp; mFullscreen = fs; mHWAccel = hwaccel; if (fs) { displayFlags |= SDL_FULLSCREEN; } else { // Resizing currently not supported on Windows, where it would require // reuploading all textures. #if !defined(_WIN32) displayFlags |= SDL_RESIZABLE; #endif } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (!(mTarget = SDL_SetVideoMode(w, h, bpp, displayFlags))) return false; #ifdef __APPLE__ if (mSync) { const GLint VBL = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); } #endif // Setup OpenGL glViewport(0, 0, w, h); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); int gotDoubleBuffer; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &gotDoubleBuffer); logger->log("Using OpenGL %s double buffering.", (gotDoubleBuffer ? "with" : "without")); char const *glExtensions = (char const *)glGetString(GL_EXTENSIONS); GLint texSize; bool rectTex = strstr(glExtensions, "GL_ARB_texture_rectangle"); bool npotTex = strstr(glExtensions, "GL_ARB_texture_non_power_of_two"); if (rectTex && !npotTex) { Image::mTextureType = GL_TEXTURE_RECTANGLE_ARB; Image::mPowerOfTwoTextures = false; glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &texSize); } else { Image::mTextureType = GL_TEXTURE_2D; Image::mPowerOfTwoTextures = !npotTex; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); } Image::mTextureSize = texSize; logger->log("OpenGL texture size: %d pixels%s", Image::mTextureSize, rectTex ? " (rectangle textures)" : ""); return true; }
extern "C" int main(int argcount, char** argvec) { #ifdef NO_STDERR std::freopen("/dev/null", "w", stderr); std::cerr.sync_with_stdio(true); #endif std::cerr << "Frogatto engine version " << preferences::version() << "\n"; LOG( "After print engine version" ); #if defined(TARGET_BLACKBERRY) chdir("app/native"); std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl; #endif std::string level_cfg = "titlescreen.cfg"; bool unit_tests_only = false, skip_tests = false; bool run_benchmarks = false; std::vector<std::string> benchmarks_list; std::string utility_program; std::vector<std::string> util_args; std::string server = "wesnoth.org"; const char* profile_output = NULL; std::string profile_output_buf; std::string orig_level_cfg = level_cfg; std::string override_level_cfg = ""; int modules_loaded = 0; std::vector<std::string> argv; for(int n = 1; n < argcount; ++n) { argv.push_back(argvec[n]); if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") { //XCode passes these arguments by default when debugging -- make sure they are ignored. argv.resize(argv.size()-2); } } if(sys::file_exists("./master-config.cfg")) { variant cfg = json::parse_from_file("./master-config.cfg"); if(cfg.is_map()) { if( cfg["id"].is_null() == false) { preferences::set_preferences_path_from_module(cfg["id"].as_string()); //XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string()); } if(cfg["arguments"].is_null() == false) { std::vector<std::string> additional_args = cfg["arguments"].as_list_string(); argv.insert(argv.begin(), additional_args.begin(), additional_args.end()); } } } for(int n = 0; n < argv.size(); ++n) { const int argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } if(arg_name == "--module") { if(load_module(arg_value, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n"; return -1; } ++modules_loaded; } } if(modules_loaded == 0) { if(load_module(DEFAULT_MODULE, &argv) != 0) { std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n"; return -1; } } preferences::load_preferences(); LOG( "After load_preferences()" ); // load difficulty settings after module, before rest of args. difficulty::manager(); for(int n = 0; n < argv.size(); ++n) { const int argc = argv.size(); const std::string arg(argv[n]); std::string arg_name, arg_value; std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '='); if(equal != arg.end()) { arg_name = std::string(arg.begin(), equal); arg_value = std::string(equal+1, arg.end()); } if(arg_name == "--module") { // ignore already processed. } else if(arg_name == "--profile" || arg == "--profile") { profile_output_buf = arg_value; profile_output = profile_output_buf.c_str(); } else if(arg_name == "--utility") { utility_program = arg_value; for(++n; n < argc; ++n) { const std::string arg(argv[n]); util_args.push_back(arg); } break; } else if(arg == "--benchmarks") { run_benchmarks = true; } else if(arg_name == "--benchmarks") { run_benchmarks = true; benchmarks_list = util::split(arg_value); } else if(arg == "--tests") { unit_tests_only = true; } else if(arg == "--no-tests") { skip_tests = true; } else if(arg == "--width" && n+1 < argc) { std::string w(argv[++n]); preferences::set_actual_screen_width(boost::lexical_cast<int>(w)); } else if(arg == "--height" && n+1 < argc) { std::string h(argv[++n]); preferences::set_actual_screen_height(boost::lexical_cast<int>(h)); } else if(arg == "--level" && n+1 < argc) { override_level_cfg = argv[++n]; } else if(arg == "--host" && n+1 < argc) { server = argv[++n]; } else if(arg == "--compiled") { preferences::set_load_compiled(true); #ifndef NO_EDITOR } else if(arg == "--edit") { preferences::set_edit_on_start(true); #endif } else if(arg == "--no-compiled") { preferences::set_load_compiled(false); #if defined(TARGET_PANDORA) } else if(arg == "--no-fbo") { preferences::set_fbo(false); } else if(arg == "--no-bequ") { preferences::set_bequ(false); #endif } else if(arg == "--help" || arg == "-h") { print_help(std::string(argvec[0])); return 0; } else { const bool res = preferences::parse_arg(argv[n].c_str()); if(!res) { std::cerr << "unrecognized arg: '" << arg << "'\n"; return -1; } } } checksum::manager checksum_manager; preferences::expand_data_paths(); LOG( "After expand_data_paths()" ); std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n'; //make sure that the user data path exists. if(!preferences::setup_preferences_dir()) { std::cerr << "cannot create preferences dir!\n"; } std::cerr << "\n"; if(utility_program.empty() == false && test::utility_needs_video(utility_program) == false) { test::run_utility(utility_program, util_args); return 0; } #if defined(TARGET_PANDORA) EGL_Open(); #endif #if defined(__ANDROID__) std::freopen("stdout.txt","w",stdout); std::freopen("stderr.txt","w",stderr); std::cerr.sync_with_stdio(true); #endif LOG( "Start of main" ); Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK; #ifdef _WINDOWS sdl_init_flags |= SDL_INIT_TIMER; #endif if(SDL_Init(sdl_init_flags) < 0) { std::cerr << "could not init SDL\n"; return -1; } LOG( "After SDL_Init" ); #ifdef TARGET_OS_HARMATTAN g_type_init(); #endif i18n::init (); LOG( "After i18n::init()" ); // SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1); #if defined(TARGET_OS_IPHONE) || defined(TARGET_BLACKBERRY) || defined(__ANDROID__) //on the iPhone and PlayBook, try to restore the auto-save if it exists if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") { level_cfg = "autosave.cfg"; sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0"); } #endif if(override_level_cfg.empty() != true) { level_cfg = override_level_cfg; orig_level_cfg = level_cfg; } #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR int width, height; iphone_screen_res(&width, &height); preferences::set_actual_screen_width(width); preferences::set_actual_screen_height(height); int multiplier = 2; if (width > 320) { //preferences::set_use_pretty_scaling(true); multiplier = 1; } preferences::set_virtual_screen_width(height*multiplier); preferences::set_virtual_screen_height(width*multiplier); preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d"); SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(), SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); if (windowID == 0) { std::cerr << "Could not create window: " << SDL_GetError() << "\n"; return -1; } // if (SDL_GL_CreateContext(windowID) == 0) { // std::cerr << "Could not create GL context: " << SDL_GetError() << "\n"; // return -1; // } if (SDL_CreateRenderer(windowID, -1, 0) != 0) { std::cerr << "Could not create renderer\n"; return -1; } #else #ifdef TARGET_OS_HARMATTAN SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } preferences::init_oes(); SDL_ShowCursor(0); #else #ifndef __APPLE__ graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png"); if(!wm_icon.null()) { SDL_WM_SetIcon(wm_icon, NULL); } #endif #if defined(TARGET_PANDORA) if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } EGL_Init(); preferences::init_oes(); #elif defined(TARGET_TEGRA) //if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) { if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } EGL_Init(); preferences::init_oes(); #elif defined(TARGET_BLACKBERRY) if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) { std::cerr << "could not set video mode\n"; return -1; } preferences::init_oes(); #elif defined(__ANDROID__) SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL); if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) { preferences::set_actual_screen_width(r[0]->w); preferences::set_actual_screen_height(r[0]->h); if(r[0]->w < 640) { preferences::set_virtual_screen_width(r[0]->w*2); preferences::set_virtual_screen_height(r[0]->h*2); } else { preferences::set_virtual_screen_width(r[0]->w); preferences::set_virtual_screen_height(r[0]->h); } preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med"); } if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN|SDL_OPENGL) == NULL) { std::cerr << "could not set video mode\n"; return -1; } #else if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) { std::cerr << "could not set video mode\n"; return -1; } #endif #endif #endif // srand(time(NULL)); const stats::manager stats_manager; #ifndef NO_EDITOR const external_text_editor::manager editor_manager; #endif // NO_EDITOR std::cerr << "\n" << "OpenGL vendor: " << reinterpret_cast<const char *>(glGetString(GL_VENDOR)) << "\n" << "OpenGL version: " << reinterpret_cast<const char *>(glGetString(GL_VERSION)) << "\n" << "OpenGL extensions: " << reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)) << "\n" << "\n"; glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); SDL_WM_SetCaption(module::get_module_pretty_name().c_str(), module::get_module_pretty_name().c_str()); std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n"; const load_level_manager load_manager; { //manager scope const font::manager font_manager; const sound::manager sound_manager; const joystick::manager joystick_manager; #if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR const SDL_Surface* fb = SDL_GetVideoSurface(); if(fb == NULL) { return 0; } #endif graphics::texture::manager texture_manager; #ifndef NO_EDITOR editor::manager editor_manager; #endif variant preloads; loading_screen loader; try { sound::init_music(json::parse_from_file(module::map_file("data/music.cfg"))); std::string filename = "data/fonts." + i18n::get_locale() + ".cfg"; if (!sys::file_exists(filename)) filename = "data/fonts.cfg"; graphical_font::init(json::parse_from_file(module::map_file(filename))); preloads = json::parse_from_file(module::map_file("data/preload.cfg")); int preload_items = preloads["preload"].num_elements(); loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below custom_object::init(); loader.draw_and_increment(_("Initializing custom object functions")); init_custom_object_functions(json::parse_from_file(module::map_file("data/functions.cfg"))); loader.draw_and_increment(_("Initializing textures")); loader.load(preloads); loader.draw_and_increment(_("Initializing tiles")); tile_map::init(json::parse_from_file(module::map_file("data/tiles.cfg"))); loader.draw_and_increment(_("Initializing GUI")); variant gui_node = json::parse_from_file(module::map_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg")); gui_section::init(gui_node); loader.draw_and_increment(_("Initializing GUI")); framed_gui_element::init(gui_node); } catch(const json::parse_error& e) { std::cerr << "ERROR PARSING: " << e.error_message() << "\n"; return 0; } loader.draw(_("Loading level")); if(!skip_tests && !test::run_tests()) { return -1; } if(unit_tests_only) { return 0; } #if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) GLint swapInterval = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval); #endif #ifndef SDL_VIDEO_OPENGL_ES GLenum glew_status = glewInit(); ASSERT_EQ(glew_status, GLEW_OK); #endif loader.finish_loading(); //look to see if we got any quit events while loading. { SDL_Event event; while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { return 0; } } } formula_profiler::manager profiler(profile_output); texture_frame_buffer::init(); if(run_benchmarks) { if(benchmarks_list.empty() == false) { test::run_benchmarks(&benchmarks_list); } else { test::run_benchmarks(); } return 0; } else if(utility_program.empty() == false) { test::run_utility(utility_program, util_args); return 0; } bool quit = false; bool of_initialized = false; while(!quit && !show_title_screen(level_cfg)) { boost::intrusive_ptr<level> lvl(load_level(level_cfg)); #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR if (!of_initialized) { of_init(); of_initialized = true; } #endif //see if we're loading a multiplayer level, in which case we //connect to the server. multiplayer::manager mp_manager(lvl->is_multiplayer()); if(lvl->is_multiplayer()) { multiplayer::setup_networked_game(server); } if(lvl->is_multiplayer()) { last_draw_position() = screen_position(); std::string level_cfg = "waiting-room.cfg"; boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg)); wait_lvl->finish_loading(); wait_lvl->set_multiplayer_slot(0); if(wait_lvl->player()) { wait_lvl->player()->set_current_level(level_cfg); } wait_lvl->set_as_current_level(); level_runner runner(wait_lvl, level_cfg, orig_level_cfg); multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner)); lvl->set_multiplayer_slot(multiplayer::slot()); } last_draw_position() = screen_position(); assert(lvl.get()); if(!lvl->music().empty()) { sound::play_music(lvl->music()); } if(lvl->player() && level_cfg != "autosave.cfg") { lvl->player()->set_current_level(level_cfg); lvl->player()->get_entity().save_game(); } set_scene_title(lvl->title()); try { quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level(); level_cfg = orig_level_cfg; } catch(multiplayer_exception&) { } } level::clear_current_level(); } //end manager scope, make managers destruct before calling SDL_Quit // controls::debug_dump_controls(); #if defined(TARGET_PANDORA) || defined(TARGET_TEGRA) EGL_Destroy(); #endif SDL_Quit(); preferences::save_preferences(); std::cerr << SDL_GetError() << "\n"; #if !defined(TARGET_OS_HARMATTAN) && !defined(TARGET_TEGRA) && !defined(TARGET_BLACKBERRY) && !defined(__ANDROID__) std::cerr << gluErrorString(glGetError()) << "\n"; #endif return 0; }