int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError()); return 1; } if (TTF_Init() != 0) { fprintf(stderr, "Failed to initialize TTF: %s\n", SDL_GetError()); return 1; } if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096)) { fprintf(stderr, "Failed to load Mixer: %s", SDL_GetError()); } int imgFlags = IMG_INIT_JPG|IMG_INIT_PNG; if(!(IMG_Init(imgFlags) & imgFlags)) { fprintf(stderr,"Failed to initialize Image: %s",SDL_GetError()); } screen = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_BORDERLESS); if (screen == NULL) { fprintf(stderr, "Failed to create window: %s\n", SDL_GetError()); return 1; } renderer = SDL_CreateRenderer(screen, -1, 0); if (renderer == NULL) { fprintf(stderr, "Failed to create renderer: %s\n", SDL_GetError()); return 1; } char* path = buildPath(ASSETS,"fonts/FONT.TTF"); font = TTF_OpenFont(path, 12); if (font == NULL) { fprintf(stderr, "Failed to load font: %s\n",TTF_GetError()); return 1; } free(path); Mix_Music* music = loadMusic(buildPath(ASSETS,"music/song.mp3")); playMusic(music); // Black backround SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); game_init(); if (buffers_init(renderer) != 0) { fprintf(stderr, "Failed to craete buffers: %s", SDL_GetError()); return 1; } curr_buffer = buffer; SDL_Event e; SDL_Rect render_rect; render_rect.x = 0; render_rect.y = 0; render_rect.w = WINDOW_WIDTH; render_rect.h = WINDOW_HEIGHT; bool quit = false; int deltaTime = 0; int currentFrame = SDL_GetTicks(); int lastFrame; int fpsMs = 1000 / MAX_FPS; map_tex = renderMap(renderer, map); camera.x = 0; camera.y = 0; camera.w = WINDOW_WIDTH; camera.h = WINDOW_HEIGHT; while (!quit) { lastFrame = currentFrame; currentFrame = SDL_GetTicks(); deltaTime = currentFrame - lastFrame; renderClear(renderer); update(deltaTime); draw(deltaTime); while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) quit = true; else event(e, deltaTime); } // Reset the target SDL_SetRenderTarget(renderer, NULL); // Copy the buffer SDL_RenderCopy(renderer, curr_buffer, &camera, &render_rect); // Draw the buffer to window SDL_RenderPresent(renderer); // Delay if we are drawing more that 100 fps float delay = fpsMs - deltaTime / 1000; if (delay > 0) SDL_Delay(delay); } SDL_Quit(); return 0; }
/****************************************************************************** * Display BackBuffer Flipping ******************************************************************************/ void display::flip() { SDL_SetRenderDrawColor(pRenderer, 0, 0, 0, 255); SDL_RenderPresent(pRenderer); SDL_RenderClear(pRenderer); }
void _Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Render_to_native_surface < _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data*, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> > ( _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data * & osdp, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> & sfc ) { auto& osd = *osdp; const cairo_filter_t cairoFilter = CAIRO_FILTER_GOOD; auto& data = osd.data; double displayWidth = static_cast<double>(data.display_dimensions.x()); double displayHeight = static_cast<double>(data.display_dimensions.y()); double backBufferWidth = static_cast<double>(data.back_buffer.dimensions.x()); double backBufferHeight = static_cast<double>(data.back_buffer.dimensions.y()); auto backBufferSfc = data.back_buffer.surface.get(); auto displaySfc = data.display_surface.get(); auto displayContext = data.display_context.get(); cairo_surface_flush(backBufferSfc); cairo_set_operator(displayContext, CAIRO_OPERATOR_SOURCE); if (osd.user_scaling_callback != nullptr) { bool letterbox = false; auto userRect = osd.user_scaling_callback(sfc, letterbox); if (letterbox) { if (data._Letterbox_brush == nullopt) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); } else { auto pttn = data._Letterbox_brush.value().data().brush.get(); if (data._Letterbox_brush_props == nullopt) { cairo_pattern_set_extend(pttn, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(pttn, CAIRO_FILTER_GOOD); cairo_matrix_t cPttnMatrix; cairo_matrix_init_identity(&cPttnMatrix); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } else { const basic_brush_props<_Cairo_graphics_surfaces<std::experimental::io2d::v1::_Graphics_math_float_impl>>& props = data._Letterbox_brush_props.value(); cairo_pattern_set_extend(pttn, _Extend_to_cairo_extend_t(props.wrap_mode())); cairo_pattern_set_filter(pttn, _Filter_to_cairo_filter_t(props.filter())); cairo_matrix_t cPttnMatrix; const auto& m = props.brush_matrix(); cairo_matrix_init(&cPttnMatrix, m.m00(), m.m01(), m.m10(), m.m11(), m.m20(), m.m21()); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } } } cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / displayWidth / static_cast<double>(userRect.width()), 1.0 / displayHeight / static_cast<double>(userRect.height())); cairo_matrix_translate(&ctm, -static_cast<double>(userRect.x()), -static_cast<double>(userRect.y())); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { // Calculate the destRect values. switch (data.scl) { case std::experimental::io2d::scaling::letterbox: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::uniform: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::fill_uniform: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; if (widthRatio < heightRatio) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / heightRatio, 1.0 / heightRatio); cairo_matrix_translate(&ctm, trunc(abs((displayWidth - (backBufferWidth * heightRatio)) / 2.0)), 0.0); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / widthRatio); cairo_matrix_translate(&ctm, 0.0, trunc(abs((displayHeight - (backBufferHeight * widthRatio)) / 2.0))); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } } break; case std::experimental::io2d::scaling::fill_exact: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / heightRatio); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } break; case std::experimental::io2d::scaling::none: { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } break; default: { assert("Unexpected _Scaling value." && false); } break; } } // cairo_restore(_Native_context.get()); // This call to cairo_surface_flush is needed for Win32 surfaces to update. cairo_surface_flush(displaySfc); cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); SDL_SetRenderDrawColor(data.renderer, 0, 0, 0, 255); if (SDL_RenderClear(data.renderer) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Copy Cairo canvas to SDL2 texture unsigned char * src = cairo_image_surface_get_data(displaySfc); // TODO([email protected]): compute the pitch, given const int pitch = (int)backBufferWidth * 4; // '4' == 4 bytes per pixel if (SDL_UpdateTexture(data.texture, nullptr, src, pitch) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } if (SDL_RenderCopy(data.renderer, data.texture, nullptr, nullptr) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Present latest image SDL_RenderPresent(data.renderer); }
bool Render::postUpdate() { SDL_SetRenderDrawColor(renderer, background.r, background.g, background.g, background.a); SDL_RenderPresent(renderer); return true; }
bool World::InitScreen() { bool run = true; if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("Fail initialize : %s\n",SDL_GetError()); run = false; } else { printf("Initialization Success!\n"); if(!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1")) { printf("Warning: VSync not enabled!\n"); run = false; } m_window = SDL_CreateWindow(TITLE,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,g_WINDOW_WIDTH,g_WINDOW_HEIGHT,SDL_WINDOW_SHOWN); if(m_window == NULL) { printf("ERROR creting Window : %s\n",SDL_GetError()); run = false; } else { printf("Created Window .\n"); m_render = SDL_CreateRenderer(m_window,-1,SDL_RENDERER_ACCELERATED); if(m_render == NULL) { printf("Failed creating Render : %s\n",SDL_GetError()); run = false; } else { printf("Creted Render.\n"); SDL_SetRenderDrawColor( m_render, 0xFF, 0xFF, 0xFF, 0xFF ); int picFlag = IMG_INIT_PNG; if(!(IMG_Init(picFlag))& picFlag) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); run = false; } else { if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf("Warning: Scale Quality not enabled!\n"); run = false; } else { m_Stick1 = SDL_JoystickOpen(0); if(m_Stick1 == NULL) { printf("Warning: 1st Joystick FAIL\n"); } m_Stick2 = SDL_JoystickOpen(1); if(m_Stick2 == NULL) { printf("Warning: 2nd Joystick FAIL\n"); } if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 4, 4048 ) < 0 ) { printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() ); } } } } } } m_main_music= new Sound(); m_main_music->Init("data/music.txt"); m_main_music->Play(true); SDL_JoystickEventState(SDL_ENABLE); return run; }
void clr(SDL_Renderer* destination, const SDL_Color& col) { SDL_SetRenderDrawColor(destination, col.r, col.g, col.b, col.a); SDL_RenderClear(destination); }
void renderRect( SDL_Rect& rect, const SDL_Color& col, SDL_Renderer* destination, bool filled) { SDL_SetRenderDrawColor(destination, col.r, col.g, col.b, col.a); if(filled) { SDL_RenderFillRect(destination, &rect); } else { SDL_RenderDrawRect(destination, &rect); } }
bool Button::draw(SDL_Renderer* renderer) { /*if(label->isDirty()) { label->draw(); }*/ SDL_Texture *oldTarget = SDL_GetRenderTarget(renderer); SDL_SetRenderTarget(renderer, _texture); SDL_SetRenderDrawColor(renderer, 0,0,0,0); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0,0,0,255); SDL_Rect extents = {0, 0, frame.w, frame.h}; _theme->draw(renderer, &extents); SDL_Rect contentRect; getContentRect(&contentRect); //printf("Content rect: %dx%d%+d%+d\n", contentRect.w, contentRect.h, contentRect.x, contentRect.y); //contentRect.x = padding.x; //contentRect.y = padding.y; //contentRect.w += padding.x + padding.w; //contentRect.h += padding.y + padding.h; //-- SDL_RenderCopy(renderer, label->getTexture(), NULL, &contentRect); /*printf("contentRect.w: %d\n", contentRect.w); int w; SDL_QueryTexture(label->getTexture(), NULL, NULL, &w, NULL); printf("label with: %d\n", w);*/ #if 0 SDL_Point srcPoints[] = { {0, 0}, {padding.x, padding.y}, {w - padding.w, h - padding.h}, {w, h} }; SDL_Point dstPoints[] = { {frame->x, frame->y}, {frame->x + padding.x, frame->y + padding.y}, {frame->x + frame->w - padding.w, frame->y + frame->h - padding.h}, {frame->x + frame->w, frame->y + frame->h} }; for (int y = 0; y < 3; y++ ) { for (int x = 0; x < 3; x++) { SDL_Rect src = { srcPoints[x].x, srcPoints[y].y, srcPoints[x+1].x, srcPoints[y+1].y }; src.w -= src.x; src.h -= src.y; SDL_Rect dst = { dstPoints[x].x, dstPoints[y].y, dstPoints[x+1].x, dstPoints[y+1].y }; dst.w -= dst.x; dst.h -= dst.y; //printf("%d,%d\n", x, y); //printf("src: %dx%d%+d%+d\n", src.w, src.h, src.x, src.y); //printf("dst: %dx%d%+d%+d\n\n", dst.w, dst.h, dst.x, dst.y); /*printf("src: %d+%d+%dx%d dst: %d+%d+%dx%d\n", src.x, src.y, src.w, src.h, dst.x, dst.y, dst.w, dst.h);*/ SDL_RenderCopy(texture, &src, &dst); //SDL_SetRenderDrawColor(renderer, 32+x*32, 32+y*32, 0, 127); //SDL_RenderFillRect(renderer, &dst); } } #endif dirty = false; SDL_SetRenderTarget(renderer, oldTarget); return true; }
update_status ModuleRender::PostUpdate() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderPresent(renderer); return update_status::UPDATE_CONTINUE; }
int main( int argc, char** argv ) { // Create the hidden program options (required args) boost::program_options::options_description hidden( "Hidden options" ); hidden.add_options() ("image", boost::program_options::value<std::string>(), "the image (with path) that will be used\n"); // Create the positional (required) args boost::program_options::positional_options_description pd; pd.add("image", 1 ); // Create the optional arguments boost::program_options::options_description generic( "Allowed options" ); generic.add_options() ("help,h", "produce help message") ("color_key_red,r", boost::program_options::value<unsigned>(), "the color key red value (0-255)\n") ("color_key_green,g", boost::program_options::value<unsigned>(), "the color key green value (0-255)\n") ("color_key_blue,b", boost::program_options::value<unsigned>(), "the color key blue value (0-255)\n"); // Create the command-line argument parser boost::program_options::options_description cmdline_options( "Allowed options" ); cmdline_options.add(generic).add(hidden); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pd).run(), vm ); boost::program_options::notify( vm ); // Check if the help message was requested if( vm.count( "help" ) ) { std::cerr << cmdline_options << std::endl; return 1; } // Store the image name std::string image_name; if( vm.count( "image" ) ) image_name = vm["image"].as<std::string>(); else { std::cerr << "The image (with path) must be specified." << std::endl; return 1; } // Store the color key rgb values unsigned char color_key_r = 255, color_key_g = 255, color_key_b = 255; if( vm.count( "color_key_red" ) ) color_key_r = vm["color_key_red"].as<unsigned>(); if( vm.count( "color_key_green" ) ) color_key_g = vm["color_key_green"].as<unsigned>(); if( vm.count( "color_key_blue" ) ) color_key_b = vm["color_key_blue"].as<unsigned>(); // Initialize the window if( !initialize() ) return 1; else { // Load the bitmap if( !loadMedia( image_name, color_key_r, color_key_g, color_key_b ) ) return 1; else { bool quit = false; // The event SDL_Event event; // The current animation frame int frame = 0; // Main application loop while( !quit ) { while( SDL_PollEvent( &event ) != 0 ) { if( event.type == SDL_QUIT ) quit = true; } // Clear the screen SDL_SetRenderDrawColor( g_renderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( g_renderer ); // Render the current frame SDL_Rect* current_clip = &g_sprite_clips[frame/4]; g_sprite_sheet_texture.render( (screen_width_height[0] - current_clip->w)/2, (screen_width_height[1] - current_clip->h)/2, current_clip ); // Update the screen SDL_RenderPresent( g_renderer ); // Increment the frame ++frame; // Reset animation if( frame/4 >= g_frames ) frame = 0; } } } // Close program close(); return 0; }
int main(int argc, char *argv[]) { SDL_Window *window; CLC_CONFIG config; Uint8 *kbdstate; SDL_Event e; PLAYER *me; PLAYER *player; Uint32 time; IPaddress srv_ip; TCPsocket srv_sock; Uint16 magic; int i; SDLNet_SocketSet srv_sset; char myname[PNAME_SIZE]; unsigned char myno; if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_EVENTS) == -1) { fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } if (SDLNet_Init() == -1) { fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } parsecfg(&config); /* * Get player name. */ printf("Wow such name: "); fgets(myname, PNAME_SIZE, stdin); for (i = 0; i < PNAME_SIZE; i++) { if (myname[i] == '\n') { myname[i] = '\0'; break; } } /* * Connect to server! */ if (SDLNet_ResolveHost(&srv_ip, config.defaultsrv, atoi(config.defaultport))) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } /* * Bind socket! */ if (!(srv_sock = SDLNet_TCP_Open(&srv_ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } /* * Add (a single) server socket to srv_sset for cheap hack for checking * the server socket's state. */ srv_sset = SDLNet_AllocSocketSet(1); if (!srv_sset) { printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } SDLNet_TCP_AddSocket(srv_sset, srv_sock); /* * Get maze, add connecting players to buffer and wait until the game * begins. */ getmaze(srv_sock); window = SDL_CreateWindow( "MAZE OF TORMENT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, config.win_width, config.win_height, config.win_flags ); SDL_GetWindowSize(window, &config.win_width, &config.win_height); if (window == NULL) { fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } renderer = SDL_CreateRenderer(window, -1, config.renderflags); hsprite = loadPic("img/predator.gif"); psprite = loadPic("img/prey.gif"); black = loadPic("img/black.gif"); /* * Initialize maze, and send player name. */ MAZE.X = (config.win_width - MAZE.w * 16) / 2; MAZE.Y = (config.win_height - MAZE.h * 16) / 2; SDLNet_TCP_Send(srv_sock, myname, PNAME_SIZE); /* * Initialize maze and get the LOCAL player, then the REMOTE players. */ SDLNet_TCP_Recv(srv_sock, &myno, 1); player = calloc(1, sizeof(PLAYER)); if (!((magic = getshort(srv_sock)) == ADD_PLAYER)) { printf("server not sending players\n!"); exit(EXIT_FAILURE); } unsigned char hunter = addp(player, srv_sock); choose_hunter(player, hunter); me = choose_player(player, myno); SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); draw_maze(MAZE.X, MAZE.Y); PLAYER *temp; for (temp = player->next; temp != NULL; temp = temp->next) { printf("drew player %d\n", temp->playerno); drawPlayer(temp); } printf("starting game!!\n"); /* * Game loop! */ for (;;) { time = SDL_GetTicks(); /* * Poll the network in each frame. Because. */ int result, numready = SDLNet_CheckSockets(srv_sset, 0); if (numready == -1) { printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError()); perror("SDLNet_CheckSockets"); } else if (numready) { unsigned char packet; unsigned char pnum, movx, movy; printf("srv socket is ready!!\n"); if ((result = SDLNet_TCP_Recv(srv_sock, &packet, 2)) == 2) { switch (SDLNet_Read16(&packet)) { case PLAYER_MOV: puts("PLAYER_MOV"); pnum = getshort(srv_sock); movx = getshort(srv_sock); movy = getshort(srv_sock); printf("player %d moved to (%d,%d)\n", pnum, movx, movy); movePlayer(choose_player(player,pnum), movx, movy); break; case PLAYER_WIN: puts("PLAYER_WIN"); break; case PLAYER_DC: puts("PLAYER_DC"); pnum = getshort(srv_sock); printf("Player %d disconnected!!\n", pnum); removep(choose_player(player,pnum)); break; case PLAYER_DIE: puts("PLAYER_DIE"); pnum = getshort(srv_sock); if (pnum == myno) { puts("YOU ARE DEAD\nGAME OVER"); goto exit; } printf("Player %d deaded!!!!!\n", pnum); removep(choose_player(player, pnum)); break; } } else if (result <= 0) { fprintf(stderr, "SDLNet_TCP_Recv: %s\n", SDLNet_GetError()); fprintf(stderr, "Lost connection to the server?\n"); break; } } /* * Poll for keys */ if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { break; } kbdstate = (Uint8 *) SDL_GetKeyboardState(NULL); if (kbdstate[SDL_SCANCODE_Q]) { break; } local_player_update(srv_sock, me, player, SDL_GetKeyboardState(NULL)); } SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); SDL_RenderPresent(renderer); if (20 > (SDL_GetTicks() - time)) { SDL_Delay(20 - (SDL_GetTicks() - time)); } } exit: SDL_DestroyTexture(psprite.texture); SDL_DestroyTexture(hsprite.texture); SDL_DestroyTexture(black.texture); free(player); free(MAZE.data); SDL_DestroyWindow(window); SDLNet_Quit(); SDL_Quit(); return 0; }
//! initialize sdl window bool initialize() { // Initialization flag bool success = true; // Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { std::cerr << "SDL could not initialize. SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { std::cerr << "Warning: Linear texture filtering not enabled!" << std::endl; } // Create window g_window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width_height[0], screen_width_height[1], SDL_WINDOW_SHOWN ); if( g_window == NULL ) { std::cerr << "Window could not be created. SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Create the renderer for the window g_renderer = SDL_CreateRenderer( g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if( g_renderer == NULL ) { std::cerr << "Renderer could not be created! SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Initialize renderer color SDL_SetRenderDrawColor( g_renderer, 0xFF, 0xFF, 0xFF, 0xFF ); // Initialize PNG loading int img_flags = IMG_INIT_PNG; if( !( IMG_Init( img_flags ) & img_flags ) ) { std::cerr << "SDL_image extension could not initialize! " << "SDL_image Error: " << IMG_GetError() << std::endl; success = false; } } } } return success; }
// load the surface from a .pbm or bitmap file bool NXSurface::LoadImage(const char *pbm_name, bool use_colorkey, int use_display_format) { stat("NXSurface::LoadImage name = %s, this = %p", pbm_name, this); SDL_Surface *image; Free(); // if (use_display_format == -1) // { // use value specified in settings // use_display_format = settings->displayformat; // } image = SDL_LoadBMP_RW(SDL_RWFromFP(fileopenRO(pbm_name), SDL_TRUE), 1); if (!image) { staterr("NXSurface::LoadImage: load failed of '%s'!", pbm_name); return 1; } if (use_colorkey) { SDL_SetColorKey(image, SDL_TRUE, SDL_MapRGB(image->format, 0, 0, 0)); } SDL_Texture * tmptex = SDL_CreateTextureFromSurface(renderer, image); if (!tmptex) { staterr("NXSurface::LoadImage: SDL_CreateTextureFromSurface failed: %s", SDL_GetError()); SDL_FreeSurface(image); return 1; } SDL_FreeSurface(image); { int wd, ht, access; Uint32 format; NXFormat nxformat; if (SDL_QueryTexture(tmptex, &format, &access, &wd, &ht)) goto error; nxformat.format = format; if (AllocNew(wd, ht, &nxformat)) goto error; if (SDL_SetTextureBlendMode(tmptex, SDL_BLENDMODE_MOD)) goto error; if (SDL_SetRenderTarget(renderer, fTexture)) goto error; if (SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255)) goto error; if (SDL_RenderClear(renderer)) goto error; if (SDL_RenderCopy(renderer, tmptex, NULL, NULL)) goto error; if (SDL_SetRenderTarget(renderer, NULL)) goto error; if (SDL_SetTextureBlendMode(fTexture, SDL_BLENDMODE_BLEND)) goto error; SDL_DestroyTexture(tmptex); goto done; error: { staterr("NXSurface::LoadImage failed: %s", SDL_GetError()); if (tmptex) { SDL_DestroyTexture(tmptex); tmptex = NULL; } if (fTexture){ SDL_DestroyTexture(fTexture); fTexture = NULL; } SDL_SetRenderTarget(renderer, NULL); } done: ; } stat("NXSurface::LoadImage name = %s, this = %p done", pbm_name, this); return (fTexture == NULL); }
void draw_HUD(SDL_Renderer* ren) { //Draw the top bar SDL_SetRenderDrawColor(ren, 255, 255, 255, 0); top_bar.w = window_size_x; SDL_RenderFillRect(ren, &top_bar); draw_int(ren, font, top_bar_text_color, 20, 0, reqired_power, "Required: ", " MW"); draw_int(ren, font, top_bar_text_color, 20, 20, power_avalible, "Avalible: ", " MW"); draw_int(ren, font, top_bar_text_color, 200, 00, getBalance(), "£", "000"); draw_int(ren, font, top_bar_text_color, 200, 20, lastBalanceChange, "£", "000"); draw_int(ren, font, top_bar_text_color, 400, 0, getPopulation(), "Pop: ", ""); fill_scale_values(); public_happiness_scale.x = window_size_x-100-80; draw_scale(ren, &public_happiness_scale, scale_values.average); //Draw the side bar if(show_sidebar) { SDL_SetRenderDrawColor(ren, 255, 255, 255, 0); side_bar.x = window_size_x - side_bar.w; SDL_RenderFillRect(ren, &side_bar); SDL_Rect scaleBox = {window_size_x-100-5,0,100,fontSizeLarge+2}; int item_y = side_bar.y+5; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_POLICE_start); scaleBox.y = item_y; draw_scale(ren, &scaleBox, scale_values.police); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_HEALTH_start); setColorGoodBad(ren, scale_values.health); scaleBox.y = item_y; SDL_RenderFillRect(ren, &scaleBox); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_EDUCATION_start); setColorGoodBad(ren, populationPerSchool() < target_population_per_school); scaleBox.y = item_y; draw_scale(ren, &scaleBox, scale_values.education); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_SHOPPING_start); setColorGoodBad(ren, scale_values.shopping); scaleBox.y = item_y; SDL_RenderFillRect(ren, &scaleBox); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_POWER_start); scaleBox.y = item_y; draw_scale(ren, &scaleBox, scale_values.power); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_WASTE_start); scaleBox.y = item_y; draw_scale(ren, &scaleBox, scale_values.waste); item_y += fontSizeLarge+2; draw_string(ren, fontLarge, top_bar_text_color, side_bar.x+5, item_y, &_binary_VALUE_TEXT_POLUTION_start); scaleBox.y = item_y; draw_scale(ren, &scaleBox, scale_values.polution); } SDL_SetRenderDrawColor(ren, 0, 0, 0, 0); SDL_Rect open_menu_button = {window_size_x-30,0,30,30}; SDL_RenderFillRect(ren, &open_menu_button); char* modeText = NULL; switch(getMode()) { case MODE_BUILD_RESIDENTIAL_1: modeText = &_binary_MODE_TEXT_RESIDENTIAL_1_start; break; case MODE_BUILD_RESIDENTIAL_2: modeText = &_binary_MODE_TEXT_RESIDENTIAL_2_start; break; case MODE_BUILD_ROAD: modeText = &_binary_MODE_TEXT_BUILD_ROAD_start; break; case MODE_BUILD_POWER_GAS: modeText = &_binary_MODE_TEXT_BUILD_POWER_GAS_start; break; case MODE_BUILD_DESTROY: modeText = &_binary_MODE_TEXT_DESTROY_start; break; case MODE_BUILD_RETAIL: modeText = &_binary_MODE_TEXT_BUILD_RETAIL_start; break; case MODE_BUILD_HOSPITAL: modeText = &_binary_MODE_TEXT_BUILD_HOSPITAL_start; break; case MODE_BUILD_POWER_SOLAR: modeText = &_binary_MODE_TEXT_BUILD_POWER_SOLAR_start; break; default: break; } if(modeText != NULL) { draw_string(ren, font, top_bar_text_color, 5, window_size_y-15, modeText); } if(ready_to_place) { SDL_SetRenderDrawColor(ren, 255, 255, 255, 0); SDL_RenderFillRect(ren, &planned_cost_box); draw_int(ren, font, top_bar_text_color, 200, 35, costOfPlannedBuild(), "(-£", "000)"); } SDL_SetRenderDrawColor(ren, 0, 0, 0, 0); draw_menu(ren); if(active_emergency()) { Point p = {window_size_x-16, 80}; drawTile(ren, &p, getClip(SPRITE_BUILD_BACKGROUND)); drawTile(ren, &p, getClip(SPRITE_BUILD_SERVICES_POLICE)); } }
SDL_bool WatchGameController(SDL_GameController * gamecontroller) { 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_Window *window = NULL; retval = SDL_FALSE; done = SDL_FALSE; 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); SDL_free(title); title = NULL; 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! */ #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg(loop, gamecontroller, 0, 1); #else while (!done) { loop(gamecontroller); } #endif SDL_DestroyRenderer(screen); screen = NULL; background = NULL; button = NULL; axis = NULL; SDL_DestroyWindow(window); return retval; }
void WPR_render_circle(WPR_sdl_data* data,GEO_vec2 pos,float radius,WPR_color color){ SDL_RenderSetScale(data->renderer,1,1); SDL_SetRenderDrawColor(data->renderer,color.r*255,color.g*255,color.b*255,color.a*255); SDL_RenderDrawPoint(data->renderer,WPR_units_x_to_pixel(data,pos.x),WPR_units_y_to_pixel(data,pos.y)); SDL_RenderSetScale(data->renderer,data->scale_x,data->scale_y); }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //Set text color as black SDL_Color textColor = { 0, 0, 0, 255 }; //The frames per second timer LTimer* fpsTimer = LTimer_create(); //The frames per second cap timer LTimer* capTimer = LTimer_create(); //In memory text stream //std::stringstream timeText; int buffSize = 45; char buff[buffSize]; //initialise gFPSTextTexture gFPSTextTexture = LTexture_create(); //Start counting frames per second int countedFrames = 0; LTimer_start(fpsTimer); //While application is running while( !quit ) { //Start cap timer LTimer_start(capTimer); //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } } //Calculate and correct fps float avgFPS = countedFrames / ( LTimer_getTicks(fpsTimer) / 1000.f ); if( avgFPS > 2000000 ) { avgFPS = 0; } //Set text to be rendered //timeText.str( "" ); //timeText << "Average Frames Per Second (With Cap) " << avgFPS; if(snprintf(buff, buffSize, "Average Frames Per Second (With Cap) %.f", avgFPS)>buffSize) { printf("balls, we have a buffer overflow here"); } else { //Render text if( !LTexture_loadFromRenderedText(gFPSTextTexture, gRenderer, buff, gFont, textColor ) ) { printf( "Unable to render FPS texture!\n" ); } //Clear screen SDL_SetRenderDrawColor( gRenderer, COLOUR_BLACK ); SDL_RenderClear( gRenderer ); //Render textures LTexture_render(gFPSTextTexture, gRenderer, ( SCREEN_WIDTH - LTexture_getWidth(gFPSTextTexture)) / 2, ( SCREEN_HEIGHT - LTexture_getHeight(gFPSTextTexture) ) / 2, NULL, 0, NULL, 0 ); } //Update screen SDL_RenderPresent( gRenderer ); ++countedFrames; //If frame finished early int frameTicks = LTimer_getTicks(capTimer); if( frameTicks < SCREEN_TICK_PER_FRAME ) { //Wait remaining time SDL_Delay( SCREEN_TICK_PER_FRAME - frameTicks ); } } LTimer_destroy(fpsTimer); LTimer_destroy(capTimer); } } //Free resources and close SDL close(); return 0; }
void WPR_render_clear(WPR_sdl_data* data){ SDL_RenderPresent(data->renderer); SDL_SetRenderDrawColor(data->renderer,0,0,0,0xFF); SDL_RenderClear(data->renderer); }
void renderRect( int x, int y, int w, int h, const SDL_Color& col, SDL_Renderer* destination, bool filled) { SDL_SetRenderDrawColor(destination, col.r, col.g, col.b, col.a); SDL_Rect rect; rect.x = x; rect.y = y; rect.w = w; rect.h = h; if(filled) { SDL_RenderFillRect(destination, &rect); } else { SDL_RenderDrawRect(destination, &rect); } }
SDL_Texture* GbQueueRenderer::renderQueue() { SDL_SetRenderTarget(_SDLRenderer, _texture); SDL_SetRenderDrawColor(_SDLRenderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(_SDLRenderer); SDL_Rect pos = { 0, 120, 38, 8 }; for (auto it = _board.getGarbageQueue().begin(); it != _board.getGarbageQueue().end(); ++it) { if (it->spawnTimer <= 0) { SDL_SetTextureColorMod(_spriteSheet, 0x50, 0x50, 0x50); } else { SDL_SetTextureColorMod(_spriteSheet, 0xFF, 0xFF, 0xFF); } SDL_Rect sprite = { 0, 305, 38, 8 }; if (!it->fullWidth || (it->fullWidth && it->size == 1)) { pos.y -= 8; if (it->fullWidth) { sprite.y -= (3 - 6) * 8; } else { sprite.y -= (3 - it->size) * 8; } SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); pos.y -= 2; } else if (it->fullWidth && it->size > 1) { pos.y -= 14; pos.h = 14; sprite = {0,337,38,14}; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); pos.y += 2; pos.x += 12; pos.w = 6; pos.h = 10; sprite = {0,351,6,10}; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); //x //digits pos.x += 6; pos.w = 7; sprite.w = 7; if (it->size < 10) { sprite.x = 5 + (it->size - 1) * 7; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); } else if (it->size == 11) { sprite.x = 5 + 0 * 7; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); pos.x += 7; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); } else if (it->size == 12) { sprite.x = 5 + 0 * 7; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); pos.x += 7; sprite.x = 5 + 1 * 7; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); } pos.x = 0; pos.y -= 2 + 2; pos.h = 8; pos.w = 38; } } SDL_SetTextureColorMod(_spriteSheet, 0xFF, 0xFF, 0xFF); return _texture; }
//Starts up SDL and creates window bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create vsynced renderer for window // gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); //Create renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); success = false; } //Initialize SDL_ttf if( TTF_Init() == -1 ) { printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } } } } return success; }
/** * @brief Tests the SDL primitives for rendering. * * \sa * http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor * http://wiki.libsdl.org/moin.cgi/SDL_RenderFillRect * http://wiki.libsdl.org/moin.cgi/SDL_RenderDrawLine * */ int render_testPrimitives (void *arg) { int ret; int x, y; SDL_Rect rect; SDL_Surface *referenceSurface = NULL; int checkFailCount1; int checkFailCount2; /* Need drawcolor or just skip test. */ SDLTest_AssertCheck(_hasDrawColor(), "_hasDrawColor"); /* Draw a rectangle. */ rect.x = 40; rect.y = 0; rect.w = 40; rect.h = 80; ret = SDL_SetRenderDrawColor(renderer, 13, 73, 200, SDL_ALPHA_OPAQUE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, &rect ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); /* Draw a rectangle. */ rect.x = 10; rect.y = 10; rect.w = 60; rect.h = 40; ret = SDL_SetRenderDrawColor(renderer, 200, 0, 100, SDL_ALPHA_OPAQUE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, &rect ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); /* Draw some points like so: * X.X.X.X.. * .X.X.X.X. * X.X.X.X.. */ checkFailCount1 = 0; checkFailCount2 = 0; for (y=0; y<3; y++) { for (x = y % 2; x<TESTRENDER_SCREEN_W; x+=2) { ret = SDL_SetRenderDrawColor(renderer, x*y, x*y/2, x*y/3, SDL_ALPHA_OPAQUE ); if (ret != 0) checkFailCount1++; ret = SDL_RenderDrawPoint(renderer, x, y ); if (ret != 0) checkFailCount2++; } } SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1); SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_RenderDrawPoint, expected: 0, got: %i", checkFailCount2); /* Draw some lines. */ ret = SDL_SetRenderDrawColor(renderer, 0, 255, 0, SDL_ALPHA_OPAQUE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor"); ret = SDL_RenderDrawLine(renderer, 0, 30, TESTRENDER_SCREEN_W, 30 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawColor(renderer, 55, 55, 5, SDL_ALPHA_OPAQUE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_RenderDrawLine(renderer, 40, 30, 40, 60 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawColor(renderer, 5, 105, 105, SDL_ALPHA_OPAQUE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_RenderDrawLine(renderer, 0, 0, 29, 29 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); ret = SDL_RenderDrawLine(renderer, 29, 30, 0, 59 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); ret = SDL_RenderDrawLine(renderer, 79, 0, 50, 29 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); ret = SDL_RenderDrawLine(renderer, 79, 59, 50, 30 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret); /* See if it's the same. */ referenceSurface = SDLTest_ImagePrimitives(); _compare(referenceSurface, ALLOWABLE_ERROR_OPAQUE ); /* Clean up. */ SDL_FreeSurface(referenceSurface); referenceSurface = NULL; return TEST_COMPLETED; }
void Window::setRendererColor(Color color) { SDL_SetRenderDrawColor(m_renderer, color.r, color.g, color.b, color.a); }
/** * @brief Tests the SDL primitives with alpha for rendering. * * \sa * http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor * http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawBlendMode * http://wiki.libsdl.org/moin.cgi/SDL_RenderFillRect */ int render_testPrimitivesBlend (void *arg) { int ret; int i, j; SDL_Rect rect; SDL_Surface *referenceSurface = NULL; int checkFailCount1; int checkFailCount2; int checkFailCount3; /* Need drawcolor and blendmode or just skip test. */ SDLTest_AssertCheck(_hasDrawColor(), "_hasDrawColor"); SDLTest_AssertCheck(_hasBlendModes(), "_hasBlendModes"); /* Create some rectangles for each blend mode. */ ret = SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, NULL ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); rect.x = 10; rect.y = 25; rect.w = 40; rect.h = 25; ret = SDL_SetRenderDrawColor(renderer, 240, 10, 10, 75 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, &rect ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); rect.x = 30; rect.y = 40; rect.w = 45; rect.h = 15; ret = SDL_SetRenderDrawColor(renderer, 10, 240, 10, 100 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, &rect ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); rect.x = 25; rect.y = 25; rect.w = 25; rect.h = 25; ret = SDL_SetRenderDrawColor(renderer, 10, 10, 240, 125 ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret); ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret); ret = SDL_RenderFillRect(renderer, &rect ); SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret); /* Draw blended lines, lines for everyone. */ checkFailCount1 = 0; checkFailCount2 = 0; checkFailCount3 = 0; for (i=0; i<TESTRENDER_SCREEN_W; i+=2) { ret = SDL_SetRenderDrawColor(renderer, 60+2*i, 240-2*i, 50, 3*i ); if (ret != 0) checkFailCount1++; ret = SDL_SetRenderDrawBlendMode(renderer,(((i/2)%3)==0) ? SDL_BLENDMODE_BLEND : (((i/2)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE ); if (ret != 0) checkFailCount2++; ret = SDL_RenderDrawLine(renderer, 0, 0, i, 59 ); if (ret != 0) checkFailCount3++; } SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1); SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2); SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawLine, expected: 0, got: %i", checkFailCount3); checkFailCount1 = 0; checkFailCount2 = 0; checkFailCount3 = 0; for (i=0; i<TESTRENDER_SCREEN_H; i+=2) { ret = SDL_SetRenderDrawColor(renderer, 60+2*i, 240-2*i, 50, 3*i ); if (ret != 0) checkFailCount1++; ret = SDL_SetRenderDrawBlendMode(renderer,(((i/2)%3)==0) ? SDL_BLENDMODE_BLEND : (((i/2)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE ); if (ret != 0) checkFailCount2++; ret = SDL_RenderDrawLine(renderer, 0, 0, 79, i ); if (ret != 0) checkFailCount3++; } SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1); SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2); SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawLine, expected: 0, got: %i", checkFailCount3); /* Draw points. */ checkFailCount1 = 0; checkFailCount2 = 0; checkFailCount3 = 0; for (j=0; j<TESTRENDER_SCREEN_H; j+=3) { for (i=0; i<TESTRENDER_SCREEN_W; i+=3) { ret = SDL_SetRenderDrawColor(renderer, j*4, i*3, j*4, i*3 ); if (ret != 0) checkFailCount1++; ret = SDL_SetRenderDrawBlendMode(renderer, ((((i+j)/3)%3)==0) ? SDL_BLENDMODE_BLEND : ((((i+j)/3)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE ); if (ret != 0) checkFailCount2++; ret = SDL_RenderDrawPoint(renderer, i, j ); if (ret != 0) checkFailCount3++; } } SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1); SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2); SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawPoint, expected: 0, got: %i", checkFailCount3); /* See if it's the same. */ referenceSurface = SDLTest_ImagePrimitivesBlend(); _compare(referenceSurface, ALLOWABLE_ERROR_BLENDED ); /* Clean up. */ SDL_FreeSurface(referenceSurface); referenceSurface = NULL; return TEST_COMPLETED; }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //Modulation component Uint8 a = 255; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //Handle key presses else if( e.type == SDL_KEYDOWN ) { //Increase alpha on w if( e.key.keysym.sym == SDLK_w ) { //Cap if over 255 if( a + 32 > 255 ) { a = 255; } //Increment otherwise else { a += 32; } } //Decrease alpha on s else if( e.key.keysym.sym == SDLK_s ) { //Cap if below 0 if( a - 32 < 0 ) { a = 0; } //Decrement otherwise else { a -= 32; } } } } //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render background gBackgroundTexture.render( 0, 0 ); //Render front blended gModulatedTexture.setAlpha( a ); gModulatedTexture.render( 0, 0 ); //Update screen SDL_RenderPresent( gRenderer ); } } } //Free resources and close SDL close(); return 0; }
int main(int argc, const char* const argv[]) { srand(time(NULL)); if (SDL_Init(SDL_INIT_VIDEO) != 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } atexit(SDL_Quit); if (IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL2 image: %s\n", IMG_GetError()); exit(EXIT_FAILURE); } atexit(IMG_Quit); SDL_Window* window = NULL; SDL_Renderer* renderer = NULL; if (SDL_CreateWindowAndRenderer(640, 480, SDL_WINDOW_SHOWN, &window, &renderer) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_Surface* icon = IMG_Load("resources/iconzilla.png"); if (!icon) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load icon file: %s\n", IMG_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); exit(EXIT_FAILURE); } SDL_SetWindowIcon(window, icon); SDL_FreeSurface(icon); SDL_SetWindowTitle(window, "SDL2 test app"); int done = 0; SDL_Point lines[3][2] = { { {rand() % 640, rand() % 480}, {rand() % 640, rand() % 480} }, { {rand() % 640, rand() % 480}, {rand() % 640, rand() % 480} }, { {rand() % 640, rand() % 480}, {rand() % 640, rand() % 480} } }; SDL_Color colors[3] = { {255, 0, 0, SDL_ALPHA_OPAQUE}, {0, 255, 0, SDL_ALPHA_OPAQUE}, {0, 0, 255, SDL_ALPHA_OPAQUE} }; while (!done) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_WINDOWEVENT) { switch (event.window.event) { case SDL_WINDOWEVENT_CLOSE: done = 1; break; } } } if (SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to set draw color: %s\n", SDL_GetError()); } if (SDL_RenderClear(renderer) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to clear renderer: %s\n", SDL_GetError()); } for(int i = 0; i < 3; i++) { if (SDL_SetRenderDrawColor(renderer, colors[i].r, colors[i].g, colors[i].b, colors[i].a) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to set draw color: %s\n", SDL_GetError()); } if (SDL_RenderDrawLines(renderer, lines[i], 2) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to draw line: %s\n", SDL_GetError()); } } SDL_RenderPresent(renderer); } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); return 0; }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //The level tiles Tile* tileSet[ TOTAL_TILES ]; //Load media if( !loadMedia( tileSet ) ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //The dot that will be moving around on the screen Dot dot; //Level camera SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT }; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //Handle input for the dot dot.handleEvent( e ); } //Move the dot dot.move( tileSet ); dot.setCamera( camera ); //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render level for( int i = 0; i < TOTAL_TILES; ++i ) { tileSet[ i ]->render( camera ); } //Render dot dot.render( camera ); //Update screen SDL_RenderPresent( gRenderer ); } } //Free resources and close SDL close( tileSet ); } return 0; }
void loop(void *arg) { SDL_Event event; int i; SDL_GameController *gamecontroller = (SDL_GameController *)arg; /* 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. */ } #ifdef __EMSCRIPTEN__ if (done) { emscripten_cancel_main_loop(); } #endif }
bool ColorKeyingApp::initApp() { // flag to return bool success = true; /***** * Use this function to initialize the SDL library. This must be called before using any other SDL function. * INFO: http://wiki.libsdl.org/SDL_Init?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 *****/ // Initialize SDL // see following for remarks on flag http://wiki.libsdl.org/SDL_Init#Remarks if (SDL_Init( SDL_INIT_VIDEO) < 0) { std::cout << "SDL ould not initalize! SDLError: " << SDL_GetError() << std::endl; success = false; } else { //Set texture filtering to linear // INFO ON SDL_SetHint: see https://wiki.libsdl.org/SDL_SetHint // INFO ON SDL_HINT_RENDER_SCALE_QUALITY: see https://wiki.libsdl.org/SDL_HINT_RENDER_SCALE_QUALITY?highlight=%28\bCategoryDefine\b%29|%28CategoryHints%29 if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { std::cout << "Warning: Linear texture filtering not enabled!" << std::endl; } /***** * Returns the window that was created or NULL on failure * INFO: http://wiki.libsdl.org/SDL_CreateWindow?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 ******/ // Create Window // INFO: see following for remarks on flags http://wiki.libsdl.org/SDL_CreateWindow#flags gWindow = SDL_CreateWindow("SDL Tutorial 10", // the title of the window in UTF-8 encoding SDL_WINDOWPOS_UNDEFINED, // the x position of the window SDL_WINDOWPOS_UNDEFINED, // the y position of the window SCREEN_WIDTH, // the width of the window SCREEN_HEIGHT, // the height of the window SDL_WINDOW_SHOWN // 0 or more SDL_WindowFlags OR'd together ); if (gWindow == nullptr) { std::cout << "Window could not be created! SDL_Error:" << SDL_GetError() << std::endl; success = false; } else { // Get window surface // INFO: http://wiki.libsdl.org/SDL_GetWindowSurface?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 // gScreenSurface = SDL_GetWindowSurface(gWindow); gCurrentRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gCurrentRenderer == nullptr) { std::cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << std::endl; } else { // Initalize renderer color SDL_SetRenderDrawColor(gCurrentRenderer, 0xFF, 0xFF, 0xFF, 0xFF); // initialize the SDL image auto imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) && imgFlags)) { std::cout << "SDL Image could not be initialized! SDL Img Error: " << IMG_GetError() << std::endl; } } } } return success; }
int main() { if(SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); exit(1); } SDL_Window *win = SDL_CreateWindow("Moving start", 100, 100, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN); if(!win) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } if(!IMG_Init(IMG_INIT_PNG)) //*** { fprintf(stderr, "IMG_Init Error: %s\n", IMG_GetError()); SDL_DestroyWindow(win); SDL_Quit(); exit(1); } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!ren) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } //SDL_Surface *png = IMG_Load("../../MediaResources/star.png"); //*** SDL_Surface *png = IMG_Load("../../MediaResources/lips.png"); if(!png) { fprintf(stderr, "IMG_Load Error: %s\n", IMG_GetError()); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, png); SDL_FreeSurface(png); if(!tex) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } /* SDL_Rect dstRect = {SCREEN_HEIGHT / 2 - 32, SCREEN_WIDTH / 2 - 32, 64, 64}; SDL_SetRenderDrawColor(ren, 0x00, 0xFF, 0xFF, 0xFF); */ /* SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, &dstRect); SDL_RenderPresent(ren); SDL_Delay(4000); */ /* for(int i = 0; i < 10; ++i) { dstRect.h *= 1.5; dstRect.w *= 1.5; dstRect.x = SCREEN_HEIGHT / 2 - dstRect.h / 2; dstRect.y = SCREEN_WIDTH / 2 - dstRect.w / 2; SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, &dstRect); SDL_RenderPresent(ren); SDL_Delay(50); } */ bool quit = false; SDL_Event e; SDL_Rect destRect = {0, 0, 256, 256}; SDL_Rect rectFrom = {0, 0, 256, 256}; SDL_SetRenderDrawColor(ren, 0xFF, 0xFF, 0xFF, 0xFF); while(!quit) { while(SDL_PollEvent(&e)) { switch(e.type) { case SDL_QUIT: case SDL_MOUSEBUTTONDOWN: case SDL_KEYDOWN: quit = true; break; } } SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, &rectFrom, &destRect); SDL_RenderPresent(ren); SDL_Delay(500); rectFrom.x = (rectFrom.x + 256) % 512; } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); return 0; }