// NB not used at the moment because we want to do smooth scrolling with a pixel offset. void backend_render_32bits() { //SDL_RenderPresent(renderer); uint32_t *plane_idx_0 = (uint32_t *)backend_bitplane[0].data; uint32_t *plane_idx_1 = (uint32_t *)backend_bitplane[1].data; uint32_t *plane_idx_2 = (uint32_t *)backend_bitplane[2].data; uint32_t *plane_idx_3 = (uint32_t *)backend_bitplane[3].data; uint32_t *plane_idx_4 = (uint32_t *)backend_bitplane[4].data; int fb_idx = 0; for(int y = 0; y < window_height; y++) { int x = 0; while(x < window_width) { uint32_t plane0 = be32toh(*plane_idx_0++); // we always have at least 2 bitplanes (TODO?) uint32_t plane1 = be32toh(*plane_idx_1++); uint32_t plane2 = plane_idx_2 ? be32toh(*plane_idx_2++) : 0; uint32_t plane3 = plane_idx_3 ? be32toh(*plane_idx_3++) : 0; uint32_t plane4 = plane_idx_4 ? be32toh(*plane_idx_4++) : 0; // Turn 32 bits from each plane into 32 pixels. unsigned bit; for(bit = 0x80000000UL; bit > 0x800000UL; bit >>= 1) { framebuffer[fb_idx + x] = palette[ ((plane0 & bit) ? 1 : 0) | ((plane1 & bit) ? 2 : 0) | ((plane2 & bit) ? 4 : 0) | ((plane3 & bit) ? 8 : 0) | ((plane4 & bit) ? 16 : 0)]; x++; } for(; bit > 0x8000; bit >>= 1) { framebuffer[fb_idx + x] = palette[ ((plane0 & bit) ? 1 : 0) | ((plane1 & bit) ? 2 : 0) | ((plane2 & bit) ? 4 : 0) | ((plane3 & bit) ? 8 : 0) | ((plane4 & bit) ? 16 : 0)]; x++; } for(; bit > 0x80; bit >>= 1) { framebuffer[fb_idx + x] = palette[ ((plane0 & bit) ? 1 : 0) | ((plane1 & bit) ? 2 : 0) | ((plane2 & bit) ? 4 : 0) | ((plane3 & bit) ? 8 : 0) | ((plane4 & bit) ? 16 : 0)]; x++; } for(; bit; bit >>= 1) { framebuffer[fb_idx + x] = palette[ ((plane0 & bit) ? 1 : 0) | ((plane1 & bit) ? 2 : 0) | ((plane2 & bit) ? 4 : 0) | ((plane3 & bit) ? 8 : 0) | ((plane4 & bit) ? 16 : 0)]; x++; } } fb_idx += window_width; } SDL_UpdateTexture(texture, NULL, framebuffer, window_width * 4); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); }
void MyRenderer::renderCopy(SDL_Texture * texture) { SDL_RenderCopy(renderer, texture, NULL, NULL); }
int main() { // Init SDL printf("Initializing SDL\n"); Init(); //SDL_RenderClear(Renderer); // SDL_CreateTextureFromSurface(Renderer, crateS); SDL_Texture* yellow_crate = IMG_LoadTexture(Renderer, "gfx/yellow_crate.png"); SDL_Texture* blue_crate = IMG_LoadTexture(Renderer, "gfx/blue_crate.png"); SDL_Texture* craneT = IMG_LoadTexture(Renderer, "gfx/crane.png"); if(yellow_crate == NULL || blue_crate == NULL || craneT == NULL) { printf("ERROR: %s", SDL_GetError()); } int sceneHeigth = 8; int sceneWidth = 3; // Scene and crane stuff Scene scene; std::vector<Box> start; std::vector<Box> result; std::vector< std::vector<int> > functions; functions.resize(4); functions[0].push_back(FUNC2); functions[0].push_back(FUNC3); functions[0].push_back(FUNC1); functions[1].push_back(GRAB); functions[1].push_back(RIGHT); functions[1].push_back(FUNC4); functions[2].push_back(FUNC4); functions[2].push_back(GRAB); functions[2].push_back(RIGHT); functions[3].push_back(GRAB); functions[3].push_back(LEFT); start.push_back(Box(1,1, YELLOW)); start.push_back(Box(2,1, BLUE)); start.push_back(Box(3,1, YELLOW)); start.push_back(Box(4,1, BLUE)); start.push_back(Box(5,1, YELLOW)); start.push_back(Box(6,1, BLUE)); result.push_back(Box(4, 0, BLUE)); result.push_back(Box(5, 0, BLUE)); result.push_back(Box(6, 0, BLUE)); result.push_back(Box(4, 2, YELLOW)); result.push_back(Box(5, 2, YELLOW)); result.push_back(Box(6, 2, YELLOW)); scene.Init(sceneHeigth, sceneWidth, start, result, functions); scene.crane.pos.y = 1; int res = NOT_DONE; int function, task; bool quit = false; SDL_Event e; SDL_Rect cratePos; cratePos.w = CRATE_SIZE; cratePos.h = CRATE_SIZE; SDL_Rect crateBasePos; crateBasePos.x = 30; crateBasePos.y = 20; crateBasePos.w = CRATE_SIZE; crateBasePos.h = CRATE_SIZE; SDL_Rect cranePos; cranePos.x = 30; cranePos.y = 200; cranePos.w = 80; cranePos.h = 76; SDL_Rect rect; rect.x = 20; rect.y = crateBasePos.y+CRATE_SIZE*(sceneHeigth-1); rect.w = 80; rect.h = 40; printf("Rect y: %d\n", rect.y); SDL_Rect basePos = rect; printf("Main Loop!\n"); while(!quit) { if(res == NOT_DONE) { res = scene.Tick( &function, &task); } else if(res == SUCCES) { printf("YOU WON\n"); res = DONE; } else if(res == FAILURE) { printf("YOU LOST!\n"); res = DONE; } //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //User presses a key else if( e.type == SDL_KEYDOWN ) { //Select surfaces based on key press switch( e.key.keysym.sym ) { case SDLK_UP: printf("UP pressed!\n"); break; } } } // Render box's in grid for (int i = 0; i < (int)scene.box.size(); ++i) { if(scene.box[i].pos.x == 0) // Box is in crane, so use that pos cratePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.crane.pos.y); else cratePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.box[i].pos.y); cratePos.y = crateBasePos.y-CRATE_SIZE*(-scene.box[i].pos.x); switch(scene.box[i].color) { case YELLOW: SDL_RenderCopy( Renderer, yellow_crate, NULL, &cratePos ); break; case BLUE: SDL_RenderCopy( Renderer, blue_crate, NULL, &cratePos ); break; }; } for(int i = 0; i < sceneWidth; i++) { basePos.x = rect.x+(CRATE_SIZE+40)*i; Draw::FilledRectangleRoundEdge(Renderer, basePos, 10); } cranePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.crane.pos.y)-10; cranePos.y = crateBasePos.y-CRATE_SIZE*(-scene.crane.pos.x)-20; SDL_RenderCopy(Renderer, craneT, NULL, &cranePos ); //Apply the image //SDL_RenderCopy( Renderer, crateT, NULL, &cratePos ); //SDL_RenderCopy( Renderer, crateT, NULL, &cratePos2); SDL_RenderPresent(Renderer); SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 0); SDL_RenderClear(Renderer); SDL_SetRenderDrawColor(Renderer, 100, 0, 0, 0); SDL_Delay(750); } SDL_DestroyRenderer( Renderer ); SDL_DestroyWindow( Window ); SDL_Quit(); return 0; }
void TrainingMode::update() { /* STEPS 0: How to move 1: How to shoot 2: Paintball Gun 3: How to select weapons - Glock 4: How to select weapons 5: How to use C4 6: Show Ammobox & how to use it 7: Show Tiger Generator, kill tiger 8: Show how to destroy tiger generator 9: Explain Survival Mode 10: Explain Mercenary Mode */ if(Main::ammoBoxes.size() > 0 && step != AmmoBoxes) Main::ammoBoxes.clear(); if(Main::tgs.size() > 0 && step!= TigerGenerators && step != DestroyTigerGenerator) Main::tgs.clear(); if(step != TigerGenerators) Main::spawning = false; else Main::spawning = true; SDL_Texture *tex = nullptr; switch(step) { case Move: message = "Move with the WASD keys"; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); if(SDL_GetTicks() - start > 3000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); } break; case Shoot: message = "Shoot with the Left Mouse Button"; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); if(SDL_GetTicks() - start > 3000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); } break; case Paintball: message = "The weapon you are holding is the Paintball Gun."; rect.h = MediumFontSize; rect.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "With the Paintball Gun,"; rect2.h = MediumFontSize; rect2.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); message = "you can shoot with the Right Mouse Button too."; rect3.h = MediumFontSize; rect3.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect3); if(SDL_GetTicks() - start > 6000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); } break; case SelectGlock: message = "Select Weapons by hitting number keys."; rect.h = LargeFontSize; rect.w = message.size() *LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "Select the Glock by pressing 0."; rect2.h = LargeFontSize; rect2.w = message.size() *LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); message = "The Glock has infinite ammo."; rect3.h = LargeFontSize; rect3.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect3); if(SDL_GetTicks() - start > 6000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); } break; case SelectWeapons: message = "Try playing around with other weapons"; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); if(SDL_GetTicks() - start > 10000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); } break; case DetonateC4: message = "Press SPACE to plant a C4."; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "Press SPACE again to detonate it."; rect2.h = LargeFontSize; rect2.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); message = "Don't kill yourself!"; rect.h = 24; rect.w = message.size() * 24; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect3); if(SDL_GetTicks() - start > 8000) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); Main::spawning = false; } break; case AmmoBoxes: if(Main::ammoBoxes.size() == 0) { Main::ammoBoxes.push_back(std::shared_ptr<AmmoBox>(new AmmoBox(player->getX() + 100, player->getY() + 100,xOffset,yOffset,renderer))); } message = "This is an ammobox."; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "Step on the ammobox to fill your current weapon with ammo."; rect2.h = MediumFontSize; rect2.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); if(SDL_GetTicks() - start > 60000 || (player->hasFullAmmo() && SDL_GetTicks() - start > 2000)) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); Main::tgs.push_back(std::shared_ptr<TigerGenerator>(new TigerGenerator(player->getX() + 200,player->getY() + 200,xOffset,yOffset,renderer,player))); Main::spawning = true; } break; case Tips::TigerGenerators: message = "This is a tiger generator. Tigers spawn from Tiger Generators. Kill the tiger(s)."; rect.h = LargeFontSize; rect.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "Tigers spawn from Tiger Generators."; rect2.h = LargeFontSize; rect2.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); message = "Kill the tiger(s)."; rect3.h = LargeFontSize; rect3.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect3); if(Main::killcount > 0) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); Main::spawning = false; } break; case DestroyTigerGenerator: message = "Tiger Generators can be destroyed by ballistic knives."; rect.h = MediumFontSize; rect.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "Select the ballistic knife by pressing 3,"; rect2.h = LargeFontSize; rect2.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); message = "and destroy the Tiger Generator."; rect3.h = LargeFontSize; rect3.w = message.size() * LargeFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect3); if(Main::tgs.size() == 0) { step++; start = SDL_GetTicks(); SDL_DestroyTexture(tex); Main::spawning = false; } break; case Survival: survivalex->draw(0,0,0,0); if(SDL_GetTicks() - start > 30000) { step++; start = SDL_GetTicks(); } break; case Mercenary: mercenaryex->draw(0,0,0,0); if(SDL_GetTicks() - start > 30000) { step++; start = SDL_GetTicks(); } break; default: message = "Congrats! You have finished training."; rect.h = MediumFontSize; rect.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect); message = "To Exit, open the pause menu by pressing ESC."; rect2.h = MediumFontSize; rect2.w = message.size() * MediumFontSize; instructionSurface = TTF_RenderText_Solid(font,message.c_str(),fg); tex = SDL_CreateTextureFromSurface(renderer,instructionSurface); SDL_FreeSurface(instructionSurface); SDL_RenderCopy(renderer,tex,NULL,&rect2); break; } }
//------------------------------------------------------------------------------ void Texture::Render(int X, int Y, int Width, int Height, int SX, int SY, int SWidth, int SHeight) { SDL_Rect Source = {SX, SY, SWidth, SHeight}; SDL_Rect Destination = {X, Y, Width, Height}; SDL_RenderCopy(Renderer, SDLTexture, &Source, &Destination); }
int main(int argc, char *argv[]) { srand(time(NULL)); SDL_Window *screen; SDL_Renderer *renderPrim; SDL_Event eventHandle; SDL_Texture *scoreDisplay; TTF_Font *defaultText; SDL_Color cPlayer = {0,255,255,255}; SDL_Color cPoint = {255,255,0,255}; SDL_Color cBackground = {0,0,0,255}; SDL_Color cScore = {0,255,0,255}; int runningGame,gotPoint, pointCount, oldScore; runningGame = 0; gotPoint = 0; pointCount = -1;//first point spawns on player SDL_Rect rPlayer = {0,0,PLAYER_WIDTH, PLAYER_HEIGHT}; SDL_Rect rPoint = {0,0,POINT_WIDTH,POINT_HEIGHT}; SDL_Rect rScore = {0,0,0,0}; screen = init("Piss easy snake", SCREEN_WIDTH, SCREEN_HEIGHT); renderPrim = createRenderer(screen); defaultText = loadFont("default.ttf", 15, renderPrim); while(runningGame == 0) { oldScore = pointCount; if(gotPoint == 1) { pointCount++; rPoint.x = rand() % SCREEN_WIDTH;//new random position rPoint.y = rand() % SCREEN_HEIGHT; gotPoint = 0; } while(SDL_PollEvent(&eventHandle) != 0) { if(eventHandle.type == SDL_KEYDOWN) { handleInput(&rPlayer, eventHandle, &runningGame); } else if(eventHandle.type == SDL_QUIT) { runningGame = 1; } } SDL_SetRenderDrawColor(renderPrim, cBackground.r,cBackground.g,cBackground.b,cBackground.a); SDL_RenderClear(renderPrim); SDL_SetRenderDrawColor(renderPrim,cPlayer.r,cPlayer.g,cPlayer.b,cPlayer.a); SDL_RenderFillRect(renderPrim,&rPlayer); SDL_SetRenderDrawColor(renderPrim,cPoint.r,cPoint.g,cPoint.b,cPoint.a); SDL_RenderFillRect(renderPrim,&rPoint); if(oldScore < pointCount) { scoreDisplay = renderScore(defaultText,cScore,&rScore, renderPrim, pointCount, scoreDisplay); } SDL_RenderCopy(renderPrim, scoreDisplay, NULL, &rScore); SDL_RenderPresent(renderPrim); gotPoint = SDL_HasIntersection(&rPlayer,&rPoint); } SDL_DestroyRenderer(renderPrim); SDL_DestroyWindow(screen); TTF_CloseFont(defaultText); TTF_Quit(); SDL_Quit(); return 0; }
//Draw the texture from the PackedSprite structure //param:packedSprite->The packed sprite to draw from void SpriteBatch::DrawTexture(PackedSprite packedSprite) { if(packedSprite.Type == PackedSprite::PackType::Sprite) { //Get the texture (we dont do bounds checking because when we added the texture to the list //we checked the bounds) We also don't check for begin, because that would've been checked in the //users call to DrawTexture. This is a private function. Only spritebatch calls this one. SDL_Texture* tex = textureList[packedSprite.Texture]; //Apply any blends ApplyBlendToTexture(tex, packedSprite.Tint); //if no flip or angle, draw with Render Copy if(packedSprite.Rotation == 0 && packedSprite.FlipEffects == 0) SDL_RenderCopy(renderer, tex, packedSprite.SourceRect, packedSprite.DestRect); else ///Draw the image with any flip/angle SDL_RenderCopyEx(renderer, tex, packedSprite.SourceRect, packedSprite.DestRect, packedSprite.Rotation, packedSprite.Origin, packedSprite.FlipEffects); } else { SDL_Surface* textSurface; //Generate surface based on draw mode if(packedSprite.DrawMode == StringDrawMode::Blended) { if(packedSprite.WrapLength <= 0) textSurface = TTF_RenderText_Blended(fontManager->GetFont(packedSprite.Texture), packedSprite.Message.c_str(), packedSprite.Tint); else textSurface = TTF_RenderText_Blended_Wrapped(fontManager->GetFont(packedSprite.Texture), packedSprite.Message.c_str(), packedSprite.Tint, packedSprite.WrapLength); } else if(packedSprite.DrawMode == StringDrawMode::Shaded) { textSurface = TTF_RenderText_Shaded(fontManager->GetFont(packedSprite.Texture), packedSprite.Message.c_str(), packedSprite.Tint, packedSprite.BackgroundColor); } else if(packedSprite.DrawMode == StringDrawMode::Solid) { textSurface = TTF_RenderText_Solid(fontManager->GetFont(packedSprite.Texture), packedSprite.Message.c_str(), packedSprite.Tint); } //Generate the texture from the surface SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, textSurface); //Free the surface and get rid of the pointer to it SDL_FreeSurface(textSurface); textSurface = nullptr; int w = 0; int h = 0; SDL_QueryTexture(tex, NULL, NULL, &w, &h); //Create a rectangle that is the size of the string SDL_Rect sourceRect = CreateRect(0, 0, w, h); SDL_Rect destRect = CreateRect(packedSprite.DestRect->x, packedSprite.DestRect->y, (Uint32)(w * packedSprite.StringScale), (Uint32)(h * packedSprite.StringScale)); //if no flip or angle, draw with Render Copy if(packedSprite.Rotation == 0 && packedSprite.FlipEffects == SDL_RendererFlip::SDL_FLIP_NONE) SDL_RenderCopy(renderer, tex, &sourceRect, &destRect); else ///Draw the image with any flip/angle SDL_RenderCopyEx(renderer, tex, &sourceRect, &destRect, packedSprite.Rotation, packedSprite.Origin, packedSprite.FlipEffects); } }
static void ANDROID_UnlockHWSurface(_THIS, SDL_Surface *surface) { SDL_PixelFormat format; Uint32 hwformat = PixelFormatEnumColorkey; int bpp; SDL_Surface * converted = NULL; if( !SDL_ANDROID_InsideVideoThread() ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Error: calling %s not from the main thread!", __PRETTY_FUNCTION__); return; } if( !surface->hwdata ) return; if( surface->format->Amask ) hwformat = PixelFormatEnumAlpha; if( surface == SDL_CurrentVideoSurface ) // Special case hwformat = PixelFormatEnum; /* Allocate the new pixel format for the screen */ SDL_memset(&format, 0, sizeof(format)); SDL_PixelFormatEnumToMasks( hwformat, &bpp, &format.Rmask, &format.Gmask, &format.Bmask, &format.Amask ); format.BytesPerPixel = SDL_ANDROID_BYTESPERPIXEL; format.BitsPerPixel = bpp; // TODO: support 24bpp and 32bpp if( format.BitsPerPixel == surface->format->BitsPerPixel && format.Rmask == surface->format->Rmask && format.Gmask == surface->format->Gmask && format.Bmask == surface->format->Bmask && format.Amask == surface->format->Amask ) { converted = surface; // No need for conversion } else { Uint16 x, y; converted = SDL_CreateRGBSurface(SDL_SWSURFACE, surface->w, surface->h, format.BitsPerPixel, format.Rmask, format.Gmask, format.Bmask, format.Amask); if( !converted ) { SDL_OutOfMemory(); return; } #define CONVERT_RGB565_RGBA5551( pixel ) (0x1 | ( (pixel & 0xFFC0) | ( (pixel & 0x1F) << 1 ) )) if( surface->flags & SDL_SRCCOLORKEY ) { DEBUGOUT("ANDROID_UnlockHWSurface() CONVERT_RGB565_RGBA5551 + colorkey"); for( y = 0; y < surface->h; y++ ) { Uint16* src = (Uint16 *)( surface->pixels + surface->pitch * y ); Uint16* dst = (Uint16 *)( converted->pixels + converted->pitch * y ); Uint16 w = surface->w; Uint16 key = surface->format->colorkey; Uint16 pixel; for( x = 0; x < w; x++, src++, dst++ ) { pixel = *src; *dst = (pixel == key) ? 0 : CONVERT_RGB565_RGBA5551( pixel ); } } } else { DEBUGOUT("ANDROID_UnlockHWSurface() CONVERT_RGB565_RGBA5551"); for( y = 0; y < surface->h; y++ ) { Uint16* src = (Uint16 *)( surface->pixels + surface->pitch * y ); Uint16* dst = (Uint16 *)( converted->pixels + converted->pitch * y ); Uint16 w = surface->w; Uint16 pixel; for( x = 0; x < w; x++, src++, dst++ ) { pixel = *src; *dst = CONVERT_RGB565_RGBA5551( pixel ); } } } } SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = surface->w; rect.h = surface->h; SDL_UpdateTexture((struct SDL_Texture *)surface->hwdata, &rect, converted->pixels, converted->pitch); if( surface == SDL_CurrentVideoSurface ) // Special case SDL_RenderCopy((struct SDL_Texture *)SDL_CurrentVideoSurface->hwdata, NULL, NULL); if( converted != surface ) SDL_FreeSurface(converted); }
int main( int argc, char** argv ) { // Create the optional arguments boost::program_options::options_description generic( "Allowed options" ); generic.add_options() ("help,h", "produce help message") ("image,i", boost::program_options::value<std::string>(), "Set the optional image to render (with path)\n"); // Create the command-line argument parser boost::program_options::options_description cmdline_options( "Allowed options" ); cmdline_options.add(generic); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(cmdline_options).run(), vm ); boost::program_options::notify( vm ); // Check if the help message was requested if( vm.count( "help" ) ) { std::cerr << generic << std::endl; return 1; } // Store the image name std::string image_name; if( vm.count( "image" ) ) image_name = vm["image"].as<std::string>(); // Initialize the window if( !initialize() ) { return 1; } else { // Load the bitmap if( !loadMedia( image_name )) { return 1; } else { bool quit = false; // Event SDL_Event event; // Main application loop while( !quit ) { while( SDL_PollEvent( &event ) != 0 ) { if( event.type == SDL_QUIT ) quit = true; } // Render the user supplied image (texture) to the screen if( image_name.size() > 0 ) { // Clear the screen SDL_RenderClear( g_renderer ); SDL_RenderCopy( g_renderer, g_texture, NULL, NULL ); } else { SDL_SetRenderDrawColor( g_renderer, 0xFF, 0xFF, 0xFF, 0xFF ); // Clear the screen SDL_RenderClear( g_renderer ); } // Render red filled quad SDL_Rect fill_rect = { screen_width_height[0]/4, screen_width_height[1]/4, screen_width_height[0]/2, screen_width_height[1]/2 }; SDL_SetRenderDrawColor( g_renderer, 0xFF, 0x00, 0x00, 0xFF ); SDL_RenderFillRect( g_renderer, &fill_rect ); // Render green outlined quad SDL_Rect outline_rect = { screen_width_height[0]/6, screen_width_height[1]/6, screen_width_height[0]*2/3, screen_width_height[1]*2/3 }; SDL_SetRenderDrawColor( g_renderer, 0x00, 0xFF, 0x00, 0xFF ); SDL_RenderDrawRect( g_renderer, &outline_rect ); // Draw a blue horizontal line SDL_SetRenderDrawColor( g_renderer, 0x00, 0x00, 0xFF, 0xFF ); SDL_RenderDrawLine( g_renderer, 0, screen_width_height[1]/2, screen_width_height[0], screen_width_height[1]/2 ); // Draw a vertial line of yellow dots SDL_SetRenderDrawColor( g_renderer, 0xFF, 0xFF, 0x00, 0xFF ); for( int i = 0; i < screen_width_height[1]; i += 4 ) SDL_RenderDrawPoint( g_renderer, screen_width_height[0]/2, i ); // Update the screen SDL_RenderPresent( g_renderer ); } } } // Close program close(); return 0; }
void DrawText(Text* text, SDL_Renderer* renderer) { SDL_RenderCopy(renderer, text->texture, NULL, &text->rect); }
void Renderer::draw_sprite(Sprite & spr, int x, int y, float scale) { SDL_Rect dst = { x, y, int(spr.width * scale), int(spr.height * scale) }; SDL_RenderCopy(renderer, spr.texture, 0, &dst); }
int main(){ init(); load_res(); SDL_Event event; Uint8 red = 255, green = 255, blue = 255; bool color_on = true; SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, color_wheel, NULL, NULL); SDL_RenderPresent(renderer); bool loop = true; while(loop) { while(SDL_PollEvent(&event) != 0) { if(event.type == SDL_QUIT) { loop = false; } if(event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_SPACE: color_on = !color_on; break; case SDLK_q: red += 32; break; case SDLK_a: red -= 32; break; case SDLK_w: green += 32; break; case SDLK_s: green -= 32; break; case SDLK_e: blue += 32; break; case SDLK_d: blue -= 32; break; case SDLK_r: red = 255; green = 255; blue = 255; break; case SDLK_ESCAPE: loop = false; default: break; } red = clamp(red); green = clamp(green); blue = clamp(blue); if(color_on) { SDL_SetTextureColorMod(color_wheel, red, green, blue); printf("< R%03d G%03d B%03d >\n", red, green, blue); } else { SDL_SetTextureColorMod(color_wheel, 255, 255, 255); printf("< R255 G255 B255 >\n"); } } } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, color_wheel, NULL, NULL); SDL_RenderPresent(renderer); } quit(); return 0; }
void Personaje::dibujar() { rect.x = x; rect.y = y; SDL_RenderCopy(renderer, textures[state][current_texture], NULL, &rect); }
void MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite) { int i; SDL_Rect viewport, temp; SDL_Rect *position, *velocity; /* Query the sizes */ SDL_RenderGetViewport(renderer, &viewport); /* Cycle the color and alpha, if desired */ if (cycle_color) { current_color += cycle_direction; if (current_color < 0) { current_color = 0; cycle_direction = -cycle_direction; } if (current_color > 255) { current_color = 255; cycle_direction = -cycle_direction; } SDL_SetTextureColorMod(sprite, 255, (Uint8) current_color, (Uint8) current_color); } if (cycle_alpha) { current_alpha += cycle_direction; if (current_alpha < 0) { current_alpha = 0; cycle_direction = -cycle_direction; } if (current_alpha > 255) { current_alpha = 255; cycle_direction = -cycle_direction; } SDL_SetTextureAlphaMod(sprite, (Uint8) current_alpha); } /* Draw a gray background */ SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); /* Test points */ SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF); SDL_RenderDrawPoint(renderer, 0, 0); SDL_RenderDrawPoint(renderer, viewport.w-1, 0); SDL_RenderDrawPoint(renderer, 0, viewport.h-1); SDL_RenderDrawPoint(renderer, viewport.w-1, viewport.h-1); /* Test horizontal and vertical lines */ SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF); SDL_RenderDrawLine(renderer, 1, 0, viewport.w-2, 0); SDL_RenderDrawLine(renderer, 1, viewport.h-1, viewport.w-2, viewport.h-1); SDL_RenderDrawLine(renderer, 0, 1, 0, viewport.h-2); SDL_RenderDrawLine(renderer, viewport.w-1, 1, viewport.w-1, viewport.h-2); /* Test fill and copy */ SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); temp.x = 1; temp.y = 1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderFillRect(renderer, &temp); SDL_RenderCopy(renderer, sprite, NULL, &temp); temp.x = viewport.w-sprite_w-1; temp.y = 1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderFillRect(renderer, &temp); SDL_RenderCopy(renderer, sprite, NULL, &temp); temp.x = 1; temp.y = viewport.h-sprite_h-1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderFillRect(renderer, &temp); SDL_RenderCopy(renderer, sprite, NULL, &temp); temp.x = viewport.w-sprite_w-1; temp.y = viewport.h-sprite_h-1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderFillRect(renderer, &temp); SDL_RenderCopy(renderer, sprite, NULL, &temp); /* Test diagonal lines */ SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF); SDL_RenderDrawLine(renderer, sprite_w, sprite_h, viewport.w-sprite_w-2, viewport.h-sprite_h-2); SDL_RenderDrawLine(renderer, viewport.w-sprite_w-2, sprite_h, sprite_w, viewport.h-sprite_h-2); /* Conditionally move the sprites, bounce at the wall */ if (iterations == -1 || iterations > 0) { for (i = 0; i < num_sprites; ++i) { position = &positions[i]; velocity = &velocities[i]; position->x += velocity->x; if ((position->x < 0) || (position->x >= (viewport.w - sprite_w))) { velocity->x = -velocity->x; position->x += velocity->x; } position->y += velocity->y; if ((position->y < 0) || (position->y >= (viewport.h - sprite_h))) { velocity->y = -velocity->y; position->y += velocity->y; } } /* Countdown sprite-move iterations and disable color changes at iteration end - used for visual tests. */ if (iterations > 0) { iterations--; if (iterations == 0) { cycle_alpha = SDL_FALSE; cycle_color = SDL_FALSE; } } } /* Draw sprites */ for (i = 0; i < num_sprites; ++i) { position = &positions[i]; /* Blit the sprite onto the screen */ SDL_RenderCopy(renderer, sprite, NULL, position); } /* Update the screen! */ SDL_RenderPresent(renderer); }
void WorldTip::Draw(double dt) { if(ply->pos.Distance(this->origin) < 200) { SDL_Rect rect = {this->rect.x - camera.x, this->rect.y - camera.y, this->rect.w, this->rect.h}; if(SDL_RenderCopy(renderer, this->texture, NULL, &rect) != 0) {printf("Worldtip Render failed: %s\n", SDL_GetError());} } }
void Sprite::DisplayRectangle(SDL_Texture* healthBar) //called when Character, Building or Gold is selected { collisionImage = healthBar; SDL_RenderCopy(renderer, collisionImage, NULL, &collisionSDLRect); //displays rectangle }
void drawBackground(SDL_Renderer *renderer, double dt) { SDL_RenderCopy(renderer, backgroundRLTexture, &camera, NULL); }
void Enemigo1::dibujar() { SDL_RenderCopy(renderer, textura, NULL, &rect_textura); for(int i=0;i<rect_balas.size();i++) SDL_RenderCopy(renderer, textura_bala, NULL, &rect_balas[i]); }
//Draws the specified texture //param:texture->the index given from load texture //param:color->the tint to apply to the texture //param:sourceRect->the rectangle to pull a smaller image from the texture with. NULL for whole texture //param:destRect->The rectangle to draw to. NULL to draw to whole renderer (screen) //param:angle->The angle to rotate the image //param:origin->The origin to rotate around. If Null, defaults to destRect center //param:flip->SDL_RendererFlip::None/FlipHorizontal/FlipVertical. If you want both Flip Horizontal and Flip Vertical, //use the bitwise operator '|' //param:layerDepth->The depth to draw the image at //Returns -1 on error, returns 0 on success int SpriteBatch::DrawTexture(Uint32 texture, SDL_Color color, const SDL_Rect* sourceRect, const SDL_Rect* destRect, float angle, const SDL_Point* origin, SDL_RendererFlip flip, float layerDepth ) { //Check if spritebatch.begin has been called if(!begun) { std::cout<<"Begin must be called before attempting to draw"<<std::endl; return -1; } //make sure we have a valid layer depth if(layerDepth < 0 || layerDepth > 1) { std::cout <<"Layer Depth must be between 0 and 1"<<std::endl; return -1; } //Make sure we have a valid renderer if(!renderer) { std::cout<<"Renderer is null. Did you Initialize Spritebatch?"<<std::endl; return -1; } try{ //Get the texture (at performs bounds checking, which will validate the index for us, regardless of sort mode) SDL_Texture* tex = textureList.at(texture); //If sort mode is immediate, draw right away if(sortMode == SpriteBatchSortMode::Immediate) { //Apply any blends ApplyBlendToTexture(tex, color); //if no flip or angle, draw with Render Copy if(angle == 0 && flip == 0) SDL_RenderCopy(renderer, tex, sourceRect, destRect); else ///Draw the image with any flip/angle SDL_RenderCopyEx(renderer, tex, sourceRect, destRect, angle, origin, flip); } else { //Take the layer depth, multiply by 10 and floor it. A layer depth of 0.09 would then go into //index 0 map, while a 0.99 will go into index 9 int sortIndex = (int)std::floor(layerDepth * 10); //Package the information PackedSprite package = PackedSprite(PackedSprite::PackType::Sprite, texture, sourceRect, destRect, origin, color, flip, angle); //if sort index is greater than 9, put it in array slot 9. We do this because //1.0 * 10 = floor(10) = 10. Our array only goes to the 9th index if(sortIndex >= 9) { sortedImages[9].insert(std::pair<float, PackedSprite>(layerDepth, package)); } else { //otherwise, just put it in the appropriate slot sortedImages[sortIndex].insert(std::pair<float, PackedSprite>(layerDepth, package)); } } } //If invalid index, we throw the error catch (std::out_of_range problem) { std::cout<<"SPRITEBATCH_DRAW ERROR: Texture not a valid index"<<std::endl; return -1; } return 0; }
void Sprite::Draw() { SDL_RenderCopy(renderer, texture, NULL, &rect); }
//Draws a string to the screen //param:font->The index of the font //param:message->The message to display //param:drawMode->The draw mode to apply to the string: //Blended: Blends the text with whatever is behind it using transparency. This mode is required for wrapping. Slowest mode //Shaded: Gives the text a background that utilizes background color //Solid: Fastest rendering speed. No box around, just quick straight text //param:foregroundColor->The color of the text //param:backgroundColor->The color of the background box. Used with Shaded drawmode //param:wrapLength->Wraps the text past this width (in pixels). Requires empty space, will not separate words. Only //works in Blended mode //param:position->Point to draw the text at //param:angle->Angle to rotate the text //param:origin->The origin point to rotate about //param:scale->Amount to size the text. Will distort quickly //param:flip-> Flip texture horizontally, vertically, both or none //param:layerDepth->The depth to draw on //Returns 0 for success, -1 for errors int SpriteBatch::DrawString(Uint32 font, std::string message, StringDrawMode drawMode, SDL_Color foregroundColor, SDL_Color backgroundColor, int wrapLength, const SDL_Point* position, float angle, const SDL_Point* origin, float scale, SDL_RendererFlip flip, float layerDepth) { //Check if spritebatch.begin has been called if(!begun) { std::cout<<"Begin must be called before attempting to draw"<<std::endl; return -1; } //make sure we have a valid layer depth if(layerDepth < 0 || layerDepth > 1) { std::cout <<"Layer Depth must be between 0 and 1"<<std::endl; return -1; } //Make sure we have a valid renderer if(!renderer) { std::cout<<"Renderer is null. Did you Initialize Spritebatch?"<<std::endl; return -1; } try{ TTF_Font* fontToDraw; //Get the texture (at performs bounds checking, which will validate the index for us, regardless of sort mode) fontToDraw = fontManager->GetFont(font); //If sort mode is immediate, draw right away if(sortMode == SpriteBatchSortMode::Immediate) { SDL_Surface* textSurface = nullptr; //Create surface based on draw mode if(drawMode == StringDrawMode::Blended) { if(wrapLength <= 0) textSurface = TTF_RenderText_Blended(fontToDraw, message.c_str(), foregroundColor); else textSurface = TTF_RenderText_Blended_Wrapped(fontToDraw, message.c_str(), foregroundColor, wrapLength); } else if(drawMode == StringDrawMode::Shaded) { textSurface = TTF_RenderText_Shaded(fontToDraw, message.c_str(), foregroundColor, backgroundColor); } else if(drawMode == StringDrawMode::Solid) { textSurface = TTF_RenderText_Solid(fontToDraw, message.c_str(), foregroundColor); } //Generate the texture from the surface SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, textSurface); //Free the surface and get rid of the pointer to it SDL_FreeSurface(textSurface); textSurface = nullptr; int w = 0; int h = 0; SDL_QueryTexture(tex, NULL, NULL, &w, &h); //Check for null position SDL_Point point; if(position == nullptr) point = CreatePoint(0, 0); else point = CreatePoint(position->x, position->y); //Create a rectangle that is the size of the string SDL_Rect sourceRect = CreateRect(0, 0, w, h); SDL_Rect destRect = CreateRect(point.x, point.y, (int)(w * scale), (int)(h * scale)); //if no flip or angle, draw with Render Copy if(angle == 0 && flip == 0) SDL_RenderCopy(renderer, tex, &sourceRect, &destRect); else ///Draw the image with any flip/angle SDL_RenderCopyEx(renderer, tex, &sourceRect, &destRect, angle, origin, flip); } else { //Take the layer depth, multiply by 10 and floor it. A layer depth of 0.09 would then go into //index 0 map, while a 0.99 will go into index 9 int sortIndex = (int)std::floor(layerDepth * 10); SDL_Rect* destRect = &CreateRect(position->x, position->y, 0, 0); SDL_Rect sourceRect = CreateRect(0, 0, 0, 0); //Package the information PackedSprite package = PackedSprite(PackedSprite::PackType::String, font, message, drawMode, destRect, origin, backgroundColor, foregroundColor, flip, angle, scale, wrapLength); //if sort index is greater than 9, put it in array slot 9. We do this because //1.0 * 10 = floor(10) = 10. Our array only goes to the 9th index if(sortIndex >= 9) { sortedImages[9].insert(std::pair<float, PackedSprite>(layerDepth, package)); } else { //otherwise, just put it in the appropriate slot sortedImages[sortIndex].insert(std::pair<float, PackedSprite>(layerDepth, package)); } } } //If invalid index, we throw the error catch (std::out_of_range problem) { std::cout<<"SPRITEBATCH_DRAWSTRING ERROR: Font not a valid index"<<std::endl; return -1; } return 0; }
void Graphics::blitSurface(SDL_Texture * texture, SDL_Rect * sourceRectangle, SDL_Rect * destinationRectangle) { SDL_RenderCopy(this->_renderer, texture, sourceRectangle, destinationRectangle); }
//------------------------------------------------------------------------------ void Texture::Render(int X, int Y, int Width, int Height) { SDL_Rect Destination = {X, Y, Width, Height}; SDL_RenderCopy(Renderer, SDLTexture, NULL, &Destination); }
int main(int argc, char * argv[]) { /*variable declarations, remember, all v. decls. are at the beginning of each function in C*/ int done = 0; const Uint8 * keys; int mx,my; float mf = 0; float guyFrame = 0; Sprite *thing; Sprite *thing2; Sprite *guyx; Sprite *galSprite; Sprite *mehSprite; int controllerConnected = 0; /*Sprite *myTileMap; const int level[] = { 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2 };*/ FILE *tilemapFile; int tileClicked = 0; int p = 0; Vector4D mouseColor = {100,255,255,200}; Vector2D flipVert = { 0, 1 }; Vector2D scaleDown = { 0.5, 0.5 }; Vector2D scaleUp = { 2, 2 }; Vector2D scaleHalfUp = { 1.5, 1.5 }; //IntNode *myLL = IntNode_init(5); /*Student *person;*/ /*Entity *guy, *testDude; Entity *en = NULL; Entity *biggo = NULL; FILE *infile; Entity *fileLoadedDude = NULL; Entity *fileLoadedDude2 = NULL;*/ SDL_Event e; SDL_Surface *icon = SDL_LoadBMP("images/sprites/guy16x.bmp"); FILE *bandFile; FILE *levelFile; Sound *NJITtheme = NULL; Sound *snareDrum = NULL; Sound *flute = NULL; Sound *trumpet = NULL; Sound *altoSax = NULL; Sound *tenorSax = NULL; Uint32 musicPlaying = 0; //Sound *clap = NULL; Sound *cdEject = NULL; /*TTF_Font *PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 24); if (!PencilFont) { slog("Error loading font"); } SDL_Color colorBlack = { 255, 255, 255, 255 }; SDL_Surface *surfaceMessage = TTF_RenderText_Solid(PencilFont, "placeholdha", colorBlack); SDL_Texture *message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer, surfaceMessage); Sprite *textBox;*/ TTF_Font *PencilFont; SDL_Color colorBlack = { 0, 0, 0, 255 }; SDL_Surface *surfaceMessage; SDL_Texture *message; Sprite *textBox; TextDisplay *nameText; int texW = 0, texH = 0; SDL_Rect rect = { 65, 630, 0, 0 }; SDL_Surface *instrumentSurface; SDL_Texture *instrumentTexture; int instX = 0, instY = 0; SDL_Rect instrumentRect = { 65, 660, 0, 0 }; Uint8 playButtonPressed = 0; srand(time(NULL)); /*program initializtion*/ init_logger("dmdwa.log"); slog("---==== BEGIN ====---"); gf2d_graphics_initialize( "Drum Majors Don't Wear Aussies", 1200, 720, 1200, 720, vector4d(0,0,0,255), 0, icon); //SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); //This line makes images render crisp instead of blurry gf2d_graphics_set_frame_delay(16); gf2d_sprite_init(1024); entitySystemInit(1024); audioSystemInit(50, 10, 2, 0, 0, 0); soundSystemInit(25); text_system_init(50); SDL_ShowCursor(SDL_DISABLE); TTF_Init(); //fileLoadedDude = entityNew(); //derp //slog("%i", myLL->data); /*demo setup*/ //backgroundSprite = gf2d_sprite_load_image("images/backgrounds/bg_flat.png"); //textBox = gf2d_sprite_load_image("images/backgrounds/bg_flat.png"); mouseSprite = gf2d_sprite_load_all("images/pointer.png",32,32,16); mouse = mouseSprite; //thing = gf2d_sprite_load_all("images/sprites/test_dude.png", 32, 32, 1); //thing2 = gf2d_sprite_load_all("images/sprites/test_dude3.png", 64, 64, 1); //guyx = gf2d_sprite_load_all("images/sprites/guy32x.png", 32, 32, 2); //galSprite = gf2d_sprite_load_all("images/sprites/gal32x.png", 32, 32, 2); //mehSprite = gf2d_sprite_load_all("images/sprites/meh32x.png", 32, 32, 2); //musicSheet = gf2d_sprite_load_image("images/gui/music_sheet.png"); controllerIcon = gf2d_sprite_load_all("images/gui/controller64x.png", 64, 64, 1); //myTileMap = gf2d_sprite_load_all("images/field_tiles.png", 64, 64, 2); //person = student("Test", "Sex", thing2); //slog("Initializing student %s", person->name); /*guy = entityNew(); strncpy(guy->name, "McBandgeek", 32); guy->mySprite = guyx; guy->scale = scaleUp; guy->currentFrame = 0; guy->minFrame = 0; guy->maxFrame = 2; guy->position = vector2d(300, 100); guy->update = move; guy->myInstrument = Instrument_Tenor_Saxophone; guy->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tenor_sax.png", 32, 32, 1); guy->boundingBox = rect_new(guy->position.x, guy->position.y, 64, 64); testDude = NULL; //SDL_SetTextureColorMod(thing2->texture, 100, 60, 0); infile = fopen("def/dude.dude", "r"); fileLoadedDude = entityNew(); fileLoadedDude = entityLoadFromFile(infile, fileLoadedDude); fclose(infile); //fileLoadedDude->mySprite = mehSprite; fileLoadedDude->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude->instrumentSpriteFilePath, 32, 32, 1); fileLoadedDude->position = vector2d(64, 64); fileLoadedDude->boundingBox = rect_new(fileLoadedDude->position.x, fileLoadedDude->position.y, 64, 64); fileLoadedDude->scale = vector2d(2, 2); fileLoadedDude->currentFrame = 0; fileLoadedDude->minFrame = 0; fileLoadedDude->maxFrame = 2; fileLoadedDude->currentPosition = 19; slog("the thing made has name: %s", &fileLoadedDude->name); infile = fopen("def/dude2.dude", "r"); fileLoadedDude2 = entityNew(); fileLoadedDude2 = entityLoadFromFile(infile, fileLoadedDude2); fclose(infile); fileLoadedDude2->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude2->instrumentSpriteFilePath, 32, 32, 1); fileLoadedDude2->position = vector2d(128, 64); fileLoadedDude2->boundingBox = rect_new(fileLoadedDude2->position.x, fileLoadedDude2->position.y, 64, 64); fileLoadedDude2->scale = vector2d(2, 2); fileLoadedDude2->currentFrame = 0; fileLoadedDude2->minFrame = 0; fileLoadedDude2->maxFrame = 2; fileLoadedDude2->currentPosition = 20;*/ tile_map = tilemap_init(); load_level("def/level/mainMenu.txt", 0); //textBox->texture = message; //Trying to load a tilemap from file //tilemapFile = fopen("def/level/field_0.tilemap", "r"); //tilemap_load_from_file(tilemapFile, tile_map); //fclose(tilemapFile); //slog("tilewidth: (%i) tileheight: (%i) tperline: (%i) filepath: (...) width: (%i) height: (%i) xPos: (%i) yPos: (%i)", tile_map->tileWidth, tile_map->tileHeight, tile_map->tilesPerLine, tile_map->width, tile_map->height, tile_map->xPos, tile_map->yPos); //slog("do i have a sprite? %i", tile_map->tilemapSprite != NULL); //tile_map->space[19] = 1; //tile_map->space[20] = 1; /*slog("tile pq start"); while (tile_map->tiles_head != NULL) { p = pq_delete(tile_map->tiles_head, tile_map->tiles_tail); if (p == NULL) { break; } slog("Removing (%d) from pq", p); } slog("tile pq end");*/ /*slog("start array"); for (p = 0; p < tile_map->width * tile_map->height; p++) { if (p == 512) { slog("end of array"); } else if (tile_map->tiles[p] == -1) { slog("found a -1"); } else { slog("tiles at index (%i) is (%i)", p, tile_map->tiles[p]); } } slog("end array");*/ //Trying to load all entities from a file //bandFile = fopen("def/_myBand.band", "r"); //entityLoadAllFromFile(bandFile); //fclose(bandFile); //Load sounds //NJITtheme = soundNew("music/bg/NJIT.ogg"); //NJITtheme = soundLoad("music/bg/NJIT.ogg", 12.0f, 3); //slog("do i have a sound? %i", NJITtheme->sound != NULL); //soundPlay(NJITtheme, 1, 0, 0, 0); //Mix_VolumeChunk(NJITtheme->sound, MIX_MAX_VOLUME); //Use this to change volume on the fly! //clap = soundLoad("music/sfx/clap.ogg", 5.0f, 1); cdEject = soundNew(); cdEject = soundLoad("music/sfx/cd_play.ogg", 18.0f, 0); snareDrum = soundNew("music/bg/meeeeh-Snare_Drum.ogg"); snareDrum = soundLoad("music/bg/meeeeh-Snare_Drum.ogg", 12.0f, Instrument_Snare_Drum); flute = soundNew("music/bg/meeeeh-Flute.ogg"); flute = soundLoad("music/bg/meeeeh-Flute.ogg", 12.0f, Instrument_Flute); trumpet = soundNew("music/bg/meeeeh-Bb_Trumpet.ogg"); trumpet = soundLoad("music/bg/meeeeh-Bb_Trumpet.ogg", 12.0f, Instrument_Trumpet); altoSax = soundNew("music/bg/meeeeh-Alto_Saxophone.ogg"); altoSax = soundLoad("music/bg/meeeeh-Alto_Saxophone.ogg", 12.0f, Instrument_Alto_Saxophone); tenorSax = soundNew("music/bg/meeeeh-Tenor_Saxophone.ogg"); tenorSax = soundLoad("music/bg/meeeeh-Tenor_Saxophone.ogg", 12.0f, Instrument_Tenor_Saxophone); //soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0); //soundPlay(flute, -1, 1, flute->defaultChannel, 0); //soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0); //soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0); //soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0); //text testing stuff PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 36); if (!PencilFont) { slog("Error loading font"); } surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack); message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage); SDL_QueryTexture(message, NULL, NULL, &texW, &texH); rect.w = texW; rect.h = texH; nameText = text_new(PencilFont, "placeholda", colorBlack); //slog("nameText inuse (%i)", nameText->inUse); instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack); instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface); SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY); instrumentRect.w = instX; instrumentRect.h = instY; cd = entityNew(); cd->mySprite = gf2d_sprite_load_all("images/gui/cd.png", 128, 128, 1); cd->position = vector2d(0, 0); cd->scale = vector2d(2, 2); cd->boundingBox = rect_new(cd->position.x, cd->position.y, 128, 128); playButton = entityNew(); playButton->mySprite = gf2d_sprite_load_image("images/gui/play.png"); playButton->position = vector2d(64, 256); strncpy(playButton->name, "playButton", MAX_CHARS); playButton->boundingBox = rect_new(playButton->position.x, playButton->position.y, playButton->mySprite->frame_w, playButton->mySprite->frame_h); /*main game loop*/ while(!done) { SDL_PumpEvents(); // update SDL's internal event structures keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame /*update things here*/ SDL_GetMouseState(&mx,&my); SDL_PollEvent(&e); mf+=0.1; if (mf >= 16.0)mf = 0; guyFrame += 0.05; if (guyFrame >= 2.0)guyFrame = 0; gf2d_graphics_clear_screen();// clears drawing buffers // all drawing should happen betweem clear_screen and next_frame //backgrounds drawn first if (backgroundSprite) { gf2d_sprite_draw_image(backgroundSprite, vector2d(0, 0)); } //Me! trying to add a sprite /*tilemap_draw( myTileMap, level, 18, 10, 0, 0);*/ if (tile_map) { tilemap_draw_from_data(tile_map); } //gf2d_sprite_draw(thing, vector2d(100, 10), &scaleUp, NULL, NULL, NULL, NULL, 0); //gf2d_sprite_draw(thing, vector2d(100, 10), NULL, NULL, NULL, NULL, NULL, 0); //gf2d_sprite_draw(guy->mySprite, guy->position, &(guy->scale), NULL, NULL, NULL, NULL, 0); /*if (keys[SDL_SCANCODE_W]) { (*guy->update)(guy, vector2d(0, -2)); } if (keys[SDL_SCANCODE_A]) { (*guy->update)(guy, vector2d(-2, 0)); } if (keys[SDL_SCANCODE_S]) { (*guy->update)(guy, vector2d(0, 2)); } if (keys[SDL_SCANCODE_D]) { (*guy->update)(guy, vector2d(2, 0)); }*/ //guy->currentFrame = guyFrame; //fileLoadedDude->currentFrame = guyFrame; /* //create an entity if it doesn't exist if (keys[SDL_SCANCODE_O] && testDude == NULL) { testDude = entityNew(); testDude->mySprite = thing; testDude->position = vector2d(500, 500); testDude->update = move; } //if it exists, call its update function //slog("%i", testDude != NULL); if (testDude != NULL) { //(*testDude->update)(testDude, vector2d(1, 1)); gf2d_sprite_draw(testDude->mySprite, testDude->position, NULL, NULL, NULL, NULL, NULL, 0); } //delete it from memory if (keys[SDL_SCANCODE_P] && testDude != NULL) { entityDelete(testDude); }*/ /*if (keys[SDL_SCANCODE_L] && biggo == NULL) { biggo = entityNew(); biggo->mySprite = guyx; biggo->position = vector2d(10, 10); biggo->scale = vector2d(25, 25); biggo->inUse = 1; biggo->currentFrame = 0; biggo->minFrame = 0; biggo->maxFrame = 2; biggo->update = move; biggo->velocity = vector2d(0.5f, 0.5f); biggo->acceleration = vector2d(0.5f, 0.5f); biggo->myInstrument = Instrument_Flute; biggo->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_flute.png", 32, 32, 1); } if (biggo != NULL) { //entityDraw(biggo); (*biggo->update)(biggo, vector2d(0.5f, 0.5f)); //biggo->currentFrame = guyFrame; } if (biggo != NULL && biggo->inUse == 1 && keys[SDL_SCANCODE_P]) { biggo->inUse = 0; entityDelete(biggo); biggo = NULL; } if (keys[SDL_SCANCODE_O] && testDude == NULL) { //slog("Let's make a new thing!"); testDude = entityNew(); testDude->mySprite = mehSprite; testDude->position = vector2d(200, 200); testDude->scale = scaleUp; testDude->inUse = 1; testDude->currentFrame = 0; testDude->minFrame = 1; testDude->maxFrame = 3; testDude->update = move; testDude->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tuba.png", 32, 32, 1); } if (testDude != NULL) { //gf2d_sprite_draw(testDude->mySprite, testDude->position, &(testDude->scale), NULL, NULL, NULL, NULL, 0); //entityDraw(testDude); (*testDude->update)(testDude, vector2d(1, 1)); //testDude->currentFrame = guyFrame; } if (testDude != NULL && testDude->inUse == 1 && keys[SDL_SCANCODE_P]) { testDude->inUse = 0; entityDelete(testDude); testDude = NULL; } if (keys[SDL_SCANCODE_M] && en == NULL) { en = entityNew(); en->mySprite = galSprite; en->position = vector2d(300, 500); en->scale = vector2d(1,1); en->inUse = 1; en->currentFrame = 0; en->minFrame = 0; en->maxFrame = 4; en->update = move; en->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_clarinet.png", 32, 32, 1); //soundPlay(clap, 0, clap->volume, clap->defaultChannel, 0); } if (en != NULL && en->inUse == 1) { //entityDraw(en); (*en->update)(en, vector2d(1, -1)); //en->currentFrame = guyFrame; } if (en != NULL && en->inUse == 1 && keys[SDL_SCANCODE_P]) { en->inUse = 0; entityDelete(en); en = NULL; } if (en != NULL && en->inUse == 1 && en->position.x >= 400) { en->inUse = 0; entityDelete(en); en = NULL; }*/ /*gf2d_sprite_draw( guyx, vector2d(64, 64), &scaleUp, NULL, NULL, NULL, NULL, 0 ); gf2d_sprite_draw( galSprite, vector2d(128, 64), &scaleUp, NULL, NULL, NULL, NULL, 0 ); gf2d_sprite_draw( mehSprite, vector2d(192, 64), &scaleUp, NULL, NULL, NULL, NULL, 0 );*/ //entityDraw(fileLoadedDude); entityDrawAll(); entityUpdateAll(); entityIncrementCurrentFrameAll(); if (pickedUp != NULL) { draw_line(vector2d(pickedUp->position.x + pickedUp->mySprite->frame_w, pickedUp->position.y + pickedUp->mySprite->frame_h), vector2d(mx, my), COLOR_RED); } switch (e.type) { case SDL_QUIT: done = 1; break; case SDL_MOUSEBUTTONDOWN: if (e.button.button == SDL_BUTTON_RIGHT) { tileClicked = tilemap_find_tile(mx, my, tile_map); if (tileClicked >= 0 && pickedUp != NULL) { if (tile_map->space[tileClicked] == 0) { slog("poop"); tile_map->space[pickedUp->currentPosition] = 0; tile_map->space[tileClicked] = 1; pickedUp->currentPosition = tileClicked; mouse = mouseSprite; pickedUp->position.x = (mx - tile_map->xPos) / tile_map->tileWidth * (tile_map->tileWidth); pickedUp->position.y = (my - tile_map->yPos) / tile_map->tileHeight * (tile_map->tileHeight); pickedUp = NULL; surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack); message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage); SDL_QueryTexture(message, NULL, NULL, &texW, &texH); rect.w = texW; rect.h = texH; instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack); instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface); SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY); instrumentRect.w = instX; instrumentRect.h = instY; } } } else if (e.button.button == SDL_BUTTON_LEFT) { if (playButton != NULL) { if (point_in_rect(mx, my, playButton->boundingBox)) { //slog("hit da BUTT"); playButtonPressed = 1; soundPlay(cdEject, 0, 5.0f, -1, 0); } } } break; case SDL_MOUSEBUTTONUP: if (e.button.button == SDL_BUTTON_LEFT) //if (mousePress(&e.button)) { /*if (point_in_rect(mx, my, guy->boundingBox)) { slog("collision with guy (%s)", guy->name); } if (point_in_rect(mx, my, fileLoadedDude->boundingBox)) { slog("collision with guy (%s)", &fileLoadedDude->name); if (pickedUp == NULL) { pickedUp = fileLoadedDude; mouse = fileLoadedDude->mySprite; } } if (point_in_rect(mx, my, fileLoadedDude2->boundingBox)) { slog("collision with guy (%s)", &fileLoadedDude2->name); if (pickedUp == NULL) { pickedUp = fileLoadedDude2; mouse = fileLoadedDude2->mySprite; } }*/ collision = entityCheckCollisionInAll(mx, my); if (collision != NULL && collision->myInstrument != Instrument_Unassigned) { slog("collision with guy (%s)", &collision->name); if (pickedUp == NULL) { pickedUp = collision; mouse = collision->mySprite; surfaceMessage = TTF_RenderText_Solid(PencilFont, &pickedUp->name, colorBlack); message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage); SDL_QueryTexture(message, NULL, NULL, &texW, &texH); rect.w = texW; rect.h = texH; instrumentSurface = TTF_RenderText_Solid(PencilFont, entityGetInstrumentName(pickedUp), colorBlack); instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface); SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY); instrumentRect.w = instX; instrumentRect.h = instY; } } //if (point_in_rect(mx, my, tile_map->boundingBox)) tileClicked = tilemap_find_tile(mx, my, tile_map); if (tileClicked >= 0) { //slog("collided with tilemap on tile (%i), occupied (%i)", tileClicked, tile_map->space[tileClicked]); } } break; case SDL_CONTROLLERDEVICEADDED: slog("Connected a controller"); controllerConnected = 1; break; case SDL_CONTROLLERDEVICEREMOVED: slog("Removed a controller"); controllerConnected = 0; break; } if (playButtonPressed && cd != NULL) { cd->position.x += 5; } if (cd != NULL) { if (point_in_rect(1000, 10, cd->boundingBox)) { load_level("def/level/myLevel.txt", 1); if (musicPlaying > 0) { //Mix_RewindMusic(); Mix_HaltChannel(-1); } soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0); soundPlay(flute, -1, 1, flute->defaultChannel, 0); soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0); soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0); soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0); musicPlaying = 1; } } //slog("ds %i %i %i %i", cd->boundingBox->x, cd->boundingBox->y, cd->boundingBox->w, cd->boundingBox->h); //UI elements last if (musicSheet) gf2d_sprite_draw(musicSheet, vector2d(0, 592), &scaleUp, NULL, NULL, NULL, NULL, 0); if (gui) gf2d_sprite_draw(gui, vector2d(0, 0), &scaleUp, NULL, NULL, NULL, NULL, 0); //text_draw_all(); //text_draw(nameText); if (message && musicSheet) { SDL_RenderCopy(gf2d_graphics_get_renderer(), message, NULL, &rect); SDL_RenderCopy(gf2d_graphics_get_renderer(), instrumentTexture, NULL, &instrumentRect); } //SDL_RenderPresent(renderer); //gf2d_sprite_draw_image(textBox, vector2d(50, 50)); if (controllerConnected && controllerIcon) gf2d_sprite_draw(controllerIcon, vector2d(700, 600), &scaleUp, NULL, NULL, NULL, NULL, 0); if (pickedUp == NULL) { gf2d_sprite_draw( mouse, //Sprite to load vector2d(mx, my), //Position to draw it at NULL, //If you want to scale the sprite NULL, //Scale the sprite from a certain position NULL, //Rotation NULL, //Flip &mouseColor, //Color shift (int)mf); //Which frame to draw at } else { gf2d_sprite_draw( mouse, //Sprite to load vector2d(mx, my), //Position to draw it at &scaleHalfUp, //If you want to scale the sprite NULL, //Scale the sprite from a certain position NULL, //Rotation NULL, //Flip &mouseColor, //Color shift 0); //Which frame to draw at } gf2d_grahics_next_frame();// render current draw frame and skip to the next frame if (keys[SDL_SCANCODE_Q]) { //close_level(tile_map); load_level("def/level/myLevel.txt", 1); if (musicPlaying > 0) { //Mix_RewindMusic(); Mix_HaltChannel(-1); } soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0); soundPlay(flute, -1, 1, flute->defaultChannel, 0); soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0); soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0); soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0); musicPlaying = 1; } if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition //slog("Rendering at %f FPS",gf2d_graphics_get_frames_per_second()); } slog("---==== END ====---"); TTF_Quit(); SDL_DestroyTexture(message); SDL_FreeSurface(surfaceMessage); return 0; }
// TODO: find a way to get rid of the unexpected segfault in this function void renderScore(Game& game) { //std::cout << game.score << "; x" << game.multiplier << std::endl; SDL_Color color; color.r = 255; color.b = 255; color.g = 255; SDL_Rect outRect; SDL_Texture* textTexture; SDL_Surface* textSurface; /// RENDER SCORE if (game.score > 999999999999) { // This guard prevents itoa to overflow game.score = 0; } char score [12]; //itoa(game.score, score, 10); sprintf(score, "%d", game.score); //std::string score = std::to_string(game.score); // Doesn't work, the problem seems to come from MinGW std::cout << (game.scoreFont != NULL) << "; " << score << std::endl; textSurface = TTF_RenderText_Solid(game.scoreFont, score, color); if (textSurface == NULL) { std::cout << TTF_GetError() << std::endl; } else { textTexture = SDL_CreateTextureFromSurface(game.renderer, textSurface); outRect.w = textSurface->w; outRect.h = textSurface->h; outRect.y = 5; outRect.x = SCREEN_WIDTH - outRect.w - 7; SDL_RenderCopy(game.renderer, textTexture, NULL, &outRect); } /// RENDER MULTIPLIER char multiplier [12]; // Formatting game.multiplier to a char* int iMul = game.multiplier * 10; //itoa(iMul, multiplier, 10); sprintf(multiplier, "%d", iMul); int i = 0; while (multiplier[i] != '\0') { i++; } multiplier[i+2] = '\0'; multiplier[i+1] = multiplier[i-1]; multiplier[i--] = ','; for (i = i; i > 0; i--) { multiplier[i] = multiplier[i-1]; } multiplier[0] = 'x'; std::cout << (game.scoreFont != NULL) << "; " << multiplier << std::endl; textSurface = TTF_RenderText_Solid(game.scoreFont, multiplier, color); if (textSurface == NULL) { std::cout << TTF_GetError() << std::endl; } else { textTexture = SDL_CreateTextureFromSurface(game.renderer, textSurface); outRect.y = outRect.y + outRect.h + 5; outRect.w = textSurface->w; outRect.h = textSurface->h; outRect.x = SCREEN_WIDTH - outRect.w - 7; SDL_RenderCopy(game.renderer, textTexture, NULL, &outRect); } SDL_FreeSurface(textSurface); SDL_DestroyTexture(textTexture); }
void AscentApp::drawStatusBox() { std::stringstream msgstringstream; switch (userInputRequested) { case InputType::Standard: { Foreground tb = engine->underWitch(); if (tb != Foreground::NONE) { msgstringstream << engine->underItemString() << "\n"; } msgstringstream << "HP: " << engine->playerHP(); if (engine->playerMaxHP()) msgstringstream << " (MAX)"; if (!engine->playerAlive()) msgstringstream << " (Dead)"; } break; case InputType::InventoryItemToDrop: msgstringstream << "Select an item to drop (a-zA-Z); Esc to cancel\n"; break; case InputType::InventoryItemToView: msgstringstream << "Select an item to view (Not implemented); Esc to cancel\n"; break; case InputType::EndGame: msgstringstream << "Esc to quit"; break; default: return; } std::string msgstring = msgstringstream.str(); if (msgstring.length() == 0) return; SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(font, msgstring.c_str(), {0xFF, 0xFF, 0xFF, 0xFF}, windowWidth - MESSAGE_BORDER * 4); if (textSurface == NULL) { fprintf(stderr, "Couldn\'t make the text surface. %s\n", TTF_GetError()); return; } int message_w = textSurface->w; int message_h = textSurface->h; if (statusMessage != NULL) SDL_DestroyTexture(statusMessage); statusMessage = SDL_CreateTextureFromSurface(renderer, textSurface); SDL_FreeSurface(textSurface); if (statusMessage == NULL) { fprintf(stderr, "Couldn\'t create the text texture. %s\n", SDL_GetError()); return; } SDL_Rect messageRect = { MESSAGE_BORDER, windowHeight - message_h - MESSAGE_BORDER, message_w, message_h }; SDL_Rect messageBackgroundRect = { 0, windowHeight - message_h - MESSAGE_BORDER * 2, // message_w + MESSAGE_BORDER * 2, windowWidth, message_h + MESSAGE_BORDER * 2 }; SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xC0); SDL_RenderFillRect(renderer, &messageBackgroundRect); SDL_RenderCopy(renderer, statusMessage, NULL, &messageRect); }
void Explode::Draw(SDL_Renderer *renderer) { SDL_RenderCopy(renderer, texture, &drawRect, &posRect); }
void CSDLVideo::transformScreenToDisplay() { #if SDL_VERSION_ATLEAST(2, 0, 0) mpScreenSfc->lock(); SDL_UpdateTexture(mpSDLScreenTexture.get(), nullptr, mpScreenSfc->getSDLSurface()->pixels, mpScreenSfc->width() * sizeof (Uint32)); mpScreenSfc->unlock(); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, mpSDLScreenTexture.get(), NULL, NULL); // Now render the textures which additionally sent over... while(!mRenderTexturePtrs.empty()) { auto &triple = mRenderTexturePtrs.front(); GsTexture &gsTexture = std::get<0>(triple); SDL_Texture *texture = gsTexture.getPtr(); const GsRect<Uint16> &src = std::get<1>(triple); const GsRect<Uint16> &dst = std::get<2>(triple); if(src.empty()) { if(dst.empty()) { SDL_RenderCopy(renderer, texture, nullptr, nullptr); } else { SDL_Rect dstSDL = dst.SDLRect(); SDL_RenderCopy(renderer, texture, nullptr, &dstSDL); } } else { SDL_Rect srcSDL = src.SDLRect(); if(dst.empty()) { SDL_RenderCopy(renderer, texture, &srcSDL, nullptr); } else { SDL_Rect dstSDL = dst.SDLRect(); SDL_RenderCopy(renderer, texture, &srcSDL, &dstSDL); } } mRenderTexturePtrs.pop(); } SDL_RenderPresent(renderer); #else // Blit the stuff mpScreenSfc->blitScaledTo(mDisplaySfc); // Flip the screen (We use double-buffering on some systems.) mDisplaySfc.flip(); #endif }
/* * Draw and update screen. */ static void display (void) { draw(); SDL_UpdateTexture(screen_texture, NULL, color_buffer, window_width*sizeof(unsigned int)); SDL_RenderCopy(renderer, screen_texture, NULL, NULL); SDL_RenderPresent(renderer); }
int main(int argc, char* argv[]) { AVFormatContext *pFormatCtx; int i, videoindex; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame,*pFrameYUV; uint8_t *out_buffer; AVPacket *packet; int y_size; int ret, got_picture; struct SwsContext *img_convert_ctx; char filepath[]="bigbuckbunny_480x272.h265"; //SDL--------------------------- int screen_w=0,screen_h=0; SDL_Window *screen; SDL_Renderer* sdlRenderer; SDL_Texture* sdlTexture; SDL_Rect sdlRect; FILE *fp_yuv; av_register_all(); avformat_network_init(); pFormatCtx = avformat_alloc_context(); if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0){ printf("Couldn't open input stream.\n"); return -1; } if(avformat_find_stream_info(pFormatCtx,NULL)<0){ printf("Couldn't find stream information.\n"); return -1; } videoindex=-1; for(i=0; i<pFormatCtx->nb_streams; i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ videoindex=i; break; } if(videoindex==-1){ printf("Didn't find a video stream.\n"); return -1; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL){ printf("Codec not found.\n"); return -1; } if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){ printf("Could not open codec.\n"); return -1; } pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc(); out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height)); avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height); packet=(AVPacket *)av_malloc(sizeof(AVPacket)); //Output Info----------------------------- printf("--------------- File Information ----------------\n"); av_dump_format(pFormatCtx,0,filepath,0); printf("-------------------------------------------------\n"); img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); #if OUTPUT_YUV420P fp_yuv=fopen("output.yuv","wb+"); #endif if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { printf( "Could not initialize SDL - %s\n", SDL_GetError()); return -1; } screen_w = pCodecCtx->width; screen_h = pCodecCtx->height; //SDL 2.0 Support for multiple windows screen = SDL_CreateWindow("Simplest ffmpeg player's Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_w, screen_h, SDL_WINDOW_OPENGL); if(!screen) { printf("SDL: could not create window - exiting:%s\n",SDL_GetError()); return -1; } sdlRenderer = SDL_CreateRenderer(screen, -1, 0); //IYUV: Y + U + V (3 planes) //YV12: Y + V + U (3 planes) sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,pCodecCtx->width,pCodecCtx->height); sdlRect.x=0; sdlRect.y=0; sdlRect.w=screen_w; sdlRect.h=screen_h; //SDL End---------------------- while(av_read_frame(pFormatCtx, packet)>=0){ if(packet->stream_index==videoindex){ ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if(ret < 0){ printf("Decode Error.\n"); return -1; } if(got_picture){ sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); #if OUTPUT_YUV420P y_size=pCodecCtx->width*pCodecCtx->height; fwrite(pFrameYUV->data[0],1,y_size,fp_yuv); //Y fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv); //U fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv); //V #endif //SDL--------------------------- #if 0 SDL_UpdateTexture( sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0] ); #else SDL_UpdateYUVTexture(sdlTexture, &sdlRect, pFrameYUV->data[0], pFrameYUV->linesize[0], pFrameYUV->data[1], pFrameYUV->linesize[1], pFrameYUV->data[2], pFrameYUV->linesize[2]); #endif SDL_RenderClear( sdlRenderer ); SDL_RenderCopy( sdlRenderer, sdlTexture, NULL, &sdlRect); SDL_RenderPresent( sdlRenderer ); //SDL End----------------------- //Delay 40ms SDL_Delay(40); } } av_free_packet(packet); } //flush decoder //FIX: Flush Frames remained in Codec while (1) { ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if (ret < 0) break; if (!got_picture) break; sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); #if OUTPUT_YUV420P int y_size=pCodecCtx->width*pCodecCtx->height; fwrite(pFrameYUV->data[0],1,y_size,fp_yuv); //Y fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv); //U fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv); //V #endif //SDL--------------------------- SDL_UpdateTexture( sdlTexture, &sdlRect, pFrameYUV->data[0], pFrameYUV->linesize[0] ); SDL_RenderClear( sdlRenderer ); SDL_RenderCopy( sdlRenderer, sdlTexture, NULL, &sdlRect); SDL_RenderPresent( sdlRenderer ); //SDL End----------------------- //Delay 40ms SDL_Delay(40); } sws_freeContext(img_convert_ctx); #if OUTPUT_YUV420P fclose(fp_yuv); #endif SDL_Quit(); av_frame_free(&pFrameYUV); av_frame_free(&pFrame); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return 0; }