glm::ivec2 GameWindow::getSize() const { int x, y; SDL_GL_GetDrawableSize(window, &x, &y); return glm::ivec2(x, y); }
static void sdl_pull_events(void *ctx) { platform_ctx *platform = (platform_ctx *)ctx; platform_params *params = platform->params; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEMOTION: params->mx = event.motion.x; params->my = event.motion.y; break; case SDL_MOUSEBUTTONUP: case SDL_MOUSEBUTTONDOWN: if (event.button.state == SDL_PRESSED) params->mkeys |= 1 << (event.button.button - 1); else params->mkeys &= ~(1 << (event.button.button - 1)); break; case SDL_KEYUP: case SDL_KEYDOWN: platform->keys[event.key.keysym.scancode] = event.key.state; break; case SDL_QUIT: platform->done = 1; break; } } SDL_GetWindowSize(platform->window, ¶ms->winWidth, ¶ms->winHeight); SDL_GL_GetDrawableSize(platform->window, ¶ms->width, ¶ms->height); params->time = sdl_get_time(ctx); }
void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplSDL2_UpdateGamepads(); }
static int GLES_UpdateClipRect(SDL_Renderer * renderer) { GLES_RenderData *data = (GLES_RenderData *) renderer->driverdata; if (SDL_CurrentContext != data->context) { /* We'll update the clip rect after we rebind the context */ return 0; } if (renderer->clipping_enabled) { const SDL_Rect *rect = &renderer->clip_rect; data->glEnable(GL_SCISSOR_TEST); if (renderer->target) { data->glScissor(renderer->viewport.x + rect->x, renderer->viewport.y + rect->y, rect->w, rect->h); } else { int w, h; SDL_GL_GetDrawableSize(renderer->window, &w, &h); data->glScissor(renderer->viewport.x + rect->x, h - renderer->viewport.y - rect->y - rect->h, rect->w, rect->h); } } else { data->glDisable(GL_SCISSOR_TEST); } return 0; }
void SDLStage::handleEvent(SDL_Event &event) { switch (event.type) { case SDL_WINDOWEVENT: { switch (event.window.event) { case SDL_WINDOWEVENT_SHOWN: m_isHidden = false; break; case SDL_WINDOWEVENT_HIDDEN: m_isHidden = true; break; case SDL_WINDOWEVENT_SIZE_CHANGED: { int local_width = 0, local_height = 0; SDL_GL_GetDrawableSize(m_pWindow, &local_width, &local_height); if (m_resizeCallback) m_resizeCallback(local_width, local_height); } break; } } break; } if (m_eventListener) m_eventListener(event); }
vec2f WindowSystem::get_render_target_dimensions(WindowHandle wh) { int w,h; auto& data = m_data[wh.value]; SDL_GL_GetDrawableSize((SDL_Window*)data.sdl_window, &w, &h); return vec2f{(float)w,(float)h}; }
void SDLX_GetDrawableSize(SDL_Window *window, int *w, int *h) { #if SDL_VERSION_ATLEAST(2, 0, 1) if (SDL_GetWindowFlags(window) & SDL_WINDOW_OPENGL) return SDL_GL_GetDrawableSize(window, w, h); #endif SDL_GetWindowSize(window, w, h); }
glm::mat4 master_renderer::create_projection_matrix() { int w, h; SDL_GL_GetDrawableSize(SDL_GL_GetCurrentWindow(), &w, &h); // This is certainly easier than the Java version... return glm::perspectiveFov(glm::radians(fov), float(w), float(h), near_plane, far_plane); }
int Window::getDrawableSize(State & state, SDL_Window * window){ Stack * stack = state.stack; int w = 0, h = 0; SDL_GL_GetDrawableSize(window, &w, &h); stack->push<int>(w); stack->push<int>(h); return 2; }
Stage::Stage() { pendingResize = true; smMainStage = this; sdlWindow = gSDLWindow; updateFromConfig(); SDL_GL_GetDrawableSize(sdlWindow, &stageWidth, &stageHeight); noteNativeSize(stageWidth, stageHeight); }
void loop() { SDL_Event event; int i; int status; /* Check for events */ ++frames; while (SDL_PollEvent(&event) && !done) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: for (i = 0; i < state->num_windows; ++i) { if (event.window.windowID == SDL_GetWindowID(state->windows[i])) { int w, h; status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); break; } /* Change view port to the new window dimensions */ SDL_GL_GetDrawableSize(state->windows[i], &w, &h); glViewport(0, 0, w, h); state->window_w = event.window.data1; state->window_h = event.window.data2; /* Update window content */ Render(event.window.data1, event.window.data2, &datas[i]); SDL_GL_SwapWindow(state->windows[i]); break; } } break; } } SDLTest_CommonEvent(state, &event, &done); } if (!done) { for (i = 0; i < state->num_windows; ++i) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } Render(state->window_w, state->window_h, &datas[i]); SDL_GL_SwapWindow(state->windows[i]); } } #ifdef __EMSCRIPTEN__ else { emscripten_cancel_main_loop(); } #endif }
void bbSDLGraphicsGetSettings( BBSDLContext *context, int * width,int * height,int * depth,int * hertz,int * flags) { if( context ){ SDL_GL_GetDrawableSize(context->window, &context->width, &context->height); *width=context->width; *height=context->height; *depth=context->depth; *hertz=context->hertz; *flags=context->flags; } }
void renderer_notify_viewport_resized(Renderer * renderer) { SDL_GL_GetDrawableSize(renderer->window, &renderer->viewport_width, &renderer->viewport_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); double x = renderer->viewport_width/2; double y = renderer->viewport_height/2; glOrtho(-x, x, -y, y, -1.0f, 1.0f); }
void ImGui_ImplSdl_NewFrame(SDL_Window* window) { if (!g_FontTexture) ImGui_ImplSdl_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); if (io.DeltaTime <= 0.0) { // Delta-T should *never* be negative, but there seem to be bugs in SDL_GetTicks // (or the underlying platform implementation) which can lead to this happening. // In that case, just assume 60 FPS. io.DeltaTime = 1.0/60.0; } g_Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent()) int mx, my; Uint32 mouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) else io.MousePos = ImVec2(-1, -1); io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); // Start the frame ImGui::NewFrame(); }
static void video_update_mode_settings(void) { SDL_ShowCursor(false); video_update_vsync(); SDL_GL_GetDrawableSize(video.window, &video.current.width, &video.current.height); video.real.width = video.current.width; video.real.height = video.current.height; video_set_viewport(); video_update_quality(); events_emit(TE_VIDEO_MODE_CHANGED, 0, NULL, NULL); if(video_is_fullscreen() && !config_get_int(CONFIG_FULLSCREEN_DESKTOP)) { video_check_fullscreen_sanity(); } }
void HUD::beginHUD() { if(!g_fontTexture) { std::cout << "Creating devices" << std::endl; createDevices(); } ImGuiIO& io = ImGui::GetIO(); int w, h, display_w, display_h; SDL_GetWindowSize(g_window, &w, &h); SDL_GL_GetDrawableSize(g_window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; io.DeltaTime = (float)(1.0f/60.0f); time = current_time; int mx, my; Uint32 MouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(g_window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); else io.MousePos = ImVec2(-1,-1); io.MouseDown[0] = g_mousePressed[0] || (MouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; io.MouseDown[2] = g_mousePressed[2] || (MouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_mousePressed[0] = g_mousePressed[1] = g_mousePressed[2] = false; io.MouseWheel = g_mouseWheel; g_mouseWheel = 0.0f; SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); ImGui::NewFrame(); { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } }
void LoadTests::invokeSample(int iSampleNum) { int width, height; pCurSampleInv = &siSamples[iSampleNum]; pCurSampleInv->sample->pfInitialize( &pCurSampleData, pCurSampleInv->args, szBasePath); SDL_GL_GetDrawableSize(pswMainWindow, &width, & height); setWindowTitle(pCurSampleInv->title); pCurSampleInv->sample->pfResize(pCurSampleData, width, height); }
void Stage::firePendingResizeEvent() { // Fire a resize event. if(smMainStage && pendingResize) { // Fire a resize event. We do this at startup so apps can size them // selves properly before first render. int winWidth, winHeight; SDL_GetWindowSize(gSDLWindow, &winWidth, &winHeight); SDL_GL_GetDrawableSize(gSDLWindow, &winWidth, &winHeight); smMainStage->noteNativeSize(winWidth, winHeight); GFX::Graphics::setNativeSize(winWidth, winHeight); pendingResize = false; } }
Renderer::Renderer(int width, int height, const b2World *world) : width(width), height(height), font(NULL), world(world){ if(TTF_Init()==-1) { printf("TTF_Init: %s\n", TTF_GetError()); exit(2); } font = TTF_OpenFont("opensans.ttf", 16); SDL_Init( SDL_INIT_VIDEO ); if(SDL_GetNumVideoDisplays() > 1){ window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED_DISPLAY(1), // initial x position SDL_WINDOWPOS_CENTERED_DISPLAY(1), // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); }else{ window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED, // initial x position SDL_WINDOWPOS_CENTERED, // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); } if (window == nullptr) { printf("Could not create window: %s\n", SDL_GetError()); SDL_Quit(); return; } //updates the width and height if there's a high DPI and calc other vars afterwards SDL_GL_GetDrawableSize(window, &this->width, &this->height); oneMeterInPX = round(SCALING * this->height); /* one meter is equal to the height */ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //white background SDL_RenderClear(renderer); }
int opengl_clear(SDL_Window *window) { int h, w; SDL_GL_GetDrawableSize(window, &w, &h); glViewport(0, 0, w, h); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //To set up orthogonal 3D view, see http://en.wikipedia.org/wiki/File:Graphical_projection_comparison.png for examples glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); return 0; }
bool Window::onSizeChanged(int width, int height) { if (!window) return false; windowWidth = width; windowHeight = height; SDL_GL_GetDrawableSize(window, &pixelWidth, &pixelHeight); if (graphics.get()) { double scaledw, scaledh; fromPixels((double) pixelWidth, (double) pixelHeight, scaledw, scaledh); graphics->setViewportSize((int) scaledw, (int) scaledh, pixelWidth, pixelHeight); } return true; }
static int GLES_UpdateViewport(SDL_Renderer * renderer) { GLES_RenderData *data = (GLES_RenderData *) renderer->driverdata; if (SDL_CurrentContext != data->context) { /* We'll update the viewport after we rebind the context */ return 0; } if (renderer->target) { data->glViewport(renderer->viewport.x, renderer->viewport.y, renderer->viewport.w, renderer->viewport.h); } else { int w, h; SDL_GL_GetDrawableSize(renderer->window, &w, &h); data->glViewport(renderer->viewport.x, (h - renderer->viewport.y - renderer->viewport.h), renderer->viewport.w, renderer->viewport.h); } data->glMatrixMode(GL_PROJECTION); data->glLoadIdentity(); if (renderer->viewport.w && renderer->viewport.h) { if (renderer->target) { data->glOrthof((GLfloat) 0, (GLfloat) renderer->viewport.w, (GLfloat) 0, (GLfloat) renderer->viewport.h, 0.0, 1.0); } else { data->glOrthof((GLfloat) 0, (GLfloat) renderer->viewport.w, (GLfloat) renderer->viewport.h, (GLfloat) 0, 0.0, 1.0); } } data->glMatrixMode(GL_MODELVIEW); return 0; }
void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt()); // Font atlas needs to be built, call renderer _NewFrame() function e.g. ImGui_ImplOpenGL3_NewFrame() // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); }
void arcball_create(SDL_Window* window, Vec4f eye, Vec4f target, float z_near, float z_far, struct Arcball* arcball) { int32_t width,height; sdl2_debug( SDL_GL_GetDrawableSize(window, &width, &height) ); // - if the user specifies an eye and target so that we are looking along the y-axis (like 0,1,0 and 0,0,0), // then we just adjust the eye a tiny bit upwards to prevent a black screen because the up_axis used in // arcball_event is the y axis, and two parallel axis have no cross product and things become 0 and everything // gets messy, so just add FLOAT_EPSILON to the z coord and be done with it if( eye[0] == target[0] && eye[2] == target[2] ) { bool assert_test = eye[1] != target[1]; log_assert( assert_test == true ); eye[2] += CUTE_EPSILON; } if( z_near < 0.01f ) { log_warn(__FILE__, __LINE__, "you are trying to create a camera with a very small z_near value, " "this would cause problems when rendering vbomeshes with a z_offset, " "this function (arcball_create) will clamp the z_near value to 0.01f\n"); z_near = 0.01f; } camera_create(width, height, CAMERA_PERSPECTIVE, &arcball->camera); float top = (z_near/width) * height/2.0f; float bottom = -top; camera_set_frustum(&arcball->camera, -z_near/2.0f, z_near/2.0f, bottom, top, z_near, z_far); vec_copy4f(eye, arcball->camera.pivot.position); arcball->flipped = pivot_lookat(&arcball->camera.pivot, target); arcball->rotate_button = INPUT_MOUSE_ARCBALL_ROTATE; arcball->translate_button = INPUT_MOUSE_ARCBALL_TRANSLATE; arcball->translate_factor = 500.0f; arcball->zoom_factor = 10.0f; vec_copy4f(target, arcball->target); }
int main(int argc, char *argv[]) { int fsaa, accel; int value; int i; SDL_DisplayMode mode; Uint32 then, now; int status; shader_data *data; /* Initialize parameters */ fsaa = 0; accel = 0; /* Initialize test framework */ state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO); if (!state) { return 1; } for (i = 1; i < argc;) { int consumed; consumed = SDLTest_CommonArg(state, i); if (consumed == 0) { if (SDL_strcasecmp(argv[i], "--fsaa") == 0) { ++fsaa; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--accel") == 0) { ++accel; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) { i++; if (!argv[i]) { consumed = -1; } else { depth = SDL_atoi(argv[i]); consumed = 1; } } else { consumed = -1; } } if (consumed < 0) { SDL_Log ("Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0], SDLTest_CommonUsage(state)); quit(1); } i += consumed; } /* Set OpenGL parameters */ state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS; state->gl_red_size = 5; state->gl_green_size = 5; state->gl_blue_size = 5; state->gl_depth_size = depth; state->gl_major_version = 2; state->gl_minor_version = 0; state->gl_profile_mask = SDL_GL_CONTEXT_PROFILE_ES; if (fsaa) { state->gl_multisamplebuffers=1; state->gl_multisamplesamples=fsaa; } if (accel) { state->gl_accelerated=1; } if (!SDLTest_CommonInit(state)) { quit(2); return 0; } context = (SDL_GLContext *)SDL_calloc(state->num_windows, sizeof(context)); if (context == NULL) { SDL_Log("Out of memory!\n"); quit(2); } /* Create OpenGL ES contexts */ for (i = 0; i < state->num_windows; i++) { context[i] = SDL_GL_CreateContext(state->windows[i]); if (!context[i]) { SDL_Log("SDL_GL_CreateContext(): %s\n", SDL_GetError()); quit(2); } } /* Important: call this *after* creating the context */ if (LoadContext(&ctx) < 0) { SDL_Log("Could not load GLES2 functions\n"); quit(2); return 0; } /* from here on out, it should be ok to call gles 2.0 routines */ if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } SDL_Log("first call address is %llx data is %lx\n",(long long)(&glGetString),GL_VENDOR); const char *test = ctx.glGetString(GL_VENDOR); if (test) { SDL_Log("we got %s\n",test); } else { SDL_Log("we got a null.\n"); quit(2); } SDL_Log("try again call address is %lx\n",(long long)(&glGetString)); SDL_Log("first ctx address is %llx data is %lx ind %llx\n",(long long)(ctx.glGetString),GL_VENDOR,((long long *)(ctx.glGetString))[0] ); {const char *test = glGetString(GL_VENDOR); if (test) { SDL_Log("we got %s\n",test); } else { SDL_Log("we got a null.\n"); quit(2); } } SDL_GetCurrentDisplayMode(0, &mode); SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format)); SDL_Log("\n"); SDL_Log("Vendor : %s\n", glGetString(GL_VENDOR)); SDL_Log("Renderer : %s\n", glGetString(GL_RENDERER)); SDL_Log("Version : %s\n", glGetString(GL_VERSION)); SDL_Log("Extensions : %s\n", glGetString(GL_EXTENSIONS)); SDL_Log("\n"); status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value); if (!status) { SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value); } else { SDL_Log( "Failed to get SDL_GL_RED_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value); if (!status) { SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value); } else { SDL_Log( "Failed to get SDL_GL_GREEN_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value); if (!status) { SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value); } else { SDL_Log( "Failed to get SDL_GL_BLUE_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value); if (!status) { SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value); } else { SDL_Log( "Failed to get SDL_GL_DEPTH_SIZE: %s\n", SDL_GetError()); } if (fsaa) { status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value); if (!status) { SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value); } else { SDL_Log( "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value); if (!status) { SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value); } else { SDL_Log( "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n", SDL_GetError()); } } if (accel) { status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value); if (!status) { SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value); } else { SDL_Log( "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n", SDL_GetError()); } } datas = (shader_data *)SDL_calloc(state->num_windows, sizeof(shader_data)); /* Set rendering settings for each context */ for (i = 0; i < state->num_windows; ++i) { int w, h; status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } SDL_GL_GetDrawableSize(state->windows[i], &w, &h); glViewport(0, 0, w, h); data = &datas[i]; data->angle_x = 0; data->angle_y = 0; data->angle_z = 0; /* Shader Initialization */ process_shader(&data->shader_vert, _shader_vert_src, GL_VERTEX_SHADER); process_shader(&data->shader_frag, _shader_frag_src, GL_FRAGMENT_SHADER); /* Create shader_program (ready to attach shaders) */ data->shader_program = GL_CHECK(glCreateProgram()); /* Attach shaders and link shader_program */ GL_CHECK(glAttachShader(data->shader_program, data->shader_vert)); GL_CHECK(glAttachShader(data->shader_program, data->shader_frag)); GL_CHECK(glLinkProgram(data->shader_program)); /* Get attribute locations of non-fixed attributes like color and texture coordinates. */ data->attr_position = GL_CHECK(glGetAttribLocation(data->shader_program, "av4position")); data->attr_color = GL_CHECK(glGetAttribLocation(data->shader_program, "av3color")); /* Get uniform locations */ data->attr_mvp = GL_CHECK(glGetUniformLocation(data->shader_program, "mvp")); GL_CHECK(glUseProgram(data->shader_program)); /* Enable attributes for position, color and texture coordinates etc. */ GL_CHECK(glEnableVertexAttribArray(data->attr_position)); GL_CHECK(glEnableVertexAttribArray(data->attr_color)); /* Populate attributes for position, color and texture coordinates etc. */ GL_CHECK(glVertexAttribPointer(data->attr_position, 3, GL_FLOAT, GL_FALSE, 0, _vertices)); GL_CHECK(glVertexAttribPointer(data->attr_color, 3, GL_FLOAT, GL_FALSE, 0, _colors)); GL_CHECK(glEnable(GL_CULL_FACE)); GL_CHECK(glEnable(GL_DEPTH_TEST)); } /* Main render loop */ frames = 0; then = SDL_GetTicks(); done = 0; #ifdef __EMSCRIPTEN__ emscripten_set_main_loop(loop, 0, 1); #else while (!done) { loop(); } #endif /* Print out some timing information */ now = SDL_GetTicks(); if (now > then) { SDL_Log("%2.2f frames per second\n", ((double) frames * 1000) / (now - then)); } #if !defined(__ANDROID__) && !defined(__NACL__) quit(0); #endif return 0; }
// Constructor and destructor c_video_screen::c_video_screen( uint id, const std::string& name, const std::string& color, int view_cols, int view_rows, int pos_x, int pos_y, int width, int height, bool fullscreen ) : // Info m_id(id), m_name(name), m_color(color), // View m_view_cols(view_cols), m_view_rows(view_rows), // Window m_window_pos_x(pos_x), m_window_pos_y(pos_y), m_window_width(width), m_window_height(height), m_window_fullscreen(fullscreen), // Timing m_time(0) { // Debug std::cout << boost::format("Screen (%s): id=%d, pos_x=%d, pos_y=%d, width=%d, height=%d, fullscreen=%s") % m_name % m_id % m_window_pos_x % m_window_pos_y % m_window_width % m_window_height % std::string(m_window_fullscreen ? "true" : "false") << std::endl; // SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) throw c_exception("Screen: Failed to initalize SDL!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) }); // Attributes SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // Create window std::string title = std::string("madj - ") + m_name; Uint32 flags = SDL_WINDOW_OPENGL | (m_window_fullscreen ? (SDL_WINDOW_BORDERLESS | SDL_WINDOW_FULLSCREEN_DESKTOP) : SDL_WINDOW_RESIZABLE); m_window = SDL_CreateWindow(title.c_str(), m_window_pos_x, m_window_pos_y, m_window_width, m_window_height, flags); if (m_window == nullptr) throw c_exception("Screen: Failed to create window!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) }); // OpenGL context m_context = c_global::video->context(m_window); gl_init(); // Window settings SDL_DisableScreenSaver(); if (SDL_GL_SetSwapInterval(-1) != 0) { // 0 = immediate, 1 = vertical retrace sync, -1 = late swap tearing //std::cout << "Screen: Failed to set swap interval to late swap tearing!" << std::endl; if (SDL_GL_SetSwapInterval(1) != 0) std::cout << "Screen: Failed to set swap interval to vsync!" << std::endl; } // Display mode SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 }; if (SDL_GetWindowDisplayMode(m_window, &mode) == 0 && mode.refresh_rate != 0) { std::cout << "Screen: refresh_rate = " << mode.refresh_rate << std::endl; } // Rendering area SDL_GL_GetDrawableSize(m_window, &m_window_width, &m_window_height); CEGUI::Rectf area(CEGUI::Vector2f(0.0f, 0.0f), CEGUI::Sizef(m_window_width, m_window_height)); m_context->cegui_renderer().getDefaultRenderTarget().setArea(area); m_context->cegui_renderer().getDefaultRenderTarget().activate(); // Timing m_time = SDL_GetTicks() / 1000.f; // CEGUI m_cegui = std::unique_ptr<c_cegui>(new c_cegui(m_context)); // Scheme CEGUI::SchemeManager::getSingleton().createFromFile("GWEN.scheme"); // Defaults //m_cegui->context().setDefaultFont("OpenSans-8"); m_cegui->context().setDefaultFont("DroidSansMono-10"); //m_cegui->context().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); //m_cegui->context().setDefaultTooltipType("TaharezLook/Tooltip"); // Root window m_cegui_root = reinterpret_cast<CEGUI::DefaultWindow*>(CEGUI::WindowManager::getSingleton().loadLayoutFromFile("screen.layout")); m_cegui_root->setUsingAutoRenderingSurface(false); //m_cegui_client = dynamic_cast<CEGUI::DefaultWindow*>(m_cegui_root->getChildRecursive("TrackerClient")); m_cegui->context().setRootWindow(m_cegui_root); // Error check g_opengl_check(); // Viewport check if ( m_view_rows < 1 || m_view_cols < 1 || m_view_rows > 10 || m_view_cols > 10 ) { throw c_exception("Screen: Wrong number of view columns/rows specified!", { throw_format("name", m_name) }); } }
void Window::glGetDrawableSize( int& w, int& h ) const noexcept { SDL_GL_GetDrawableSize( m_wimpl->window, &w, &h ); }
void Sdl2Application::mainLoop() { #ifndef CORRADE_TARGET_EMSCRIPTEN const UnsignedInt timeBefore = _minimalLoopPeriod ? SDL_GetTicks() : 0; #endif SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: switch(event.window.event) { case SDL_WINDOWEVENT_RESIZED: { #ifndef CORRADE_TARGET_IOS viewportEvent({event.window.data1, event.window.data2}); #else /* On iOS the window event is in points and not pixels, but we need pixels to call glViewport() properly */ Vector2i drawableSize; SDL_GL_GetDrawableSize(_window, &drawableSize.x(), &drawableSize.y()); viewportEvent(drawableSize); #endif _flags |= Flag::Redraw; } break; case SDL_WINDOWEVENT_EXPOSED: _flags |= Flag::Redraw; break; } break; case SDL_KEYDOWN: case SDL_KEYUP: { KeyEvent e(static_cast<KeyEvent::Key>(event.key.keysym.sym), fixedModifiers(event.key.keysym.mod)); event.type == SDL_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { MouseEvent e(static_cast<MouseEvent::Button>(event.button.button), {event.button.x, event.button.y}); event.type == SDL_MOUSEBUTTONDOWN ? mousePressEvent(e) : mouseReleaseEvent(e); } break; case SDL_MOUSEWHEEL: if(event.wheel.y != 0) { MouseEvent e(event.wheel.y > 0 ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, {event.wheel.x, event.wheel.y}); mousePressEvent(e); } break; case SDL_MOUSEMOTION: { MouseMoveEvent e({event.motion.x, event.motion.y}, {event.motion.xrel, event.motion.yrel}, static_cast<MouseMoveEvent::Button>(event.motion.state)); mouseMoveEvent(e); break; } case SDL_QUIT: #ifndef CORRADE_TARGET_EMSCRIPTEN _flags |= Flag::Exit; #else emscripten_cancel_main_loop(); #endif return; } } /* Tick event */ if(!(_flags & Flag::NoTickEvent)) tickEvent(); /* Draw event */ if(_flags & Flag::Redraw) { _flags &= ~Flag::Redraw; drawEvent(); #ifndef CORRADE_TARGET_EMSCRIPTEN /* If VSync is not enabled, delay to prevent CPU hogging (if set) */ if(!(_flags & Flag::VSyncEnabled) && _minimalLoopPeriod) { const UnsignedInt loopTime = SDL_GetTicks() - timeBefore; if(loopTime < _minimalLoopPeriod) SDL_Delay(_minimalLoopPeriod - loopTime); } #endif return; } #ifndef CORRADE_TARGET_EMSCRIPTEN /* If not drawing anything, delay to prevent CPU hogging (if set) */ if(_minimalLoopPeriod) { const UnsignedInt loopTime = SDL_GetTicks() - timeBefore; if(loopTime < _minimalLoopPeriod) SDL_Delay(_minimalLoopPeriod - loopTime); } /* Then, if the tick event doesn't need to be called periodically, wait indefinitely for next input event */ if(_flags & Flag::NoTickEvent) SDL_WaitEvent(nullptr); #endif }
bool Sdl2Application::tryCreateContext(const Configuration& configuration) { CORRADE_ASSERT(_context->version() == Version::None, "Platform::Sdl2Application::tryCreateContext(): context already created", false); /* Enable double buffering and 24bt depth buffer */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); /* Multisampling */ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration.sampleCount() > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration.sampleCount()); #ifndef CORRADE_TARGET_EMSCRIPTEN /* sRGB */ SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, configuration.isSRGBCapable()); #endif /** @todo Remove when Emscripten has proper SDL2 support */ #ifndef CORRADE_TARGET_EMSCRIPTEN /* Set context version, if user-specified */ if(configuration.version() != Version::None) { Int major, minor; std::tie(major, minor) = version(configuration.version()); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); #ifndef MAGNUM_TARGET_GLES SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, configuration.version() >= Version::GL310 ? SDL_GL_CONTEXT_PROFILE_CORE : SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())); /* Request usable version otherwise */ } else { #ifndef MAGNUM_TARGET_GLES /* First try to create core context. This is needed mainly on OS X and Mesa, as support for recent OpenGL versions isn't implemented in compatibility contexts (which are the default). At least GL 3.2 is needed on OSX, at least GL 3.1 is needed on Mesa. Bite the bullet and try 3.1 also elsewhere. */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #ifdef CORRADE_TARGET_APPLE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())|SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); #else /* For ES the major context version is compile-time constant */ #ifdef MAGNUM_TARGET_GLES3 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #elif defined(MAGNUM_TARGET_GLES2) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); #else #error unsupported OpenGL ES version #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif } /* Create window. Hide it by default so we don't have distracting window blinking in case we have to destroy it again right away */ if(!(_window = SDL_CreateWindow( #ifndef CORRADE_TARGET_IOS configuration.title().data(), #else nullptr, #endif SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, configuration.size().x(), configuration.size().y(), SDL_WINDOW_OPENGL|SDL_WINDOW_HIDDEN|Uint32(configuration.windowFlags())))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create window:" << SDL_GetError(); return false; } /* Create context */ _glContext = SDL_GL_CreateContext(_window); #ifndef MAGNUM_TARGET_GLES /* Fall back to (forward compatible) GL 2.1, if version is not user-specified and either core context creation fails or we are on binary NVidia/AMD drivers on Linux/Windows. Instead of creating forward- compatible context with highest available version, they force the version to the one specified, which is completely useless behavior. */ #ifndef CORRADE_TARGET_APPLE constexpr static const char nvidiaVendorString[] = "NVIDIA Corporation"; constexpr static const char amdVendorString[] = "ATI Technologies Inc."; const char* vendorString; #endif if(configuration.version() == Version::None && (!_glContext #ifndef CORRADE_TARGET_APPLE /* Sorry about the UGLY code, HOPEFULLY THERE WON'T BE MORE WORKAROUNDS */ || (vendorString = reinterpret_cast<const char*>(glGetString(GL_VENDOR)), (std::strncmp(vendorString, nvidiaVendorString, sizeof(nvidiaVendorString)) == 0 || std::strncmp(vendorString, amdVendorString, sizeof(amdVendorString)) == 0) && !_context->isDriverWorkaroundDisabled("amd-nv-no-forward-compatible-core-context")) #endif )) { /* Don't print any warning when doing the NV workaround, because the bug will be there probably forever */ if(!_glContext) Warning() << "Platform::Sdl2Application::tryCreateContext(): cannot create core context:" << SDL_GetError() << "(falling back to compatibility context)"; else SDL_GL_DeleteContext(_glContext); SDL_DestroyWindow(_window); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, int(configuration.flags())); if(!(_window = SDL_CreateWindow(configuration.title().data(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, configuration.size().x(), configuration.size().y(), SDL_WINDOW_OPENGL|SDL_WINDOW_HIDDEN|Uint32(configuration.windowFlags())))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create window:" << SDL_GetError(); return false; } /* Create compatibility context */ _glContext = SDL_GL_CreateContext(_window); } #endif /* Cannot create context (or fallback compatibility context on desktop) */ if(!_glContext) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create context:" << SDL_GetError(); SDL_DestroyWindow(_window); _window = nullptr; return false; } #ifdef CORRADE_TARGET_IOS /* iOS has zero initial GL_VIEWPORT size, get drawable size and put it back in so all other code can assume that the viewport is set to sane values. Fortunately on iOS we also don't have to load any function pointers so it's safe to do the glViewport() call as it is linked statically. */ Vector2i drawableSize; SDL_GL_GetDrawableSize(_window, &drawableSize.x(), &drawableSize.y()); glViewport(0, 0, drawableSize.x(), drawableSize.y()); #endif #else /* Emscripten-specific initialization */ if(!(_glContext = SDL_SetVideoMode(configuration.size().x(), configuration.size().y(), 24, SDL_OPENGL|SDL_HWSURFACE|SDL_DOUBLEBUF))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create context:" << SDL_GetError(); return false; } #endif /* Destroy everything also when the Magnum context creation fails */ if(!_context->tryCreate()) { SDL_GL_DeleteContext(_glContext); SDL_DestroyWindow(_window); _window = nullptr; return false; } #ifndef CORRADE_TARGET_EMSCRIPTEN /* Show the window once we are sure that everything is okay */ if(!(configuration.windowFlags() & Configuration::WindowFlag::Hidden)) SDL_ShowWindow(_window); #endif /* Return true if the initialization succeeds */ return true; }
static int GLES_GetOutputSize(SDL_Renderer * renderer, int *w, int *h) { SDL_GL_GetDrawableSize(renderer->window, w, h); return 0; }