SDL_bool WatchGameController(SDL_GameController * gamecontroller) { /* This is indexed by SDL_GameControllerButton. */ static const struct { int x; int y; } button_positions[] = { {387, 167}, /* A */ {431, 132}, /* B */ {342, 132}, /* X */ {389, 101}, /* Y */ {174, 132}, /* BACK */ {233, 132}, /* GUIDE */ {289, 132}, /* START */ {75, 154}, /* LEFTSTICK */ {305, 230}, /* RIGHTSTICK */ {77, 40}, /* LEFTSHOULDER */ {396, 36}, /* RIGHTSHOULDER */ {154, 188}, /* DPAD_UP */ {154, 249}, /* DPAD_DOWN */ {116, 217}, /* DPAD_LEFT */ {186, 217}, /* DPAD_RIGHT */ }; /* This is indexed by SDL_GameControllerAxis. */ static const struct { int x; int y; double angle; } axis_positions[] = { {75, 154, 0.0}, /* LEFTX */ {75, 154, 90.0}, /* LEFTY */ {305, 230, 0.0}, /* RIGHTX */ {305, 230, 90.0}, /* RIGHTY */ {91, 0, 90.0}, /* TRIGGERLEFT */ {375, 0, 90.0}, /* TRIGGERRIGHT */ }; const char *name = SDL_GameControllerName(gamecontroller); const char *basetitle = "Game Controller Test: "; const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1; char *title = (char *)SDL_malloc(titlelen); SDL_Texture *background, *button, *axis; SDL_Window *window = NULL; SDL_Renderer *screen = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE; SDL_Event event; int i; if (title) { SDL_snprintf(title, titlelen, "%s%s", basetitle, name); } /* Create a window to display controller state */ window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); if (!background || !button || !axis) { SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetTextureColorMod(button, 10, 255, 21); SDL_SetTextureColorMod(axis, 10, 255, 21); /* !!! FIXME: */ /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/ /* Print info about the controller we are watching */ SDL_Log("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ while (!done) { /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderCopy(screen, background, NULL, NULL); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym != SDLK_ESCAPE) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } /* Update visual controller state */ for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) { if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) { const SDL_Rect dst = { button_positions[i].x, button_positions[i].y, 50, 50 }; SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, 0); } } for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) { const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */ const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i)); if (value < -deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0); } else if (value > deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle + 180.0; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0); } } SDL_RenderPresent(screen); if (!SDL_GameControllerGetAttached(gamecontroller)) { done = SDL_TRUE; retval = SDL_TRUE; /* keep going, wait for reattach. */ } } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return retval; }
static int GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder) { int perChannelColorBits; int colorBits, depthBits, stencilBits; int samples; int i = 0; SDL_Surface *icon = NULL; SDL_DisplayMode desktopMode; int display = 0; int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_GRABBED; #ifndef FEATURE_RENDERER_GLES GLenum glewResult; #endif Ren_Print("Initializing OpenGL display\n"); if (r_allowResize->integer && !fullscreen) { flags |= SDL_WINDOW_RESIZABLE; } icon = SDL_CreateRGBSurfaceFrom( (void *)CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); // If a window exists, note its display index if (main_window != NULL) { display = SDL_GetWindowDisplayIndex(main_window); } if (SDL_GetDesktopDisplayMode(display, &desktopMode) == 0) { displayAspect = (float)desktopMode.w / (float)desktopMode.h; Ren_Print("Estimated display aspect: %.3f\n", displayAspect); } else { Com_Memset(&desktopMode, 0, sizeof(SDL_DisplayMode)); Ren_Print("Cannot estimate display aspect, assuming 1.333\n"); } Ren_Print("...setting mode %d: ", mode); if (mode == -2) { // use desktop video resolution if (desktopMode.h > 0) { glConfig.vidWidth = desktopMode.w; glConfig.vidHeight = desktopMode.h; } else { glConfig.vidWidth = 640; glConfig.vidHeight = 480; Ren_Print("Cannot determine display resolution, assuming 640x480\n"); } glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; } else if (!R_GetModeInfo(&glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode)) { Ren_Print("invalid mode\n"); return RSERR_INVALID_MODE; } Ren_Print("%dx%d\n", glConfig.vidWidth, glConfig.vidHeight); // Center window if (r_centerWindow->integer && !fullscreen) { x = (desktopMode.w / 2) - (glConfig.vidWidth / 2); y = (desktopMode.h / 2) - (glConfig.vidHeight / 2); } // Destroy existing state if it exists if (SDL_glContext != NULL) { SDL_GL_DeleteContext(SDL_glContext); SDL_glContext = NULL; } if (main_window != NULL) { SDL_GetWindowPosition(main_window, &x, &y); Ren_Developer("Existing window at %dx%d before being destroyed\n", x, y); SDL_DestroyWindow(main_window); main_window = NULL; } if (fullscreen) { if (r_mode->integer == -2) { flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } else { flags |= SDL_WINDOW_FULLSCREEN; } glConfig.isFullscreen = qtrue; } else { if (noborder) { flags |= SDL_WINDOW_BORDERLESS; } glConfig.isFullscreen = qfalse; } colorBits = r_colorbits->value; if ((!colorBits) || (colorBits >= 32)) { colorBits = 24; } if (!r_depthbits->value) { depthBits = 24; } else { depthBits = r_depthbits->value; } stencilBits = r_stencilbits->value; samples = r_ext_multisample->value; for (i = 0; i < 16; i++) { int testColorBits, testDepthBits, testStencilBits; // 0 - default // 1 - minus colorBits // 2 - minus depthBits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2: if (colorBits == 24) { colorBits = 16; } break; case 1: if (depthBits == 32) { depthBits = 24; } else if (depthBits == 24) { depthBits = 16; } else if (depthBits == 16) { depthBits = 8; } case 3: // fall through if (stencilBits == 24) { stencilBits = 16; } else if (stencilBits == 16) { stencilBits = 8; } } } testColorBits = colorBits; testDepthBits = depthBits; testStencilBits = stencilBits; if ((i % 4) == 3) // reduce colorbits { if (testColorBits == 24) { testColorBits = 16; } } if ((i % 4) == 2) // reduce depthbits { if (testDepthBits == 24) { testDepthBits = 16; } else if (testDepthBits == 16) { testDepthBits = 8; } } if ((i % 4) == 1) // reduce stencilbits { if (testStencilBits == 24) { testStencilBits = 16; } else if (testStencilBits == 16) { testStencilBits = 8; } else { testStencilBits = 0; } } if (testColorBits == 24) { perChannelColorBits = 8; } else { perChannelColorBits = 4; } #ifdef __sgi // Fix for SGIs grabbing too many bits of color if (perChannelColorBits == 4) { perChannelColorBits = 0; /* Use minimum size for 16-bit color */ } // Need alpha or else SGIs choose 36+ bit RGB mode SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 1); #endif SDL_GL_SetAttribute(SDL_GL_RED_SIZE, perChannelColorBits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, perChannelColorBits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, perChannelColorBits); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, testDepthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, testStencilBits); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples); // SDL2 uses opengl by default, if we want opengl es we need to set this attribute //SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, 1); if (r_stereoEnabled->integer) { glConfig.stereoEnabled = qtrue; SDL_GL_SetAttribute(SDL_GL_STEREO, 1); } else { glConfig.stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // If not allowing software GL, demand accelerated if (!r_allowSoftwareGL->integer) { SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); } main_window = SDL_CreateWindow(CLIENT_WINDOW_TITLE, x, y, glConfig.vidWidth, glConfig.vidHeight, flags | SDL_WINDOW_SHOWN); if (!main_window) { Ren_Developer("SDL_CreateWindow failed: %s\n", SDL_GetError()); continue; } //This is disabled since at least now we have no use for this /* if (!Glimp_Create2DRenderer(main_window)) { continue; } */ if (fullscreen) { SDL_DisplayMode mode; switch (testColorBits) { case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; default: Ren_Developer("testColorBits is %d, can't fullscreen\n", testColorBits); continue; } mode.w = glConfig.vidWidth; mode.h = glConfig.vidHeight; mode.refresh_rate = glConfig.displayFrequency = ri.Cvar_VariableIntegerValue("r_displayRefresh"); mode.driverdata = NULL; if (SDL_SetWindowDisplayMode(main_window, &mode) < 0) { Ren_Developer("SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError()); continue; } } SDL_SetWindowIcon(main_window, icon); #if defined(FEATURE_RENDERER2) glewExperimental = GL_TRUE; 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_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); #endif if ((SDL_glContext = SDL_GL_CreateContext(main_window)) == NULL) { Ren_Developer("SDL_GL_CreateContext failed: %s\n", SDL_GetError()); continue; } SDL_GL_MakeCurrent(main_window, SDL_glContext); SDL_GL_SetSwapInterval(r_swapInterval->integer); glConfig.colorBits = testColorBits; glConfig.depthBits = testDepthBits; glConfig.stencilBits = testStencilBits; ri.Printf(PRINT_ALL, "Using %d color bits, %d depth, %d stencil display.\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits); break; } GLimp_DetectAvailableModes(); #if !defined(FEATURE_RENDERER_GLES) glewResult = glewInit(); if (GLEW_OK != glewResult) { // glewInit failed, something is seriously wrong Ren_Fatal("GLW_StartOpenGL() - could not load OpenGL subsystem: %s", glewGetErrorString(glewResult)); } else { Ren_Print("Using GLEW %s\n", glewGetString(GLEW_VERSION)); } #endif if (!GLimp_InitOpenGLContext()) { return RSERR_OLD_GL; } if (!main_window) //|| !main_renderer) { Ren_Print("Couldn't get a visual\n"); return RSERR_INVALID_MODE; } SDL_FreeSurface(icon); return RSERR_OK; }
int main(int argc, char** argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("SDL Practice4", SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, 800,700, SDL_WINDOW_SHOWN); SDL_Renderer* rend = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //创建renderer SDL_RenderClear(rend); //清空rend SDL_Surface* image_surface = SDL_LoadBMP("x.bmp"); SDL_Texture* image_texture = SDL_CreateTextureFromSurface(rend, image_surface); //将surface转换为texture并显示在rend上 SDL_Event event; SDL_Rect pos; pos.x=0; pos.y=0; pos.w=image_surface->w; pos.h=image_surface->h; SDL_Rect image_pos; image_pos.x = 0; image_pos.y = 0; image_pos.w = image_surface->w; image_pos.h = image_surface->h; bool quit=false; bool pressed = false; while(!quit) { while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) quit = true; if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { image_pos.x = event.motion.x - pos.x; image_pos.y = event.motion.y - pos.y; if(image_pos.x>=0 && image_pos.x<=image_pos.w && image_pos.y>0 && image_pos.y<image_pos.h) pressed = true; } } if(pressed && event.type == SDL_MOUSEMOTION) { pos.x = event.motion.x - image_pos.x; pos.y = event.motion.y - image_pos.y; } if(event.type == SDL_MOUSEBUTTONUP) { if(pressed && event.button.button == SDL_BUTTON_LEFT) { pressed = false; } } } SDL_RenderClear(rend); //清空rend SDL_RenderCopy(rend, image_texture, NULL, &pos); //将texture显示到rend上 SDL_Delay(5); SDL_RenderPresent(rend); //显示rend } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int CVideo::setMode(int w, int h, int bits_per_pixel, int flags) { bool reset_zoom = frameBuffer? false: true; mode_changed_ = true; flags = get_flags(flags); if (current_format == SDL_PIXELFORMAT_UNKNOWN) { current_format = SDL_PIXELFORMAT_ARGB8888; } fullScreen = (flags & SDL_WINDOW_FULLSCREEN) != 0; if (window) { SDL_DestroyWindow(window); } if (frameTexture) { SDL_DestroyTexture(frameTexture); } if (renderer) { SDL_DestroyRenderer(renderer); } int x = SDL_WINDOWPOS_UNDEFINED; int y = SDL_WINDOWPOS_UNDEFINED; #if (defined(__APPLE__) && TARGET_OS_IPHONE) if (gui2::twidget::hdpi) { x = y = 0; } #endif window = SDL_CreateWindow(_(game_config::app_msgid.c_str()), x, y, w, h, flags); int ret_w, ret_h; SDL_GetWindowSize(window, &ret_w, &ret_h); renderer = SDL_CreateRenderer(window, -1, 0); #if (defined(__APPLE__) && TARGET_OS_IPHONE) if (gui2::twidget::hdpi) { // Fix Bug! SDL_SetWindowSize(window, w, h); } #endif frameBuffer = SDL_CreateRGBSurface(0, w, h, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); SDL_SetSurfaceBlendMode(frameBuffer, SDL_BLENDMODE_NONE); frameTexture = SDL_CreateTexture(renderer, current_format, SDL_TEXTUREACCESS_STREAMING, w, h); // frameBuffer's refcount should be 1. If not, check SDL_SetVideoMode! // 1 is holded by frameBuffer. if (frameBuffer.get()->refcount != 1) { return 0; } if (frameBuffer != NULL) { image::set_pixel_format(frameBuffer->format); game_config::tiny_gui = frameBuffer->w < 800 * gui2::twidget::hdpi_ratio || frameBuffer->h < 600 * gui2::twidget::hdpi_ratio; if (reset_zoom) { int zoom = preferences::zoom(); display::initial_zoom = zoom; image::set_zoom(display::initial_zoom); } return bits_per_pixel; } else { return 0; } }
int main(){ TempSettings gamesettings; gamesettings.mapw = 10; gamesettings.maph = 6; gamesettings.mapx = 0; gamesettings.mapy = 0; gamesettings.mapmidx = gamesettings.mapw/2.0; gamesettings.mapmidy = gamesettings.maph/2.0; gamesettings.window_width = 1300; gamesettings.window_height = 800; // initialize window, renderer, textures if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return 1; } if (TTF_Init() != 0){ std::cerr << "TTF_Init error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Window* window = SDL_CreateWindow("deathblade_floating", 0, 0, gamesettings.window_width, gamesettings.window_height, SDL_WINDOW_SHOWN); if (window == nullptr){ std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == nullptr){ std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl; SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string resource_path = getResourcePath(""); std::string charfile = resource_path + "initialcharacter.png"; std::string bgfile = resource_path + "initialbackgroundtile.png"; std::string starfile = resource_path + "star.png"; std::string wallfile = resource_path + "wall.png"; SDL_Texture* character_texture = IMG_LoadTexture(renderer, charfile.c_str()); SDL_Texture* bgtile_texture = IMG_LoadTexture(renderer, bgfile.c_str()); SDL_Texture* star_texture = IMG_LoadTexture(renderer, starfile.c_str()); SDL_Texture* wall_texture = IMG_LoadTexture(renderer,wallfile.c_str()); if (character_texture == nullptr || bgtile_texture == nullptr || star_texture == nullptr || wall_texture == nullptr){ std::cerr << "IMG_LoadTexture error: " << SDL_GetError() << std::endl; SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string fontfile = resource_path + "sample.ttf"; TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 15); if (font == NULL){ std::cerr << "TTF_OpenFont error: " << SDL_GetError() << std::endl; } CameraControl camera(&gamesettings); ObjectController objects; DeveloperConsoleClass console(&gamesettings); console.add_controller(&console); console.add_controller(&camera); const double tilew = 0.5; const double tileh = 0.5; double mousex = gamesettings.mapmidx; double mousey = gamesettings.mapmidy; int mousepx = gamesettings.window_width/2; int mousepy = gamesettings.window_height/2; double wallthickness = 0.1; TextureWall bottomwall, topwall, leftwall, rightwall; bottomwall.x = gamesettings.mapw/2; bottomwall.y = gamesettings.maph+wallthickness/2; bottomwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&bottomwall); topwall.x = gamesettings.mapw/2; topwall.y = -wallthickness/2; topwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&topwall); leftwall.x = -wallthickness/2; leftwall.y = gamesettings.maph/2; leftwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&leftwall); rightwall.x = gamesettings.mapw + wallthickness/2; rightwall.y = gamesettings.maph/2; rightwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&rightwall); Player human; human.x = 5; human.y = 5; human.dx = -0.025; human.dy = -0.03; human.setTexture(character_texture, 0.05, 0.05); objects.add_object(&human); // map x [0, 10] // map y [0, 6] // star width 0.256 std::vector<vec2d> star_positions = { vec2d(6,4), vec2d(3,4.1), vec2d(9,0.2), vec2d(1,0.4), vec2d(2,2.5), vec2d(3,2.5), vec2d(9,4.9), vec2d(0.2,5.1), vec2d(4.1,4.1) }; std::vector<double> star_thetas = { 0, 45, 15, 60, 85, 4, 50, 66, 31 }; std::vector<Star*> star_field; for(unsigned int i = 0; i < star_positions.size(); ++i){ Star* newstar = new Star(); newstar->x = star_positions[i].x; newstar->y = star_positions[i].y; newstar->setTexture(star_texture, 0.256, 0.256); if(i < star_thetas.size()) newstar->rotate(star_thetas[i]*3.14159265359/180.0); star_field.push_back(newstar); objects.add_object(star_field[i]); } bool rightmouse_down = false; SDL_Event event; bool quitnow = false; Uint32 fps_lastframe = SDL_GetTicks(); while(!quitnow){ int zoomdirection = 0; while(SDL_PollEvent(&event)){ if (console.is_active()){ if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_BACKSPACE: console.backspace(); break; case SDLK_RETURN: case SDLK_RETURN2: console.enter(); break; case SDLK_UP: console.goback_inhistory(); break; case SDLK_DOWN: console.goforward_inhistory(); break; default: break; } console.render_current_command(renderer); } else if (event.type == SDL_TEXTINPUT && event.text.text[0] != '`'){ console.addinput(event.text.text); console.render_current_command(renderer); } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ if(!console.mouse_grab(true, event.button.x, event.button.y)) camera.mousecontrol_on(); } //if (event.button.button == SDL_BUTTON_RIGHT) } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ console.mouse_grab(false, -1,-1); camera.mousecontrol_off(); } } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; console.handle_mouse(event.motion.xrel, event.motion.yrel); if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); } } else if (event.type == SDL_MOUSEWHEEL){ if(!console.scroll(event.wheel.y, mousepx, mousepy)) zoomdirection += event.wheel.y; } else if (event.type == SDL_QUIT){ quitnow = true; } continue; } // if console is not up if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_ESCAPE: quitnow = true; break; case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_t: if (!camera.is_tracking()) camera.track_object(&(human.x), &(human.y)); else camera.stop_tracking(); break; case SDLK_w: case SDLK_UP: camera.pan_updown(-1); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(-1); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(1); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(1); break; default: break; } } else if (event.type == SDL_KEYUP){ switch(event.key.keysym.sym){ case SDLK_w: case SDLK_UP: camera.pan_updown(0); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(0); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(0); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(0); break; default: break; } } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_on(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = true; human.bound.xclick = camera.xfrompixel(event.button.x,event.button.y,db::Player); human.bound.yclick = camera.yfrompixel(event.button.x,event.button.y,db::Player); human.bound.xdrag = 0; human.bound.ydrag = 0; human.bound.enabled = true; } } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_off(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = false; } } else if (event.type == SDL_MOUSEWHEEL){ zoomdirection += event.wheel.y; } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); if(mousepx <= 1) camera.pan_leftright(-1); else if (mousepx >= (int)gamesettings.window_width-1) camera.pan_leftright(1); else if (mousepx - event.motion.xrel <= 1) camera.pan_leftright(0); else if (mousepx - event.motion.xrel >= (int)gamesettings.window_width-1) camera.pan_leftright(0); if(mousepy <= 1) camera.pan_updown(-1); else if (mousepy >= (int)gamesettings.window_height-1) camera.pan_updown(1); else if (mousepy - event.motion.yrel <= 1) camera.pan_updown(0); else if (mousepy - event.motion.yrel >= (int)gamesettings.window_height-1) camera.pan_updown(0); if(rightmouse_down){ human.bound.xdrag += event.motion.xrel; human.bound.ydrag += event.motion.yrel; } } } else if (event.type == SDL_QUIT){ quitnow = true; } } objects.step_time(); SDL_SetRenderDrawColor(renderer, 0,0,0,255); SDL_RenderClear(renderer); camera.adjust_zoom(zoomdirection, mousex, mousey); for (double x = gamesettings.mapx+tilew/2; x < gamesettings.mapx+gamesettings.mapw+tilew/2; x += tilew){ for (double y = gamesettings.mapy+tileh/2; y < gamesettings.mapy+gamesettings.maph+tileh/2; y += tileh){ SDL_Rect dst = camera.calculate_display_destination(x,y,tilew,tileh,db::Floor); SDL_RenderCopyEx(renderer, bgtile_texture, NULL, &dst, -camera.camyaw*180.0/3.14156033, NULL, SDL_FLIP_NONE); } } objects.drawon(renderer, &camera); if(console.is_active()) console.drawon(renderer); human.bound.drawon(renderer, &camera); Uint32 fps_newframe = SDL_GetTicks(); if((fps_newframe-fps_lastframe) < SCREEN_TICKS_PER_FRAME){ SDL_Delay(SCREEN_TICKS_PER_FRAME - (fps_newframe-fps_lastframe)); } draw_fps(renderer, font, 1.0/(fps_newframe/1000.0 - fps_lastframe/1000.0)); fps_lastframe = fps_newframe; SDL_RenderPresent(renderer); } SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); for(unsigned int i = 0; i < star_field.size(); ++i) delete star_field[i]; return 0; }
PixelDrawer::~PixelDrawer() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); }
std::vector<Landmark> createLandmarks() { std::vector<Landmark> lmks; SDL_Color color_red = {.r = 255, .g = 0, .b = 0, .a = 255 }; SDL_Color color_green = {.r = 0, .g = 255, .b = 0, .a = 255 }; SDL_Color color_blue = {.r = 0, .g = 0, .b = 255, .a = 255 }; SDL_Color color_purple = {.r = 255, .g = 0, .b = 255, .a = 255 }; lmks.push_back( Landmark(300.,300.,color_red)); lmks.push_back( Landmark(124.,478.,color_blue)); // lmks.push_back( Landmark(214.,312.,color_purple)); return lmks; } int main() { if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } SDL_Window *win = SDL_CreateWindow("Robot Program", XSTART, YSTART, WWIDTH, WHEIGHT, SDL_WINDOW_SHOWN); if (win == nullptr){ std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr){ SDL_DestroyWindow(win); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } std::vector<Landmark> landmarks = createLandmarks(); SDL_Color orange {.r=255, .g=165, .b=0, .a=255}; SDL_Color red {.r=255, .g=0, .b=0, .a=255}; SDL_Color gray {.r=128, .g=128, .b=128, .a=255}; Robot robby(200, 200, 0.0, 20, red); // Kalman filter stuff int n = 3; // number of state variables (x,y,phi) int m = 3; // number of measurements (landmark x, y, index) // Best guess of initial states Eigen::VectorXf x0(n); //[x, y, phi] x0 << 200., 200., 0.0; Robot robby_estimate(x0(0), x0(1), x0(2), 18, gray); // control vector: Eigen::VectorXf control(2); // [v, omega] Eigen::MatrixXf A(n, n); // System dynamics matrix Eigen::MatrixXf C(m, n); // Output matrix Eigen::MatrixXf Q(n, n); // Process noise covariance Eigen::MatrixXf R(m, m); // Measurement noise covariance Eigen::MatrixXf covariance(n, n); // Estimate error covariance // Reasonable covariance matrices covariance << 5., .0, .0, .0, 5., .0, .0, .0, 5.; R << 1.0, 0., 0., 0., 1.0, 0., 0., 0., 0.1; Q << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1; KalmanFilter kf(DT, A, C, Q, R, covariance); float t0 = 0.0; kf.init(t0, x0); // rendering loop int i = 0; while (i < 10000) { //First clear the renderer SDL_RenderClear(ren); //Draw the texture SDL_SetRenderDrawColor(ren, 200, 200, 255, 255); SDL_RenderClear(ren); // fill the scene with white SDL_SetRenderDrawColor(ren, 0, 0, 0, 255); // update renderer SDL_RenderPresent(ren); // move robot SDL_PumpEvents(); const Uint8 *key_pressed = SDL_GetKeyboardState(NULL); robby.move(key_pressed, control); // measure landmark positions auto observed_landmarks = robby.measureLandmarks(landmarks); // get robot state Eigen::VectorXf state = robby.get_state(); // Localize via Landmarks kf.localization_landmarks(observed_landmarks, landmarks, control); // get estimated state (x,y,phi) as estimated by the EKF auto x_hat = kf.get_state(); printf("True x,y,phi: %f, %f, %f\n", state(0), state(1),state(2)); printf("Estimated x,y,phi: %f, %f, %f\n", x_hat(0), x_hat(1), x_hat(2)); // move robby estimate to new pose as calculated by kalman filter: robby_estimate.setPose(x_hat(0), x_hat(1), x_hat(2)); robby_estimate.render(ren); // render robot robby.render(ren); // render landmarks for (auto lm = landmarks.begin(); lm != landmarks.end(); ++lm) { SDL_SetRenderDrawColor(ren, lm->id.r, lm->id.g, lm->id.b, lm->id.a); lm->render(ren); } SDL_SetRenderDrawColor(ren, gray.r, gray.g, gray.b, gray.a); // render sampled probability distribution kf.renderSamples(ren); SDL_RenderPresent(ren); //Take a quick break after all that hard work SDL_Delay(30); if (key_pressed[SDL_SCANCODE_RETURN]) { printf("Exiting Program!\n"); break; } i+=1; } SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; }
void cleanup<SDL_Window>(SDL_Window *win){ if (!win){ return; } SDL_DestroyWindow(win); }
void CommonEvent(CommonState * state, SDL_Event * event, int *done) { int i; if (state->verbose & VERBOSE_EVENT) { PrintEvent(event); } switch (event->type) { case SDL_WINDOWEVENT: switch (event->window.event) { case SDL_WINDOWEVENT_CLOSE: { SDL_Window *window = SDL_GetWindowFromID(event->window.windowID); if (window) { SDL_DestroyWindow(window); } } break; } break; case SDL_KEYDOWN: switch (event->key.keysym.sym) { /* Add hotkeys here */ case SDLK_PRINTSCREEN: { SDL_Window *window = SDL_GetWindowFromID(event->key.windowID); if (window) { for (i = 0; i < state->num_windows; ++i) { if (window == state->windows[i]) { ScreenShot(state->renderers[i]); } } } } break; case SDLK_c: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-C copy awesome text! */ SDL_SetClipboardText("SDL rocks!\nYou know it!"); printf("Copied text to clipboard\n"); } break; case SDLK_v: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-V paste awesome text! */ char *text = SDL_GetClipboardText(); if (*text) { printf("Clipboard: %s\n", text); } else { printf("Clipboard is empty\n"); } SDL_free(text); } break; case SDLK_g: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-G toggle grab */ SDL_Window *window = SDL_GetWindowFromID(event->key.windowID); if (window) { SDL_SetWindowGrab(window, !SDL_GetWindowGrab(window)); } } break; case SDLK_m: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-M maximize */ SDL_Window *window = SDL_GetWindowFromID(event->key.windowID); if (window) { Uint32 flags = SDL_GetWindowFlags(window); if (flags & SDL_WINDOW_MAXIMIZED) { SDL_RestoreWindow(window); } else { SDL_MaximizeWindow(window); } } } break; case SDLK_r: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-R toggle mouse relative mode */ SDL_SetRelativeMouseMode(!SDL_GetRelativeMouseMode()); } break; case SDLK_z: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-Z minimize */ SDL_Window *window = SDL_GetWindowFromID(event->key.windowID); if (window) { SDL_MinimizeWindow(window); } } break; case SDLK_RETURN: if (event->key.keysym.mod & KMOD_CTRL) { /* Ctrl-Enter toggle fullscreen */ SDL_Window *window = SDL_GetWindowFromID(event->key.windowID); if (window) { Uint32 flags = SDL_GetWindowFlags(window); if (flags & SDL_WINDOW_FULLSCREEN) { SDL_SetWindowFullscreen(window, SDL_FALSE); } else { SDL_SetWindowFullscreen(window, SDL_TRUE); } } } break; case SDLK_ESCAPE: *done = 1; break; default: break; } break; case SDL_QUIT: *done = 1; break; } }
OpenGLRenderer::~OpenGLRenderer() { glDeleteVertexArrays(1, &vertex_array_id_); SDL_GL_DeleteContext(context_); SDL_DestroyWindow(window_); }
Renderer::~Renderer() { SDL_GL_DeleteContext(glcontext); SDL_DestroyWindow(window); SDL_Quit(); }
int main(int argc, char* argv[]){ if(argc<=1){ std::cerr<<"Usage: "<<argv[0]<<" <vertexShader.glsl> [-w <width>] [-h <height>] [-c{0,1,2,3,4} index]\n"; return 1; } char* wArg = getCmdOption(argv, argv+argc, "-w"); if(wArg){ width = std::atoi(wArg); } char* hArg = getCmdOption(argv, argv+argc, "-h"); if(hArg){ height = std::atoi(hArg); } char* c0Arg = getCmdOption(argv, argv+argc, "-c0"); if(c0Arg){ iChannel0Index=std::atoi(c0Arg); } char* c1Arg = getCmdOption(argv, argv+argc, "-c1"); if(c1Arg){ iChannel1Index=std::atoi(c1Arg); } char* c2Arg = getCmdOption(argv, argv+argc, "-c2"); if(c2Arg){ iChannel2Index=std::atoi(c2Arg); } char* c3Arg = getCmdOption(argv, argv+argc, "-c3"); if(c3Arg){ iChannel3Index=std::atoi(c3Arg); } SDL_Init(SDL_INIT_VIDEO); SDL_Window* window; SDL_GLContext maincontext; SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL,1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); window = SDL_CreateWindow("Shadertoy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL ); maincontext = SDL_GL_CreateContext(window); glViewport(0,0,width,height); SDL_GL_SetSwapInterval(1); std::cout<<glGetString(GL_VERSION)<<"\n"; std::ifstream shaderInStream(argv[1]); std::stringstream buffer; buffer << uniforms << shaderInStream.rdbuf()<<mainMethod; std::string contents = buffer.str(); GLuint programIndex = compile(contents); glUseProgram(programIndex); iResolutionLocation = glGetUniformLocation(programIndex, "iResolution"); iGlobalTimeLocation = glGetUniformLocation(programIndex, "iGlobalTime"); iMouseLocation = glGetUniformLocation(programIndex, "iMouse"); iChannel0Location = glGetUniformLocation(programIndex, "iChannel0"); iChannel1Location = glGetUniformLocation(programIndex, "iChannel1"); iChannel2Location = glGetUniformLocation(programIndex, "iChannel2"); iChannel3Location = glGetUniformLocation(programIndex, "iChannel3"); iChannelResolutionLocation = glGetUniformLocation(programIndex, "iChannelResolution"); loadTextures(); setStaticUniforms(); unsigned int lastTime=SDL_GetTicks(); unsigned int deltaCounter=0; unsigned int fps=0; unsigned int secondCounter=0; bool hasQuit=false; while(!hasQuit){ unsigned int now=SDL_GetTicks(); deltaCounter+=now-lastTime; secondCounter+=now-lastTime; lastTime=now; while(deltaCounter>17){ deltaCounter-=17; } SDL_Event e; while(SDL_PollEvent(&e)){ switch(e.type){ case SDL_QUIT: hasQuit=true; break; case SDL_MOUSEBUTTONDOWN: mouseXPos=mouseXClick=e.button.x; mouseYPos=mouseYClick=e.button.y; break; case SDL_MOUSEMOTION: if(e.motion.state&SDL_BUTTON(1)){ mouseXPos=e.motion.x; mouseYPos=e.motion.y; } } } setDynamicUniforms(); glRects(-1,-1,1,1); SDL_GL_SwapWindow(window); fps++; if(secondCounter>1000){ std::cout<<fps<<" FPS\n"; fps=0; secondCounter-=1000; } // SDL_Delay(10); } SDL_DestroyWindow(window); SDL_Quit(); }
int main(int argc, char**argv) { if(SDL_Init(SDL_INIT_VIDEO)==-1) { SDL_Log("%s\n", SDL_GetError()); } SDL_Window* wnd; wnd = SDL_CreateWindow ("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1680, 1050, SDL_WINDOW_OPENGL); if(wnd == NULL) { SDL_Log("%s\n", SDL_GetError()); } SDL_GLContext glctxt = SDL_GL_CreateContext(wnd); if(glctxt == NULL) { SDL_Log("%s\n", SDL_GetError()); } const Uint8* kbd = SDL_GetKeyboardState(NULL); if(kbd == NULL) { SDL_Log("%s\n", SDL_GetError()); } int done=0; float t=0.0; float dt=0.0; frame_init(); int wnd_w, wnd_h; SDL_GetWindowSize(wnd, &wnd_w, &wnd_h); render_init(wnd_w, wnd_h); float mousex_old; float mousey_old; while(!done) { int start_time = SDL_GetTicks(); /* react to system quit event */ SDL_Event evt; while(SDL_PollEvent(&evt)) { if(evt.type==SDL_QUIT) { done = 1; } } /* get mouse state */ int imousex, imousey; /* i for int */ Uint32 mouseb = SDL_GetMouseState(&imousex, &imousey); /* convert "integer" coordinates to "floating point" coordinates */ /* (0.5, 0.5) is monitor center */ /* (1.0, 1.0) is top right corner */ /* (0.0, 0.0) is bottom left corner */ float mousex, mousey; int wnd_w, wnd_h; SDL_GetWindowSize(wnd, &wnd_w, &wnd_h); mousex = (float)(imousex)/(wnd_w); mousey = 1.0f - (float)(imousey)/(wnd_h); float dx = mousex - mousex_old; float dy = mousey - mousey_old; mousex_old = mousex; mousey_old = mousey; done = frame(dt, evt, kbd, dx, dy, mouseb); render(); SDL_GL_SwapWindow(wnd); /* sleep */ int dt_int = SDL_GetTicks() - start_time; if(dt_int < DELAY_TIME) SDL_Delay(DELAY_TIME - dt_int); dt = (float)dt_int / 1.0e3; } frame_shutdown(); render_shutdown(); /* free resources */ SDL_GL_DeleteContext(glctxt); SDL_DestroyWindow(wnd); SDL_Quit(); return 0; }
int main(int argc, char* argv[]) { SDL_GLContext context; SDL_Window *window; SDL_Init(SDL_INIT_VIDEO); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); window = SDL_CreateWindow( "Wolf", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL ); if (!window) { fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); return 1; } context = SDL_GL_CreateContext(window); glewExperimental = GL_TRUE; glewInit(); wolf_load_texture(0, "Assets/Textures/Wall.jpg"); wolf_load_texture(1, "Assets/Textures/Floor.jpg"); glViewport(0, 0, (GLsizei) 640, (GLsizei) 480); unsigned int time_delta = 0; while (running) { unsigned int frame_start, frame_end; frame_start = SDL_GetTicks(); wolf_input(); wolf_update(time_delta); wolf_frame(&position, &direction, angle); SDL_GL_SwapWindow(window); frame_end = SDL_GetTicks(); time_delta = frame_end - frame_start; } SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
Graphics::~Graphics() { SDL_DestroyWindow(this->_window); }
static void _gut_destroyWindow(SDL_Window **window) { if (*window) { SDL_DestroyWindow(*window); *window = NULL; } }
int main(int argc, char* argv[]) { signal(SIGSEGV, segFault); if (argc < 2) { printUsage(); return 0; } #ifdef DEPRECATED printf("*Deprecation warning*\n"); fflush(0); #endif randomizer.timeSeed(); Scene& scene = *Scene::getInstance(); Texture screen; int w = 300, h = 300; bool threads_changed = 0; std::string filename, output = "out.bmp"; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--no-preview")) { settings.show_preview = 0; } else if (!strcmp(argv[i], "--size")) { sscanf(argv[++i], "%d", &w); sscanf(argv[++i], "%d", &h); } else if (!strcmp(argv[i], "--renders")) { sscanf(argv[++i], "%d", &settings.nrenders); } else if (!strcmp(argv[i], "--samples")) { sscanf(argv[++i], "%d", &settings.nsamples); } else if (!strcmp(argv[i], "--shadows")) { sscanf(argv[++i], "%d", &settings.nshadows); } else if (!strcmp(argv[i], "--coherent")) { settings.coherence = 1; } else if (!strcmp(argv[i], "--point-lights")) { settings.point_lights = 1; } else if (!strcmp(argv[i], "--dof-degrees")) { sscanf(argv[++i], "%f", &settings.dof_range); settings.dof_range *= PI / 180.0; } else if (!strcmp(argv[i], "--no-aa")) { settings.aa_enabled = 0; } else if (!strcmp(argv[i], "--aa-threshold")) { sscanf(argv[++i], "%f", &settings.aa_threshold); } else if (!strcmp(argv[i], "--threads")) { threads_changed = 1; sscanf(argv[++i], "%d", &settings.nworkers); } else if (!strcmp(argv[i], "--output") || !strcmp(argv[i], "-o")) { output = argv[++i]; } else if (!strcmp(argv[i], "--no-output")) { output = ""; } else { if (filename.empty()) { filename = argv[i]; } else { printf("Unrecognized token \"%s\".\n", argv[i]); exit(0); } } } if (settings.show_preview) { if (SDL_Init(SDL_INIT_VIDEO) < 0) return -1; } else { if (SDL_Init(0) < 0) return -1; } atexit(SDL_Quit); if (!threads_changed) { settings.nworkers = SDL_GetCPUCount(); if (settings.nworkers > 1) settings.nworkers--; //Use n threads (counting this one) on n-core machines, but 2 threads for single-core machines } try { Parser parser; parser.parseInto(filename.c_str(), &scene); } catch (std::exception& e) { fprintf(stderr, "%s\n", e.what()); return 1; } scene.init(); /* * Set up scene */ scene.camera.setScreen(w, h, (float)w / h, 1, PI / 2); screen.setDimensions(scene.camera.pxw, scene.camera.pxh); drawPattern(screen); if (settings.show_preview) { window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, scene.camera.pxw, scene.camera.pxh, 0); px = new PixelRenderer(SDL_CreateRenderer(window, -1, 0), scene.camera.pxw, scene.camera.pxh); redraw(screen); } Uint32 started = SDL_GetTicks(); std::vector<Texture> screens; for (int i = 0; i < settings.nrenders; i++) { render(scene, screen, i + 1, settings.nrenders); screens.push_back(screen); randomizer.advanceSeed(); } screen = Texture(screens); #ifndef SHOW_AA if (settings.show_preview) redraw(screen); #endif printf("Tracing complete:\n"); printf("\tTotal time elapsed: %.3fs\n", 0.001 * (SDL_GetTicks() - started)); fflush(0); if (output != "") screen.save_filename(output); if (settings.show_preview) { SDL_Event event; bool exitflag = 0; while (!exitflag) { while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) exitflag = 1; SDL_Delay(100); } SDL_DestroyRenderer(px->getRenderer()); delete px; SDL_DestroyWindow(window); } return 0; }
/* =============== GLimp_SetMode =============== */ static int GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder) { const char *glstring; int perChannelColorBits; int colorBits, depthBits, stencilBits; int samples; int i = 0; SDL_Surface *icon = NULL; Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; SDL_DisplayMode desktopMode; int display = 0; int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; char windowTitle[128]; textureLevel_t *iconPic; byte *pixelData; int bytesPerPixel, width, height; ri.Printf( PRINT_ALL, "Initializing OpenGL display\n"); ri.Cvar_VariableStringBuffer("com_productName", windowTitle, sizeof (windowTitle)); if ( r_allowResize->integer ) flags |= SDL_WINDOW_RESIZABLE; iconPic = NULL; pixelData = NULL; bytesPerPixel = 4; #ifdef USE_ICON // try to load 32 x 32 icon if ( r_forceWindowIcon32->integer ) { int numLevels; R_LoadImage( "windowicon32", &numLevels, &iconPic ); if ( iconPic && ( iconPic[0].width != 32 || iconPic[0].height != 32 ) ) { ri.Free( iconPic ); iconPic = NULL; ri.Printf( PRINT_WARNING, "Ignoring windowicon32: Image must be 32 x 32!\n"); } } else { int numLevels; // try to load high resolution icon R_LoadImage( "windowicon", &numLevels, &iconPic ); } if ( iconPic ) { pixelData = iconPic[0].data; width = iconPic[0].width; height = iconPic[0].height; } else { // fallback to default icon pixelData = (byte *)CLIENT_WINDOW_ICON.pixel_data; bytesPerPixel = CLIENT_WINDOW_ICON.bytes_per_pixel; width = CLIENT_WINDOW_ICON.width; height = CLIENT_WINDOW_ICON.height; } icon = SDL_CreateRGBSurfaceFrom( (void *)pixelData, width, height, bytesPerPixel * 8, bytesPerPixel * width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); #endif // If a window exists, note its display index if( SDL_window != NULL ) { display = SDL_GetWindowDisplayIndex( SDL_window ); if( display < 0 ) { ri.Printf( PRINT_DEVELOPER, "SDL_GetWindowDisplayIndex() failed: %s\n", SDL_GetError() ); } } if( display >= 0 && SDL_GetDesktopDisplayMode( display, &desktopMode ) == 0 ) { glConfig.displayWidth = desktopMode.w; glConfig.displayHeight = desktopMode.h; glConfig.displayAspect = (float)desktopMode.w / (float)desktopMode.h; ri.Printf( PRINT_ALL, "Display aspect: %.3f\n", glConfig.displayAspect ); } else { Com_Memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) ); glConfig.displayWidth = 640; glConfig.displayHeight = 480; glConfig.displayAspect = 1.333f; ri.Printf( PRINT_ALL, "Cannot determine display aspect, assuming 1.333\n" ); } ri.Printf (PRINT_ALL, "...setting mode %d:", mode ); if (mode == -2) { // use desktop video resolution if( desktopMode.h > 0 ) { glConfig.vidWidth = desktopMode.w; glConfig.vidHeight = desktopMode.h; } else { glConfig.vidWidth = 640; glConfig.vidHeight = 480; ri.Printf( PRINT_ALL, "Cannot determine display resolution, assuming 640x480\n" ); } glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; } else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) ) { ri.Printf( PRINT_ALL, " invalid mode\n" ); return RSERR_INVALID_MODE; } ri.Printf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight); // Center window if( r_centerWindow->integer && !fullscreen ) { x = ( desktopMode.w / 2 ) - ( glConfig.vidWidth / 2 ); y = ( desktopMode.h / 2 ) - ( glConfig.vidHeight / 2 ); } // Destroy existing state if it exists if( SDL_glContext != NULL ) { SDL_GL_DeleteContext( SDL_glContext ); SDL_glContext = NULL; } if( SDL_window != NULL ) { SDL_GetWindowPosition( SDL_window, &x, &y ); ri.Printf( PRINT_DEVELOPER, "Existing window at %dx%d before being destroyed\n", x, y ); SDL_DestroyWindow( SDL_window ); SDL_window = NULL; } if( fullscreen ) { flags |= SDL_WINDOW_FULLSCREEN; glConfig.isFullscreen = qtrue; } else { if( noborder ) flags |= SDL_WINDOW_BORDERLESS; glConfig.isFullscreen = qfalse; } colorBits = r_colorbits->value; if ((!colorBits) || (colorBits >= 32)) colorBits = 24; if (!r_depthbits->value) depthBits = 24; else depthBits = r_depthbits->value; stencilBits = r_stencilbits->value; samples = r_ext_multisample->value; for (i = 0; i < 16; i++) { int testColorBits, testDepthBits, testStencilBits; // 0 - default // 1 - minus colorBits // 2 - minus depthBits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2 : if (colorBits == 24) colorBits = 16; break; case 1 : if (depthBits == 24) depthBits = 16; else if (depthBits == 16) depthBits = 8; case 3 : if (stencilBits == 24) stencilBits = 16; else if (stencilBits == 16) stencilBits = 8; } } testColorBits = colorBits; testDepthBits = depthBits; testStencilBits = stencilBits; if ((i % 4) == 3) { // reduce colorBits if (testColorBits == 24) testColorBits = 16; } if ((i % 4) == 2) { // reduce depthBits if (testDepthBits == 24) testDepthBits = 16; else if (testDepthBits == 16) testDepthBits = 8; } if ((i % 4) == 1) { // reduce stencilBits if (testStencilBits == 24) testStencilBits = 16; else if (testStencilBits == 16) testStencilBits = 8; else testStencilBits = 0; } if (testColorBits == 24) perChannelColorBits = 8; else perChannelColorBits = 4; #ifdef __sgi /* Fix for SGIs grabbing too many bits of color */ if (perChannelColorBits == 4) perChannelColorBits = 0; /* Use minimum size for 16-bit color */ /* Need alpha or else SGIs choose 36+ bit RGB mode */ SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1); #endif SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); if(r_stereoEnabled->integer) { glConfig.stereoEnabled = qtrue; SDL_GL_SetAttribute(SDL_GL_STEREO, 1); } else { glConfig.stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); #if 0 // if multisampling is enabled on X11, this causes create window to fail. // If not allowing software GL, demand accelerated if( !r_allowSoftwareGL->integer ) SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ); #endif if( ( SDL_window = SDL_CreateWindow( windowTitle, x, y, glConfig.vidWidth, glConfig.vidHeight, flags ) ) == NULL ) { ri.Printf( PRINT_DEVELOPER, "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); continue; } if( fullscreen ) { SDL_DisplayMode mode; switch( testColorBits ) { case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; default: ri.Printf( PRINT_DEVELOPER, "testColorBits is %d, can't fullscreen\n", testColorBits ); continue; } mode.w = glConfig.vidWidth; mode.h = glConfig.vidHeight; mode.refresh_rate = glConfig.displayFrequency = ri.Cvar_VariableIntegerValue( "r_displayRefresh" ); mode.driverdata = NULL; if( SDL_SetWindowDisplayMode( SDL_window, &mode ) < 0 ) { ri.Printf( PRINT_DEVELOPER, "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) ); continue; } } SDL_SetWindowIcon( SDL_window, icon ); if( ( SDL_glContext = SDL_GL_CreateContext( SDL_window ) ) == NULL ) { ri.Printf( PRINT_DEVELOPER, "SDL_GL_CreateContext failed: %s\n", SDL_GetError( ) ); continue; } qglClearColor( 0, 0, 0, 1 ); qglClear( GL_COLOR_BUFFER_BIT ); SDL_GL_SwapWindow( SDL_window ); if( SDL_GL_SetSwapInterval( r_swapInterval->integer ) == -1 ) { ri.Printf( PRINT_DEVELOPER, "SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError( ) ); } glConfig.colorBits = testColorBits; glConfig.depthBits = testDepthBits; glConfig.stencilBits = testStencilBits; ri.Printf( PRINT_ALL, "Using %d color bits, %d depth, %d stencil display.\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); break; } SDL_FreeSurface( icon ); if ( iconPic ) { ri.Free( iconPic ); iconPic = NULL; } if( !SDL_window ) { ri.Printf( PRINT_ALL, "Couldn't get a visual\n" ); return RSERR_INVALID_MODE; } GLimp_DetectAvailableModes(); glstring = (char *) qglGetString (GL_RENDERER); ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring ); return RSERR_OK; }
int vid_thread (void* arg) { SDL_Event event; static char *eventtypes[SDL_LASTEVENT]; static t_bool initialized = FALSE; if (!initialized) { initialized = TRUE; eventtypes[SDL_QUIT] = "QUIT"; /**< User-requested quit */ /* These application events have special meaning on iOS, see README-ios.txt for details */ eventtypes[SDL_APP_TERMINATING] = "APP_TERMINATING"; /**< The application is being terminated by the OS Called on iOS in applicationWillTerminate() Called on Android in onDestroy() */ eventtypes[SDL_APP_LOWMEMORY] = "APP_LOWMEMORY"; /**< The application is low on memory, free memory if possible. Called on iOS in applicationDidReceiveMemoryWarning() Called on Android in onLowMemory() */ eventtypes[SDL_APP_WILLENTERBACKGROUND] = "APP_WILLENTERBACKGROUND"; /**< The application is about to enter the background Called on iOS in applicationWillResignActive() Called on Android in onPause() */ eventtypes[SDL_APP_DIDENTERBACKGROUND] = "APP_DIDENTERBACKGROUND"; /**< The application did enter the background and may not get CPU for some time Called on iOS in applicationDidEnterBackground() Called on Android in onPause() */ eventtypes[SDL_APP_WILLENTERFOREGROUND] = "APP_WILLENTERFOREGROUND"; /**< The application is about to enter the foreground Called on iOS in applicationWillEnterForeground() Called on Android in onResume() */ eventtypes[SDL_APP_DIDENTERFOREGROUND] = "APP_DIDENTERFOREGROUND"; /**< The application is now interactive Called on iOS in applicationDidBecomeActive() Called on Android in onResume() */ /* Window events */ eventtypes[SDL_WINDOWEVENT] = "WINDOWEVENT"; /**< Window state change */ eventtypes[SDL_SYSWMEVENT] = "SYSWMEVENT"; /**< System specific event */ /* Keyboard events */ eventtypes[SDL_KEYDOWN] = "KEYDOWN"; /**< Key pressed */ eventtypes[SDL_KEYUP] = "KEYUP"; /**< Key released */ eventtypes[SDL_TEXTEDITING] = "TEXTEDITING"; /**< Keyboard text editing (composition) */ eventtypes[SDL_TEXTINPUT] = "TEXTINPUT"; /**< Keyboard text input */ /* Mouse events */ eventtypes[SDL_MOUSEMOTION] = "MOUSEMOTION"; /**< Mouse moved */ eventtypes[SDL_MOUSEBUTTONDOWN] = "MOUSEBUTTONDOWN"; /**< Mouse button pressed */ eventtypes[SDL_MOUSEBUTTONUP] = "MOUSEBUTTONUP"; /**< Mouse button released */ eventtypes[SDL_MOUSEWHEEL] = "MOUSEWHEEL"; /**< Mouse wheel motion */ /* Joystick events */ eventtypes[SDL_JOYAXISMOTION] = "JOYAXISMOTION"; /**< Joystick axis motion */ eventtypes[SDL_JOYBALLMOTION] = "JOYBALLMOTION"; /**< Joystick trackball motion */ eventtypes[SDL_JOYHATMOTION] = "JOYHATMOTION"; /**< Joystick hat position change */ eventtypes[SDL_JOYBUTTONDOWN] = "JOYBUTTONDOWN"; /**< Joystick button pressed */ eventtypes[SDL_JOYBUTTONUP] = "JOYBUTTONUP"; /**< Joystick button released */ eventtypes[SDL_JOYDEVICEADDED] = "JOYDEVICEADDED"; /**< A new joystick has been inserted into the system */ eventtypes[SDL_JOYDEVICEREMOVED] = "JOYDEVICEREMOVED"; /**< An opened joystick has been removed */ /* Game controller events */ eventtypes[SDL_CONTROLLERAXISMOTION] = "CONTROLLERAXISMOTION"; /**< Game controller axis motion */ eventtypes[SDL_CONTROLLERBUTTONDOWN] = "CONTROLLERBUTTONDOWN"; /**< Game controller button pressed */ eventtypes[SDL_CONTROLLERBUTTONUP] = "CONTROLLERBUTTONUP"; /**< Game controller button released */ eventtypes[SDL_CONTROLLERDEVICEADDED] = "CONTROLLERDEVICEADDED"; /**< A new Game controller has been inserted into the system */ eventtypes[SDL_CONTROLLERDEVICEREMOVED] = "CONTROLLERDEVICEREMOVED"; /**< An opened Game controller has been removed */ eventtypes[SDL_CONTROLLERDEVICEREMAPPED] = "CONTROLLERDEVICEREMAPPED"; /**< The controller mapping was updated */ /* Touch events */ eventtypes[SDL_FINGERDOWN] = "FINGERDOWN"; eventtypes[SDL_FINGERUP] = "FINGERUP"; eventtypes[SDL_FINGERMOTION] = "FINGERMOTION"; /* Gesture events */ eventtypes[SDL_DOLLARGESTURE] = "DOLLARGESTURE"; eventtypes[SDL_DOLLARRECORD] = "DOLLARRECORD"; eventtypes[SDL_MULTIGESTURE] = "MULTIGESTURE"; /* Clipboard events */ eventtypes[SDL_CLIPBOARDUPDATE] = "CLIPBOARDUPDATE"; /**< The clipboard changed */ /* Drag and drop events */ eventtypes[SDL_DROPFILE] = "DROPFILE"; /**< The system requests a file open */ /** Events ::SDL_USEREVENT through ::SDL_LASTEVENT are for your use, * and should be allocated with SDL_RegisterEvents() */ eventtypes[SDL_USEREVENT] = "USEREVENT"; } sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Starting\n"); vid_mono_palette[0] = sim_end ? 0xFF000000 : 0x000000FF; vid_mono_palette[1] = 0xFFFFFFFF; memset (&vid_key_state, 0, sizeof(vid_key_state)); SDL_Init (SDL_INIT_VIDEO); SDL_CreateWindowAndRenderer (vid_width, vid_height, SDL_WINDOW_SHOWN, &vid_window, &vid_renderer); if ((vid_window == NULL) || (vid_renderer == NULL)) { sim_printf ("%s: Error Creating Video Window: %s\b", sim_dname(vid_dev), SDL_GetError()); SDL_Quit (); return 0; } SDL_SetRenderDrawColor (vid_renderer, 0, 0, 0, 255); SDL_RenderClear (vid_renderer); SDL_RenderPresent (vid_renderer); vid_texture = SDL_CreateTexture (vid_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, vid_width, vid_height); if (!vid_texture) { sim_printf ("%s: Error configuring Video environment: %s\b", sim_dname(vid_dev), SDL_GetError()); SDL_DestroyRenderer(vid_renderer); vid_renderer = NULL; SDL_DestroyWindow(vid_window); vid_window = NULL; SDL_Quit (); return 0; } SDL_StopTextInput (); sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Started\n"); while (vid_active) { if (SDL_WaitEvent (&event)) { switch (event.type) { case SDL_KEYDOWN: case SDL_KEYUP: vid_key ((SDL_KeyboardEvent*)&event); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: vid_mouse_button ((SDL_MouseButtonEvent*)&event); break; case SDL_MOUSEMOTION: vid_mouse_move ((SDL_MouseMotionEvent*)&event); break; case SDL_USEREVENT: /* There are 2 user events generated */ /* EVENT_REDRAW to update the display */ /* EVENT_CLOSE to wake up this thread and let */ /* it notice vid_active has changed */ if (event.user.code == EVENT_REDRAW) vid_update (); break; default: sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Ignored Event: Type: %s(%d)\n", eventtypes[event.type], event.type); break; } } } SDL_DestroyTexture(vid_texture); vid_texture = NULL; SDL_DestroyRenderer(vid_renderer); vid_renderer = NULL; SDL_DestroyWindow(vid_window); vid_window = NULL; SDL_Quit (); sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Exiting\n"); return 0; }
int main(int argc, char *argv[]) { #ifdef _WIN32 /*Initialise SDL needed for desktop*/ if (SDL_Init(SDL_INIT_VIDEO) < 0) //Check SDL initialisation { //Failed initialisation SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL"); return -1; } #endif /*Initialise SDL_ttf*/ if (TTF_Init() < 0) /*Check SDL_ttf initialisation*/ { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_ttf"); return -1; } /*Initialise SDL_mixer*/ Mix_Init(MIX_INIT_OGG); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_Mixer"); return -1; } /*Initialize PNG loading*/ int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_image"); return -1; } /*Time Check*/ unsigned int lastTime = SDL_GetTicks(); SDL_Window* window; SDL_Renderer* renderer; int winWidth; int winHeight; #ifdef __ANDROID__ if(SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer) < 0) exit(2); SDL_GetWindowSize(window, &winWidth, &winHeight); #elif _WIN32 /*Create Window*/ int winPosX = 100; int winPosY = 100; winWidth = 640; winHeight = 480; window = SDL_CreateWindow("MGPDemoAudio", /*The first parameter is the window title*/ winPosX, winPosY, winWidth, winHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); /*Create Renderer from the window*/ renderer = SDL_CreateRenderer(window, -1, 0); #endif /*setup state manager*/ JAM_StateManager * stateManager = new JAM_StateManager(); /*set the initial state*/ stateManager->addState(new Game(stateManager, renderer, winWidth, winHeight)); /*Start Game Loop*/ bool go = true; while (go) { /*Time Check*/ unsigned int current = SDL_GetTicks(); float deltaTime = (float)(current - lastTime) / 1000.0f; lastTime = current; /*handle the current state inputs*/ go = stateManager->input(); /*update the current state*/ stateManager->update(deltaTime); /*set draw colour to white*/ SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); /*Clear the entire screen to the set colour*/ SDL_RenderClear(renderer); /*draw the states*/ stateManager->draw(); /*display renderer*/ SDL_RenderPresent(renderer); /*Time Limiter*/ if (deltaTime < (1.0f / 50.0f)) { SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f)); } } /*destroy data*/ delete stateManager; SDL_DestroyWindow(window); SDL_Quit(); exit(0); return 0; }
RenderManager::~RenderManager() { #ifdef USES_SDL SDL_DestroyWindow(this->gWindow); SDL_Quit(); #endif // USES_SDL }
void ModoGraficoSDL::limpiar() { SDL_DestroyRenderer(this->renderizador); SDL_DestroyWindow(this->ventana); SDL_Quit(); }
int graphics_SetMode(int width, int height, int fullscreen, int resizable, const char* title, const char* renderer, char** error) { graphics_calculateUnitToPixels(width, height); #if defined(ANDROID) if (!fullscreen) { // do not use windowed on Android *error = strdup("Windowed mode is not supported on Android"); return 0; } #endif char errormsg[512]; // initialize SDL video if not done yet if (!graphics_InitVideoSubsystem(error)) { return 0; } // think about the renderer we want #ifndef WINDOWS #ifdef ANDROID char preferredrenderer[20] = "opengles"; #else char preferredrenderer[20] = "opengl"; #endif #else char preferredrenderer[20] = "direct3d"; #endif int softwarerendering = 0; if (renderer) { if (strcasecmp(renderer, "software") == 0) { #ifdef ANDROID // we don't want software rendering on Android #else softwarerendering = 1; strcpy(preferredrenderer, "software"); #endif } else { if (strcasecmp(renderer, "opengl") == 0) { #ifdef ANDROID // opengles is the opengl we want for android :-) strcpy(preferredrenderer, "opengles"); #else // regular opengl on desktop platforms strcpy(preferredrenderer, "opengl"); #endif } #ifdef WINDOWS // only windows knows direct3d obviously if (strcasecmp(renderer,"direct3d") == 0) { strcpy(preferredrenderer, "direct3d"); } #endif } } // get renderer index int rendererindex = -1; if (strlen(preferredrenderer) > 0 && !softwarerendering) { int count = SDL_GetNumRenderDrivers(); if (count > 0) { int r = 0; while (r < count) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(r, &info); if (strcasecmp(info.name, preferredrenderer) == 0) { rendererindex = r; break; } r++; } } } // see if anything changes at all unsigned int oldw = 0; unsigned int oldh = 0; graphics_GetWindowDimensions(&oldw,&oldh); if (mainwindow && mainrenderer && width == (int)oldw && height == (int)oldh) { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); if (strcasecmp(preferredrenderer, info.name) == 0) { // same renderer and resolution if (strcmp(SDL_GetWindowTitle(mainwindow), title) != 0) { SDL_SetWindowTitle(mainwindow, title); } // toggle fullscreen if desired if (graphics_IsFullscreen() != fullscreen) { graphics_ToggleFullscreen(); } return 1; } } // Check if we support the video mode for fullscreen - // This is done to avoid SDL allowing impossible modes and // giving us a fake resized/padded/whatever output we don't want. if (fullscreen) { // check all video modes in the list SDL returns for us int count = graphics_GetNumberOfVideoModes(); int i = 0; int supportedmode = 0; while (i < count) { int w,h; graphics_GetVideoMode(i, &w, &h); if (w == width && h == height) { supportedmode = 1; break; } i++; } if (!supportedmode) { // check for desktop video mode aswell int w,h; graphics_GetDesktopVideoMode(&w,&h); if (w == 0 || h == 0 || width != w || height != h) { *error = strdup("Video mode is not supported"); return 0; } } } // notify texture manager of device shutdown texturemanager_deviceLost(); // destroy old window/renderer if we got one graphics_Close(1); // create window if (fullscreen) { mainwindow = SDL_CreateWindow(title, 0, 0, width, height, SDL_WINDOW_FULLSCREEN); mainwindowfullscreen = 1; } else { mainwindow = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_MINIMIZED); mainwindowfullscreen = 0; } if (!mainwindow) { snprintf(errormsg, sizeof(errormsg), "Failed to open SDL window: %s", SDL_GetError()); errormsg[sizeof(errormsg)-1] = 0; *error = strdup(errormsg); return 0; } // see if we actually ended up with the resolution we wanted: int actualwidth, actualheight; SDL_GetWindowSize(mainwindow, &actualwidth, &actualheight); if (actualwidth != width || actualheight != height) { if (fullscreen) { // we failed to get the requested resolution: SDL_DestroyWindow(mainwindow); snprintf(errormsg, sizeof(errormsg), "Failed to open " "SDL window: ended up with other resolution than requested"); *error = strdup(errormsg); return 0; } } // Create renderer if (!softwarerendering) { mainrenderer = SDL_CreateRenderer(mainwindow, rendererindex, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); if (!mainrenderer) { softwarerendering = 1; strcpy(preferredrenderer, "software"); } } if (softwarerendering) { mainrenderer = SDL_CreateRenderer(mainwindow, -1, SDL_RENDERER_SOFTWARE); } if (!mainrenderer) { // we failed to create the renderer if (mainwindow) { // destroy window aswell in case it is open SDL_DestroyWindow(mainwindow); mainwindow = NULL; } if (softwarerendering) { snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend software): %s", SDL_GetError()); } else { SDL_RendererInfo info; SDL_GetRenderDriverInfo(rendererindex, &info); snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend %s): %s", info.name, SDL_GetError()); } errormsg[sizeof(errormsg)-1] = 0; *error = strdup(errormsg); return 0; } else { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); } // notify texture manager that device is back texturemanager_deviceRestored(); // Transfer textures back to SDL /*if (!graphicstexturelist_TransferTexturesToHW()) { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend %s): " "Cannot recreate textures", info.name); *error = strdup(errormsg); SDL_DestroyRenderer(mainrenderer); SDL_DestroyWindow(mainwindow); return 0; }*/ // Re-focus window if previously focussed if (!inbackground) { SDL_RaiseWindow(mainwindow); } graphicsactive = 1; return 1; }
Display::~Display () { SDL_DestroyWindow(_window); SDL_Quit(); }
OpenGL_Window::~OpenGL_Window() { SDL_DestroyWindow(window); SDL_GL_DeleteContext(context); SDL_Quit(); }
SDLApp::~SDLApp() { SDL_DestroyRenderer(renderer_); SDL_DestroyWindow( mainwindow_ ); SDL_Quit(); }
void SDLHandler::CleanUp() { SDL_GL_DeleteContext(opengl_context); SDL_DestroyWindow(window); SDL_Quit(); }
int main(int argc, char* argv[]) { const unsigned int windowWidth = 640; const unsigned int windowHeight = 480; SDL_Window* pWindow = NULL; // Ecran principal SDL_Surface* pImage = NULL; // Logo char mustContinue = 1; // Indicateur boolean pour la boucle principale int imgFlags = IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF; // Flags pour charger le support du JPG, PNG et TIF const char* imagePath = "./data/logo.jpg"; SDL_Rect blitDestination; TTF_Font* pFont = NULL; const char* fontPath = "./data/font.ttf"; SDL_Color fontColor = {99, 140, 222}; SDL_Surface* pFontSurface = NULL; SDL_Rect texteDestination; // Demarre SDL if ( SDL_Init(SDL_INIT_VIDEO) == -1 ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL\n"); return -1; } if ( IMG_Init(imgFlags) != imgFlags ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL_image : '%s'\n",IMG_GetError()); cleanup(); return -1; } if ( TTF_Init() == -1 ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL_TTF : '%s'\n",TTF_GetError()); cleanup(); return -1; } /* Création de la fenêtre */ pWindow = SDL_CreateWindow("Ma première application SDL2",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); if ( pWindow != NULL ) { pImage = IMG_Load(imagePath); if ( pImage == NULL ) { fprintf(stderr,"Erreur de chargement de l'image %s : %s\n",imagePath,IMG_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -3; } // Charge la police pFont = TTF_OpenFont(fontPath,32); if ( pFont == NULL ) { fprintf(stderr,"Erreur de chargement de la police %s : %s\n",fontPath,TTF_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -3; } // Genere la SDL_Surface a partir de la police pFontSurface = TTF_RenderText_Solid(pFont,"Developpez.com",fontColor); if ( !pFontSurface ) { fprintf(stderr,"Erreur pour generer le texte '%s'\n",TTF_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -4; } // Une fois l'image chargée, nous pouvons calculer une position relative à celle-ci // Nous centrons l'image dans la fenêtre blitDestination.x = windowWidth/2 - pImage->w/2; blitDestination.y = windowHeight/2 - pImage->h/2; blitDestination.w = pImage->w; blitDestination.h = pImage->h; // Nous avons notre surface pour le texte donc nous calculons la position relative // Le texte est à un quart de la hauteur de l'ecran texteDestination.x = windowWidth/2 - pFontSurface->w/2; texteDestination.y = windowHeight/4; texteDestination.w = pFontSurface->w; texteDestination.h = pFontSurface->h; // Boucle principale while ( mustContinue ) { // Affiche le logo au centre de la fenêtre if ( SDL_BlitSurface(pImage,NULL,SDL_GetWindowSurface(pWindow),&blitDestination) != 0 ) { fprintf(stderr,"Erreur de copie de la surface sur l'écran\n"); mustContinue=0; } // Affiche le texte if ( SDL_BlitSurface(pFontSurface,NULL,SDL_GetWindowSurface(pWindow),&texteDestination) != 0 ) { fprintf(stderr,"Erreur de copie du texte sur l'écran\n"); mustContinue=0; } SDL_UpdateWindowSurface(pWindow); SDL_Event event; SDL_WaitEvent(&event); // Detecte si on clique sur la croix if( event.type == SDL_QUIT ) { //On quitte le programme mustContinue = 0; } // Detecte si une touche est appuyee else if( event.type == SDL_KEYDOWN ) { if ( event.key.keysym.sym == SDLK_ESCAPE ) { mustContinue = 0; } } } SDL_DestroyWindow(pWindow); SDL_FreeSurface(pFontSurface); TTF_CloseFont(pFont); SDL_FreeSurface(pImage); } else { fprintf(stderr,"Erreur de création de la fenêtre: %s\n",SDL_GetError()); cleanup(); return -3; } cleanup(); return 0; }
int main(void) { // int good = 0; // int numeroMap = 0; // do{ // printf("Quelle map?\n"); // printf("1 - Original\n"); // printf("2 - Hard\n"); // printf("3 - Lol\n"); // printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n"); // scanf("%d", &numeroMap); // switch(numeroMap){ // case 1: // loadMap("../projec/map/original.map"); // good = 1; // break; // case 2: // loadMap("../projec/map/hard.map"); // good = 1; // break; // case 3: // loadMap("../projec/map/maplol.map"); // good = 1; // break; // case 4: // loadMap("../projec/map/rdastn.map"); // good = 1; // break; // case 42: // loadMap("../projec/map/rdastn.map"); // good = 1; // setQ(); // break; // } // }while(!good); //Create SDL objects SDL_Window *window = 0; SDL_Event event; SDL_Renderer *renderer = 0; int terminate = 0; //Initialise SDL if(SDL_Init(SDL_INIT_VIDEO) < 0){ printf("Error with SDL : %s\n", SDL_GetError()); SDL_Quit(); return EXIT_FAILURE; } window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN); terminate = 0; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg"); SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu); SDL_FreeSurface(menu); SDL_RenderClear(renderer); int x, y; while(!terminate){ SDL_Rect dest = {0, 0, 544, 344}; SDL_RenderCopy(renderer, menuTexture, NULL, &dest); SDL_RenderPresent(renderer); SDL_WaitEvent(&event); switch(event.type){ case SDL_MOUSEBUTTONDOWN: x = event.motion.x; y = event.motion.y; if(x >= 57 && x <= (57+54) && y >= 94 && y <= (94 + 74)){ loadMap("../projec/map/original.map"); terminate = 1; } if(x >= 124 && x <= (124+53) && y >= 208 && y <= (208 + 73)){ loadMap("../projec/map/hard.map"); terminate = 1; } if(x >= 221 && x <= (221+59) && y >= 95 && y <= (95 + 80)){ loadMap("../projec/map/maplol.map"); terminate = 1; } if(x >= 311 && x <= (311+63) && y >= 208 && y <= (208 + 76)){ loadMap("../projec/map/rdastn.map"); terminate = 1; } if(x >= 350 && x <= (350+124) && y >= 73 && y <= (73 + 109)){ loadMap("../projec/map/rdastn.map"); terminate = 1; setQ(); } break; } SDL_Delay(1000 / FPS); } SDL_DestroyTexture(menuTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); //Search the pacman on the map and create him Pacman *pacman = getPacmanInstance(); unsigned int initialX = pacman->x; unsigned int initialY = pacman->y; Map *map = getMapInstance(); //If the pacman is not found if(!pacman){ printf("Pacman not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Pacman found !\n"); Ghost *clyde = searchAndCreateGhost(CLYDE); if(!clyde){ printf("Clyde not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Clyde found !\n"); Ghost *blinky = searchAndCreateGhost(BLINKY); if(!blinky){ printf("Blinky not found on map\n"); freeMap(map); freeGhost(clyde); exit(EXIT_FAILURE); } printf("Blinky found !\n"); Ghost *inky = searchAndCreateGhost(INKY); if(!inky){ printf("Inky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); exit(EXIT_FAILURE); } printf("Inky found !\n"); Ghost *pinky = searchAndCreateGhost(PINKY); if(!pinky){ printf("Pinky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); exit(EXIT_FAILURE); } printf("Pinky found !\n"); printf("SDL initialisation\n"); if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){ printf("%s", Mix_GetError()); } Mix_Music *music = NULL; music = Mix_LoadMUS("../projec/pacman.wav"); if(!music){ printf("Erreur de chargement de la musique %s \n", Mix_GetError()); }else{ Mix_VolumeMusic(MIX_MAX_VOLUME); Mix_PlayMusic(music, -1); } if(TTF_Init() == -1){ printf("Error during TTF initialization : %s\n", TTF_GetError()); } TTF_Font *police = NULL; police = TTF_OpenFont("../projec/monof.ttf", 65); if(!police){ printf("Error during font load : %s\n", TTF_GetError()); } SDL_Color color = { 255, 255, 255, 255}; //Create the window window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN); //If there is an error if(window == 0){ printf("Error during window creation : %s \n", SDL_GetError()); SDL_Quit(); freeMap(map); return EXIT_FAILURE; } int j; printf("SDL init success\n"); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //NEED gerer erreurs loadTextures(renderer); SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color); SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score); SDL_FreeSurface(score); char scoreString[15]; SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_Surface *scoreN; SDL_Texture *scoreTN; int open = 0; int konami[10] = {0,0,0,0,0,0,0,0,0,0}; //Infinite loop until we want to stop the game terminate = 0; while(!terminate){ SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20}; sprintf(scoreString, "%d", pacman->point); scoreN = TTF_RenderText_Solid(police, scoreString, color); scoreTN = SDL_CreateTextureFromSurface(renderer, score); renderMap(renderer); open = renderPacman(open, renderer); renderClyde(clyde, renderer); renderBlinky(blinky, renderer); renderPinky(pinky, renderer); renderInky(inky, renderer); changeDirectionGhost(blinky); changeDirectionGhost(clyde); changeDirectionGhost(inky); changeDirectionGhost(pinky); SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_RenderCopy(renderer, scoreTN, NULL, &dest2); SDL_RenderPresent(renderer); //Event handling SDL_PollEvent(&event); switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.scancode){ case SDL_SCANCODE_UP: setPacmanDirection(NORTH); if(konami[0]){ if(konami[1]){ for(j = 0 ; j < 10 ; j++){ konami[j] = 0; } // printf("Déjà deux\n"); }else{ konami[1] = 1; } }else{ konami[0] = 1; } break; case SDL_SCANCODE_DOWN: setPacmanDirection(SOUTH); break; case SDL_SCANCODE_RIGHT: setPacmanDirection(EAST); break; case SDL_SCANCODE_LEFT: setPacmanDirection(WEST); break; default: break; } break; } terminate = update(clyde, blinky, inky, pinky); if(terminate){ if(pacman->life > 0 ){ pacman->life--; terminate = 0; pacman->x = initialX; pacman->y = initialY; } } if(event.window.event == SDL_WINDOWEVENT_CLOSE){ terminate = 1; } SDL_Delay(1000 / FPS); SDL_DestroyTexture(scoreTN); SDL_FreeSurface(scoreN); } printf("Score final : %d\n", pacman->point); Mix_FreeMusic(music); Mix_CloseAudio(); freeTextures(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); SDL_DestroyTexture(scoreT); freePacman(); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); freeGhost(pinky); freeMap(); TTF_CloseFont(police); TTF_Quit(); return EXIT_SUCCESS; }
// // Set video mode // hal_bool SDL2_SetVideoMode(int width, int height, int fs, int mnum) { if(glcontext) { SDL_GL_DeleteContext(glcontext); glcontext = nullptr; } if(mainwindow) { SDL_DestroyWindow(mainwindow); mainwindow = nullptr; } Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_SHOWN; int x = SDL_WINDOWPOS_CENTERED_DISPLAY(mnum); int y = SDL_WINDOWPOS_CENTERED_DISPLAY(mnum); if(fs == 1) flags |= SDL_WINDOW_FULLSCREEN; // if dimensions are zero, then use fullscreen desktop if(!(width && height) || fs == -1) { x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(mnum); y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(mnum); flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; fs = -1; } // set GL 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_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if(!(mainwindow = SDL_CreateWindow("Calico", x, y, width, height, flags))) { // Try resetting previous mode if(width != curscreenwidth || height != curscreenheight || fs != curfullscreen || mnum != curmonitornum) { return SDL2_SetVideoMode(curscreenwidth, curscreenheight, curfullscreen, curmonitornum); } else { hal_platform.fatalError("Failed to set video mode %dx%d (%s)", width, height, SDL_GetError()); } } // set window icon hal_platform.setIcon(); // create GL context if(!(glcontext = SDL_GL_CreateContext(mainwindow))) { hal_platform.fatalError("Failed to create GL context (%s)", SDL_GetError()); } // remember set state SDL_GetWindowSize(mainwindow, &curscreenwidth, &curscreenheight); curfullscreen = fs; curmonitornum = mnum; // calculate game subscreen geometry SDL2_calcSubRect(); // make current and set swap SDL_GL_MakeCurrent(mainwindow, glcontext); SDL2_ToggleGLSwap(HAL_TRUE); // wake up RB system RB_InitDefaultState(); // set orthonormal projection SDL2_setOrthoMode(curscreenwidth, curscreenheight); // update appstate maintenance hal_appstate.updateFocus(); hal_appstate.updateGrab(); return HAL_TRUE; }