TTF_Font *TTF_OpenFont(const char *file, int ptsize) { TTF_Font *font; TT_Face_Properties properties; TT_Instance_Metrics imetrics; int i, n; TT_UShort platform, encoding; TT_Error error; font = (TTF_Font *)malloc(sizeof(*font)); if ( font == NULL ) { SDL_SetError("Out of memory"); return(NULL); } memset(font, 0, sizeof(*font)); /* Open the font and create ancillary data */ error = TT_Open_Face(engine, file, &font->face); if ( error ) { SDL_SetError("Couldn't load font file"); free(font); return(NULL); } error = TT_New_Glyph(font->face, &font->glyph); if ( error ) { SDL_SetError("Couldn't create glyph container"); TTF_CloseFont(font); return(NULL); } error = TT_New_Instance(font->face, &font->inst); if ( error ) { SDL_SetError("Couldn't create font instance"); TTF_CloseFont(font); return(NULL); } /* Set the display resolution */ error = TT_Set_Instance_Resolutions(font->inst, 72, 72); if ( error ) { SDL_SetError("Couldn't set font resolution"); TTF_CloseFont(font); return(NULL); } error = TT_Set_Instance_CharSize(font->inst, ptsize*64); if ( error ) { SDL_SetError("Couldn't set font size"); TTF_CloseFont(font); return(NULL); } /* Get a Unicode mapping for this font */ n = TT_Get_CharMap_Count(font->face); for ( i=0; i<n; ++i ) { TT_Get_CharMap_ID(font->face, i, &platform, &encoding); if ( ((platform == TT_PLATFORM_MICROSOFT) && (encoding == TT_MS_ID_UNICODE_CS)) || ((platform == TT_PLATFORM_APPLE_UNICODE) && (encoding == TT_APPLE_ID_DEFAULT)) ) { TT_Get_CharMap(font->face, i, &font->map); break; } } if ( i == n ) { SDL_SetError("Font doesn't have a Unicode mapping"); TTF_CloseFont(font); return(NULL); } /* Get the font metrics for this font */ TT_Get_Face_Properties(font->face, &properties ); TT_Get_Instance_Metrics(font->inst, &imetrics); font->pointsize = imetrics.y_ppem; font->ascent = (float)properties.horizontal->Ascender / properties.header->Units_Per_EM; font->ascent *= font->pointsize; font->descent = (float)properties.horizontal->Descender / properties.header->Units_Per_EM; font->descent *= font->pointsize; font->lineskip = (float)properties.horizontal->Line_Gap / properties.header->Units_Per_EM; font->lineskip *= font->pointsize; font->height = round(font->ascent - font->descent); /* Set the default font style */ font->style = TTF_STYLE_NORMAL; font->glyph_overhang = font->pointsize/10; /* x offset = cos(((90.0-12)/360)*2*M_PI), or 12 degree angle */ font->glyph_italics = 0.207; font->glyph_italics *= font->height; return(font); }
void destruct_display(displayer* d) { TTF_CloseFont(d->police); free(d); }
int main(int argc, char *argv[]) { int i, j; SDL_Texture *texture = NULL; TTF_Font *font; texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB555, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); Button button[20]; for(i = 0; i < 20; i++){ button[i].button_rect.x = button_x[i/5] + 4; button[i].button_rect.y = button_y[i%5] + 3; button[i].button_rect.w = BUTTON_WIDTH - 8; button[i].button_rect.h = BUTTON_HEIGHT - 6; button[i].button_char = button_ch[i]; button[i].button_status = 0; } if(!init()) { printf("Failed to initialize!"); }else{ int quit = 0; SDL_Event e; while(!quit){ SDL_SetRenderTarget(renderer, texture); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); SDL_SetRenderTarget(renderer, texture); SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); for(i = 0; i < 4; i++){ SDL_RenderDrawLine(renderer, button_x[i], button_y[0], button_x[i], SCREEN_HEIGHT); } for(i = 0; i < 5; i++){ SDL_RenderDrawLine(renderer, button_x[0], button_y[i], SCREEN_WIDTH, button_y[i]); } for(i = 0; i < 20; i++){ StatusButton(button[i]); font = TTF_OpenFont("Choko.ttf", 35); SDL_Color ttf_color = {0, 0, 0}; SDL_Texture *ttexture; SDL_Surface *surface; SDL_Rect rect; ttexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB555, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); surface = TTF_RenderText_Solid(font, button[i].button_char, ttf_color); ttexture = SDL_CreateTextureFromSurface(renderer, surface); TTF_SizeText(font, button[i].button_char, &rect.w, &rect.h); rect.x = button[i].button_rect.x + (BUTTON_WIDTH - rect.w)/2; rect.y = button[i].button_rect.y + (BUTTON_HEIGHT - rect.h)/2; SDL_SetRenderTarget(renderer, ttexture); SDL_RenderCopyEx(renderer, ttexture, NULL, &rect, 0.0, NULL, SDL_FLIP_NONE); SDL_FreeSurface(surface); SDL_DestroyTexture(ttexture); TTF_CloseFont(font); } while(SDL_PollEvent(&e) != 0){ if(e.type == SDL_QUIT){ quit = 1; }else if(e.type == SDL_MOUSEBUTTONDOWN){ if(e.button.button == SDL_BUTTON_LEFT){ SDL_Point point; SDL_GetMouseState(&point.x, &point.y); for(i = 0; i < 20; i++){ if(PointInRect(point, button[i].button_rect)) button[i].button_status = 1; } } }else{ for(i = 0; i < 20; i++){ button[i].button_status = 0; } } } SDL_SetRenderTarget(renderer, NULL); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } } TTF_Quit(); SDL_DestroyRenderer(renderer); renderer = NULL; SDL_DestroyWindow(window); window = NULL; SDL_Quit(); return 0; }
TTF_Font* TTF_OpenFontIndexRW( SDL_RWops *src, int freesrc, int ptsize, long index ) { TTF_Font* font; FT_Error error; FT_Face face; FT_Fixed scale; FT_Stream stream; int position; if ( ! TTF_initialized ) { TTF_SetError( "Library not initialized" ); return NULL; } /* Check to make sure we can seek in this stream */ position = SDL_RWtell(src); if ( position < 0 ) { TTF_SetError( "Can't seek in stream" ); return NULL; } font = (TTF_Font*) malloc(sizeof *font); if ( font == NULL ) { TTF_SetError( "Out of memory" ); return NULL; } memset(font, 0, sizeof(*font)); font->src = src; font->freesrc = freesrc; stream = (FT_Stream)malloc(sizeof(*stream)); if ( stream == NULL ) { TTF_SetError( "Out of memory" ); TTF_CloseFont( font ); return NULL; } memset(stream, 0, sizeof(*stream)); stream->read = RWread; stream->descriptor.pointer = src; stream->pos = (unsigned long)position; SDL_RWseek(src, 0, SEEK_END); stream->size = (unsigned long)(SDL_RWtell(src) - position); SDL_RWseek(src, position, SEEK_SET); font->args.flags = FT_OPEN_STREAM; font->args.stream = stream; error = FT_Open_Face( library, &font->args, index, &font->face ); if( error ) { TTF_SetFTError( "Couldn't load font file", error ); TTF_CloseFont( font ); return NULL; } face = font->face; /* Make sure that our font face is scalable (global metrics) */ if ( FT_IS_SCALABLE(face) ) { /* Set the character size and use default DPI (72) */ error = FT_Set_Char_Size( font->face, 0, ptsize * 64, 0, 0 ); if( error ) { TTF_SetFTError( "Couldn't set font size", error ); TTF_CloseFont( font ); return NULL; } /* Get the scalable font metrics for this font */ scale = face->size->metrics.y_scale; font->ascent = FT_CEIL(FT_MulFix(face->ascender, scale)); font->descent = FT_CEIL(FT_MulFix(face->descender, scale)); font->height = font->ascent - font->descent + /* baseline */ 1; font->lineskip = FT_CEIL(FT_MulFix(face->height, scale)); font->underline_offset = FT_FLOOR(FT_MulFix(face->underline_position, scale)); font->underline_height = FT_FLOOR(FT_MulFix(face->underline_thickness, scale)); } else { /* Non-scalable font case. ptsize determines which family * or series of fonts to grab from the non-scalable format. * It is not the point size of the font. * */ if ( ptsize >= font->face->num_fixed_sizes ) ptsize = font->face->num_fixed_sizes - 1; font->font_size_family = ptsize; error = FT_Set_Pixel_Sizes( face, face->available_sizes[ptsize].height, face->available_sizes[ptsize].width ); /* With non-scalale fonts, Freetype2 likes to fill many of the * font metrics with the value of 0. The size of the * non-scalable fonts must be determined differently * or sometimes cannot be determined. * */ font->ascent = face->available_sizes[ptsize].height; font->descent = 0; font->height = face->available_sizes[ptsize].height; font->lineskip = FT_CEIL(font->ascent); font->underline_offset = FT_FLOOR(face->underline_position); font->underline_height = FT_FLOOR(face->underline_thickness); } if ( font->underline_height < 1 ) { font->underline_height = 1; } #ifdef DEBUG_FONTS printf("Font metrics:\n"); printf("\tascent = %d, descent = %d\n", font->ascent, font->descent); printf("\theight = %d, lineskip = %d\n", font->height, font->lineskip); printf("\tunderline_offset = %d, underline_height = %d\n", font->underline_offset, font->underline_height); #endif /* Set the default font style */ font->style = TTF_STYLE_NORMAL; font->glyph_overhang = face->size->metrics.y_ppem / 10; /* x offset = cos(((90.0-12)/360)*2*M_PI), or 12 degree angle */ font->glyph_italics = 0.207f; font->glyph_italics *= font->height; return font; }
int main(int argc, char* args[]) { bool loop = true; srand(time(0)); SDL_Event event; int ticks; int mouseX, mouseY; init(); SDL_Surface *text = NULL; stringstream ss; Block newBlock(0, 0, 16, 16); Block drawBlock(0, 0, 16, 16); list<Block> blockList; list<Block>::iterator it_Block; list<Bullet> bulletList; list<Bullet>::iterator it_Bullet; list<Explosion> explosionList; list<Explosion>::iterator it_Explosion; for (int i = 0; i < LEVEL_WIDTH / 16; i++) { newBlock.rect.y = SCREEN_HEIGHT - 16; newBlock.rect.x = i * 16; blockList.push_back(newBlock); if (i % 3 == 0) { newBlock.rect.y = SCREEN_HEIGHT - 32; newBlock.rect.x = i * 16; blockList.push_back(newBlock); } if (i % 3 == 0) { newBlock.rect.y = SCREEN_HEIGHT - 48; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 64; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 80; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 96; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 112; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 128; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 144; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 160; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 176; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 192; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 208; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 224; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 240; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 256; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 272; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 288; newBlock.rect.x = i * 16; blockList.push_back(newBlock); newBlock.rect.y = SCREEN_HEIGHT - 304; newBlock.rect.x = i * 16; blockList.push_back(newBlock); } } if (true) //load surfaces { playerImage = load_image("playerImage.bmp"); bullet1Image = load_image("bullet1.bmp"); bullet2Image = load_image("bullet2.bmp"); bullet3Image = load_image("bullet3.bmp"); explosion1 = load_image("explosion/01.bmp", true, 255, 255, 255); explosion2 = load_image("explosion/02.bmp", true, 255, 255, 255); explosion3 = load_image("explosion/03.bmp", true, 255, 255, 255); explosion4 = load_image("explosion/04.bmp", true, 255, 255, 255); blockImage = load_image("blockImage.bmp"); inventoryImage = load_image("inventoryImage.bmp"); } Player player(32, SCREEN_HEIGHT - 32, 16, 16); while (loop) { ticks = SDL_GetTicks(); //Handle Events while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { loop = false; } if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_w) { bool jumped = false; for (it_Block = blockList.begin(); it_Block != blockList.end(); it_Block++) { if (player.check_collision(it_Block->rect, 0, 1)) { player.ySpeed = -8; jumped = true; } } if (!jumped) { for (it_Block = blockList.begin(); it_Block != blockList.end(); it_Block++) { if (player.check_collision(it_Block->rect, 1, 0)) { player.ySpeed = -8; player.xSpeed = -8; jumped = true; } } } if (!jumped) { for (it_Block = blockList.begin(); it_Block != blockList.end(); it_Block++) { if (player.check_collision(it_Block->rect, -1, 0)) { player.ySpeed = -8; player.xSpeed = 8; jumped = true; } } } } if (event.key.keysym.sym == SDLK_SPACE) { player.shoot(mouseX, mouseY, &bulletList); } } if (event.type == SDL_MOUSEBUTTONDOWN) { if (event.button.button == SDL_BUTTON_RIGHT) { player.next_gun(); } if (event.button.button == SDL_BUTTON_WHEELDOWN) { if (player.power >= 6) player.power -= 5; else player.power = 1; } if (event.button.button == SDL_BUTTON_WHEELUP) { if (player.power == 1) player.power = 5; else if (player.power <= 95) player.power += 5; else player.power = 100; } } } //Game Logic Uint8 *keyStates = SDL_GetKeyState(NULL); SDL_GetMouseState(&mouseX, &mouseY); player.move(keyStates); player.gravity(); player.step(); player.block_collision(blockList); for (it_Bullet = bulletList.begin(); it_Bullet != bulletList.end(); it_Bullet++) { it_Bullet->step(); it_Bullet->gravity(); for (it_Block = blockList.begin(); it_Block != blockList.end(); it_Block++) { if (it_Bullet->check_collision(it_Block->rect)) { if (it_Bullet->explode) { create_explosion(it_Bullet->rect.x - 8, it_Bullet->rect.y - 8, &explosionList); it_Block = blockList.erase(it_Block); } it_Bullet = bulletList.erase(it_Bullet); } } } //Clear screen SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 255, 255, 255)); //Draw to screen player.draw(); bulletList.remove_if(bullet_dead); explosionList.remove_if(explosion_dead); for (it_Block = blockList.begin(); it_Block != blockList.end(); it_Block++) { it_Block->draw(); } for (it_Bullet = bulletList.begin(); it_Bullet != bulletList.end(); it_Bullet++) { it_Bullet->draw(); } for (it_Explosion = explosionList.begin(); it_Explosion != explosionList.end(); it_Explosion++) { it_Explosion->draw(); } //Draw inventory and status bars draw_inventory(player); //Show screen SDL_Flip(screen); if (SDL_GetTicks() - ticks < 1000 / FPS) { SDL_Delay((1000 / FPS) - (SDL_GetTicks() - ticks)); } } if (true) //free surfaces { SDL_FreeSurface(playerImage); SDL_FreeSurface(bullet1Image); SDL_FreeSurface(bullet2Image); SDL_FreeSurface(bullet3Image); SDL_FreeSurface(explosion1); SDL_FreeSurface(explosion2); SDL_FreeSurface(explosion3); SDL_FreeSurface(explosion4); SDL_FreeSurface(blockImage); SDL_FreeSurface(inventoryImage); SDL_FreeSurface(text); TTF_CloseFont(font); } //quit SDL TTF_Quit(); SDL_Quit(); return 0; }
void rtTextUtil::cleanup() { TTF_CloseFont(RT_LARGE_FONT); TTF_CloseFont(RT_MEDIUM_FONT); TTF_CloseFont(RT_SMALL_FONT); }
/** \brief Clean SDL_TTF stuff */ static void video_clean_text() { TTF_CloseFont(font); TTF_Quit(); }
BattleScene::~BattleScene(){ TTF_CloseFont(font); }
int main ( int argc, char** argv ) { if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "Unable to init SDL: %s\n", SDL_GetError() ); return 1; } atexit(SDL_Quit); screen = SDL_SetVideoMode(SCREENW, SCREENH, 32, SDL_HWSURFACE|SDL_DOUBLEBUF); if ( !screen ) { printf("Unable to set 800x600 video: %s\n", SDL_GetError()); return 1; } SDL_WM_SetCaption("Szit the Game", NULL); if( TTF_Init() == -1 ) { printf("Unable to initialize font"); return 1; } font=TTF_OpenFont("tahoma.ttf", 28); if(font){printf("Success");} // centre the bitmap on screen CGameManager manager; bool done = false; CBlock blockT(0, -1, 0, 0, 0, 1, 0, 0, -1, 100, 100, 100); //t blockT.TryTurn(); blockT.Turn(); blockT.TryTurn(); blockT.Turn(); CBlock blockZ(0, -1,-1,0,-1,0,0,1,0, 198,255,126); //z CBlock blockS(0, -1,0,0,0,0,-1,1,-1, 126,196,255); //s CBlock blockO(1, 0,0,1,0,0,1,1,1, 100, 100, 0); //o CBlock blockI(0, 0,-1,0,0,0,1,0,2, 255,159,126); //i CBlock blockJ(0, -1,1,0,1,0,0,0,-1, 139,77,156); //j CBlock blockL(0, 0,-1,0,0,0,1,1,1, 255,229,126); //l CBlock GameBlock(0, -1, 0, 0, 0, 1, 0, 0, -1, 179,206,221); //creating t CBlock NextBlock(0, -1, 0, 0, 0, 1, 0, 0, -1, 179,206,221); //t //CBlock GameBlock(0, -1,0,0,0,0,-1,1,-1); //s //CBlock GameBlock(0, 0,-1,0,0,0,1,0,2); //i CButton start(300, 350, 200, 50, 100, 100, 100, 150, 150, 150, 1, "Start"); CButton help(300, 425, 200, 50, 100, 100, 100, 150, 150, 150, 0, "Help"); CButton exit(300, 500, 200, 50, 100, 100, 100, 150, 150, 150, 0, "Exit"); CButton easy(100, 350, 200, 50, 200, 200, 200, 255, 255, 255, 0, "Easy"); CButton medium(300, 350, 200, 50, 200, 200, 200, 255, 255, 255, 1, "Medium"); CButton hard(500, 350, 200, 50, 200, 200, 200, 255, 255, 255, 0, "Hard"); manager.Refresh(&GameBlock, &NextBlock); manager.Refresh(&GameBlock, &NextBlock); srand(time(NULL)); switch(rand()%7){ case 0: GameBlock.Set(0, -1, 0, 0, 0, 1, 0, 0, -1,179,206,221);break; //t case 1: GameBlock.Set(0, -1,-1,0,-1,0,0,1,0, 198,255,126);break; //z case 2: GameBlock.Set(0, -1,0,0,0,0,-1,1,-1, 126,196,255);break; //s case 3: GameBlock.Set(1, 0,0,1,0,0,1,1,1, 100, 100, 0);break; //o case 4: GameBlock.Set(0, 0,-1,0,0,0,1,0,2, 255,159,126);break; //i case 5: GameBlock.Set(0, -1,1,0,1,0,0,0,-1, 139,77,156);break; //j case 6: GameBlock.Set(0, 0,-1,0,0,0,1,1,1, 255,229,126);break; //l } srand(time(NULL)+SDL_GetTicks()); switch(rand()%7){ case 0: NextBlock.Set(0, -1, 0, 0, 0, 1, 0, 0, -1,179,206,221);break; //t case 1: NextBlock.Set(0, -1,-1,0,-1,0,0,1,0, 198,255,126);break; //z case 2: NextBlock.Set(0, -1,0,0,0,0,-1,1,-1, 126,196,255);break; //s case 3: NextBlock.Set(1, 0,0,1,0,0,1,1,1, 100, 100, 0);break; //o case 4: NextBlock.Set(0, 0,-1,0,0,0,1,0,2, 255,159,126);break; //i case 5: NextBlock.Set(0, -1,1,0,1,0,0,0,-1, 139,77,156);break; //j case 6: NextBlock.Set(0, 0,-1,0,0,0,1,1,1, 255,229,126);break; //l } // program main loop while (!done) { // message processing loop SDL_Event event; ++frame; SetFPS(); LastFrame=SDL_GetTicks(); if(gamestatus==1){manager.Refresh(&GameBlock, &NextBlock); } while (SDL_PollEvent(&event)) { // check for messages switch (event.type) { // exit if the window is closed case SDL_QUIT: done = true; break; // check for keypresses case SDL_KEYDOWN: { // exit if ESCAPE is pressed if (event.key.keysym.sym == SDLK_ESCAPE) {done = true;} if(!gamestatus) { if(event.key.keysym.sym == SDLK_DOWN){ if(start.Active()){start.ChangeActivity(); help.ChangeActivity();}else if(help.Active()){help.ChangeActivity(); exit.ChangeActivity();}else if(exit.Active()){exit.ChangeActivity(); start.ChangeActivity();} } else if(event.key.keysym.sym == SDLK_UP){ if(start.Active()){start.ChangeActivity(); exit.ChangeActivity();}else if(help.Active()){help.ChangeActivity(); start.ChangeActivity();}else if(exit.Active()){exit.ChangeActivity(); help.ChangeActivity();} } if(event.key.keysym.sym == SDLK_RETURN){ if(start.Active()){gamestatus=3;} else if(help.Active()){gamestatus=5;} else if(exit.Active()){done=1;} } }else if(gamestatus==1){ if(event.key.keysym.sym == SDLK_DOWN){ manager.MoveBlockDown(&GameBlock, 1); } if(event.key.keysym.sym == SDLK_SPACE){ manager.TurnGameBlock(&GameBlock); } if(event.key.keysym.sym == SDLK_LEFT){ manager.MoveBlockLeft(&GameBlock); } if(event.key.keysym.sym == SDLK_RIGHT){ manager.MoveBlockRight(&GameBlock); } if(event.key.keysym.sym == SDLK_w){ manager.SpeedUp(); } if(event.key.keysym.sym ==SDLK_p){ gamestatus=2; } }else if(gamestatus==2){ if(event.key.keysym.sym ==SDLK_p){ gamestatus=1; } }else if(gamestatus==3){ if(event.key.keysym.sym == SDLK_RETURN){ if(easy.Active()){manager.SetLevel(1);}else if(medium.Active()){manager.SetLevel(2);}else if(hard.Active()){manager.SetLevel(3);} gamestatus=1; }else if(event.key.keysym.sym == SDLK_RIGHT){ if(easy.Active()){easy.ChangeActivity(); medium.ChangeActivity();}else if(medium.Active()){medium.ChangeActivity(); hard.ChangeActivity();}else if(hard.Active()){hard.ChangeActivity(); easy.ChangeActivity();} }else if(event.key.keysym.sym == SDLK_LEFT){ if(easy.Active()){easy.ChangeActivity(); hard.ChangeActivity();}else if(medium.Active()){medium.ChangeActivity(); easy.ChangeActivity();}else if(hard.Active()){hard.ChangeActivity(); medium.ChangeActivity();} } }else if(gamestatus==4){ if(event.key.keysym.sym){ SDL_Delay(1000); gamestatus=0; manager.ClearGame(); } }else if(gamestatus==5){ if(event.key.keysym.sym){ gamestatus=0; } } break; } } // end switch }// end of message processing // DRAWING STARTS HERE // clear screen SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0)); // draw bitmap if(gamestatus==0){ int a=SDL_GetTicks(); RBC_DrawRect(0, 0, screen->w, screen->h, 0, 0, 50); RBC_DrawRect((0+frame/2)%screen->w, 0, screen->w/5, screen->h, 105,210,231); if(((0+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((0+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 105,210,231);} RBC_DrawRect((screen->w/5+frame/2)%screen->w, 0, screen->w/5, screen->h, 167,219,216); if(((screen->w/5+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 167,219,216);} RBC_DrawRect((screen->w/5*2+frame/2)%screen->w, 0, screen->w/5, screen->h, 224,228,204); if(((screen->w/5*2+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*2+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 224,228,204);} RBC_DrawRect((screen->w/5*3+frame/2)%screen->w, 0, screen->w/5, screen->h, 243,134,48); if(((screen->w/5*3+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*3+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 243,134,48);} RBC_DrawRect((screen->w/5*4+frame/2)%screen->w, 0, screen->w/5, screen->h, 250,105,0); if(((screen->w/5*4+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*4+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 250,105,0);} blockS.Draw(-100, 90+sin(a/100)*50); blockZ.Draw(50, 90+sin(a/100+10)*50); blockI.Draw(200, 90+sin(a/100+20)*50); blockT.Draw(350, 90+sin(a/100+30)*50); start.Draw(); help.Draw(); exit.Draw(); }else if(gamestatus==1){ switch(manager.ReturnSpeed()){ case 2:RBC_DrawRect(0, 0, screen->w, screen->h, 105,210,231);break; case 4:RBC_DrawRect(0, 0, screen->w, screen->h, 167,219,216);break; case 6:RBC_DrawRect(0, 0, screen->w, screen->h, 224,228,204);break; case 8:RBC_DrawRect(0, 0, screen->w, screen->h, 243,134,48);break; case 10:RBC_DrawRect(0, 0, screen->w, screen->h, 250,105,0);break; case 12:RBC_DrawRect(0, 0, screen->w, screen->h, 250,70,0);break; case 14:RBC_DrawRect(0, 0, screen->w, screen->h, 250,35,0);break; case 16:RBC_DrawRect(0, 0, screen->w, screen->h, 250,10,0);break; case 18:RBC_DrawRect(0, 0, screen->w, screen->h, 250,0,0);break; } RBC_DrawRect(245, 0, 310, 600, 0,0,0); RBC_DrawRect(250, 0, 300, 600, 85,98,112); RBC_DrawRect(570, 70, 210, 210, 0,0,0); RBC_DrawRect(575, 75, 200, 200, 200, 200, 200); GameBlock.Draw(manager.GetGameBlockX()*30, manager.GetGameBlockY()*30); NextBlock.Draw(375, 150); manager.DrawTable(); RBC_Write(575, 300, "Speed:", screen); RBC_Write(675, 300, manager.ReturnSpeed(), screen); RBC_Write(575, 330, "Lines:", screen); RBC_Write(675, 330, manager.ReturnDone(), screen); RBC_Write(575, 360, "Score:", screen); RBC_Write(675, 360, manager.ReturnScore(), screen); }else if(gamestatus==2){ switch(manager.ReturnSpeed()){ case 2:RBC_DrawRect(0, 0, screen->w, screen->h, 105,210,231);break; case 4:RBC_DrawRect(0, 0, screen->w, screen->h, 167,219,216);break; case 6:RBC_DrawRect(0, 0, screen->w, screen->h, 224,228,204);break; case 8:RBC_DrawRect(0, 0, screen->w, screen->h, 243,134,48);break; case 10:RBC_DrawRect(0, 0, screen->w, screen->h, 250,105,0);break; case 12:RBC_DrawRect(0, 0, screen->w, screen->h, 250,70,0);break; case 14:RBC_DrawRect(0, 0, screen->w, screen->h, 250,35,0);break; case 16:RBC_DrawRect(0, 0, screen->w, screen->h, 250,10,0);break; case 18:RBC_DrawRect(0, 0, screen->w, screen->h, 250,0,0);break; } RBC_DrawRect(245, 0, 310, 600, 0,0,0); RBC_DrawRect(250, 0, 300, 600, 85,98,112); RBC_Write(360, 250, "Pause", screen); }else if(gamestatus==3){ RBC_DrawRect((0+frame/2)%screen->w, 0, screen->w/5, screen->h, 105,210,231); if(((0+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((0+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 105,210,231);} RBC_DrawRect((screen->w/5+frame/2)%screen->w, 0, screen->w/5, screen->h, 167,219,216); if(((screen->w/5+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 167,219,216);} RBC_DrawRect((screen->w/5*2+frame/2)%screen->w, 0, screen->w/5, screen->h, 224,228,204); if(((screen->w/5*2+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*2+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 224,228,204);} RBC_DrawRect((screen->w/5*3+frame/2)%screen->w, 0, screen->w/5, screen->h, 243,134,48); if(((screen->w/5*3+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*3+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 243,134,48);} RBC_DrawRect((screen->w/5*4+frame/2)%screen->w, 0, screen->w/5, screen->h, 250,105,0); if(((screen->w/5*4+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*4+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 250,105,0);} easy.Draw(); medium.Draw(); hard.Draw(); }else if(gamestatus==4){ switch(manager.ReturnSpeed()){ case 2:RBC_DrawRect(0, 0, screen->w, screen->h, 105,210,231);break; case 4:RBC_DrawRect(0, 0, screen->w, screen->h, 167,219,216);break; case 6:RBC_DrawRect(0, 0, screen->w, screen->h, 224,228,204);break; case 8:RBC_DrawRect(0, 0, screen->w, screen->h, 243,134,48);break; case 10:RBC_DrawRect(0, 0, screen->w, screen->h, 250,105,0);break; case 12:RBC_DrawRect(0, 0, screen->w, screen->h, 250,70,0);break; case 14:RBC_DrawRect(0, 0, screen->w, screen->h, 250,35,0);break; case 16:RBC_DrawRect(0, 0, screen->w, screen->h, 250,10,0);break; case 18:RBC_DrawRect(0, 0, screen->w, screen->h, 250,0,0);break; } RBC_DrawRect(245, 0, 310, 600, 0,0,0); RBC_DrawRect(250, 0, 300, 600, 85,98,112); RBC_DrawRect(570, 70, 210, 210, 0,0,0); RBC_DrawRect(575, 75, 200, 200, 200, 200, 200); GameBlock.Draw(manager.GetGameBlockX()*30, manager.GetGameBlockY()*30); NextBlock.Draw(375, 150); manager.DrawTable(); RBC_Write(575, 300, "Speed:", screen); RBC_Write(675, 300, manager.ReturnSpeed(), screen); RBC_Write(575, 330, "Lines:", screen); RBC_Write(675, 330, manager.ReturnDone(), screen); RBC_Write(575, 360, "Score:", screen); RBC_Write(675, 360, manager.ReturnScore(), screen); for(int i=0; i<screen->w/2; i++){ for(int j=0; j<screen->h/2; j++){ RBC_DrawRect(i*2, j*2, 1,1, 0,0,0); } } RBC_Write(300, 300, "Game Over", screen); RBC_Write(300, 350, manager.ReturnScore(), screen); }else if(gamestatus==5){ RBC_DrawRect((0+frame/2)%screen->w, 0, screen->w/5, screen->h, 105,210,231); if(((0+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((0+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 105,210,231);} RBC_DrawRect((screen->w/5+frame/2)%screen->w, 0, screen->w/5, screen->h, 167,219,216); if(((screen->w/5+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 167,219,216);} RBC_DrawRect((screen->w/5*2+frame/2)%screen->w, 0, screen->w/5, screen->h, 224,228,204); if(((screen->w/5*2+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*2+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 224,228,204);} RBC_DrawRect((screen->w/5*3+frame/2)%screen->w, 0, screen->w/5, screen->h, 243,134,48); if(((screen->w/5*3+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*3+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 243,134,48);} RBC_DrawRect((screen->w/5*4+frame/2)%screen->w, 0, screen->w/5, screen->h, 250,105,0); if(((screen->w/5*4+frame/2)%screen->w+screen->w/5)>screen->w){RBC_DrawRect(0, 0, ((screen->w/5*4+frame/2)%screen->w+screen->w/5)-screen->w, screen->h, 250,105,0);} RBC_Write(20, 300, "Use left and right arrow to move block sideways", screen); RBC_Write(20, 350, "Use down arrow to move block down faster for extra points", screen); RBC_Write(20, 400, "Use space to turn falling tetramino", screen); RBC_Write(20, 450, "Hit 'P' to pause game", screen); } RBC_Write(10, 20, "FPS: ", screen);RBC_Write(70, 20, GetFPS(), screen); // DRAWING ENDS HERE // finally, update the screen :) SDL_Flip(screen); } // end main loop // free loaded bitmap TTF_CloseFont(font); TTF_Quit(); // all is well ;) printf("Exited cleanly\n"); return 0; }
static void cleanupFonts() { for(FontPool::iterator ii=fontPool->begin(); ii!=fontPool->end(); ii++) TTF_CloseFont(ii->second); fontPool->clear(); }
void BattleScene::displayCharacterInfo(){ SDL_Surface *temp; TTF_Font *tempFont; SDL_Rect tempLoc; tempFont = TTF_OpenFont("../Fonts/coolvetica.ttf",25); SDL_Color fgColor = {255,255,255}; std::ostringstream oss; oss << player->getName(); temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); tempLoc.x = 10+594; tempLoc.y = 0; SDL_BlitSurface(temp,NULL,scene->getScreen(),&tempLoc); SDL_FreeSurface(temp); oss.str(""); oss << "HP: "; temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); tempLoc.x = 10+594; tempLoc.y = 30; SDL_BlitSurface(temp,NULL,scene->getScreen(),&tempLoc); //change color of HP oss.str(""); oss << player->getHP() << "/" << player->getMaxHP(); if(player->getHP() == player->getMaxHP()){ fgColor.r = 0; fgColor.g = 255; fgColor.b = 50; } else if(player->getHP() <= player->getMaxHP()/4){ fgColor.g = 255; fgColor.g = 10; fgColor.b = 0; } else if(player->getHP() <= player->getMaxHP()/2){ fgColor.r = 255; fgColor.g = 150; fgColor.b = 0; } else{ fgColor.g = 255; fgColor.g = 255; fgColor.b = 255; } temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); tempLoc.x = 90+594; tempLoc.y = 30; SDL_BlitSurface(temp,NULL,scene->getScreen(),&tempLoc); SDL_FreeSurface(temp); fgColor.r = 255; fgColor.g = 255; fgColor.b = 255; oss.str(""); oss << "MP: "; temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); tempLoc.x = 10+594; tempLoc.y = 60; SDL_BlitSurface(temp,NULL,scene->getScreen(),&tempLoc); //change color of HP oss.str(""); oss << player->getMP() << "/" << player->getMaxMP(); if(player->getMP() == player->getMaxMP()){ fgColor.r = 0; fgColor.g = 100; fgColor.b = 255; } else if(player->getMP() <= player->getMaxMP()/4){ fgColor.g = 255; fgColor.g = 50; fgColor.b = 0; } else if(player->getMP() <= player->getMaxMP()/2){ fgColor.r = 192; fgColor.g = 255; fgColor.b = 0; } else{ fgColor.r = 0; fgColor.g = 255; fgColor.b = 126; } temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); tempLoc.x = 90+594; tempLoc.y = 60; temp = TTF_RenderText_Blended(tempFont,oss.str().c_str(),fgColor); SDL_BlitSurface(temp,NULL,scene->getScreen(),&tempLoc); SDL_FreeSurface(temp); TTF_CloseFont(tempFont); }
/** * Destructor. */ Menu::~Menu() { TTF_CloseFont(font); TTF_Quit(); }
int main(int argc, char *argv[]) { Uint32 initflags = SDL_INIT_VIDEO; //| SDL_DOUBLEBUF; /* See documentation for details */ SDL_Surface *ecran, *rectangle, *board, *texte1; // quelques surfaces Dimensions fenetre; // main window fenetre.h = WINHI; // en pixels fenetre.w = WINWI; Uint8 video_bpp = 32; // 32 bits de couleur Uint32 videoflags = SDL_HWSURFACE; // utiliser la mémoire vidéo Uint32 vert, rouge; // des variables pour des couleurs bool continuer; // pour la boucle principale des évènements SDL_Event event; // aussi /* Initialize the SDL library */ if ( SDL_Init(initflags) < 0 ) { fprintf(stderr, "N'arrive pas a` initialiser la SDL : %s\n", SDL_GetError()); exit(1); } /* Set video mode */ ecran = SDL_SetVideoMode(fenetre.w, fenetre.h, video_bpp, videoflags); // surface principale if (ecran == NULL) { fprintf(stderr, "N'arrive pas a` etablir mode video%dx%dx%d : %s\n", fenetre.w, fenetre.h, video_bpp, SDL_GetError()); SDL_Quit(); exit(2); } vert = SDL_MapRGB(ecran->format,0,128,0); // c'est du vert rouge = SDL_MapRGB(ecran->format,255,0,0); // c'est du rouge SDL_FillRect(ecran,NULL,vert); // de la couleur dans le fond de la fenêtre principale SDL_WM_SetCaption("Jeu de Hex", NULL); // legende de la fenêtre // Une autre surface avec du texte TTF_Init(); TTF_Font *fontMenu = TTF_OpenFont("CAC-Champagne/cac_champagne.ttf",60); // charger une fonte (un peu moche) SDL_Color fontBlack = {0,0,0}; texte1 = TTF_RenderText_Blended(fontMenu,"Projet Hex !",fontBlack); // encore une surface rectangle = SDL_CreateRGBSurface(initflags,225,80,video_bpp,0,0,0,0); // une autre surface pour inclure dans l'autre SDL_FillRect(rectangle,NULL,rouge); // un fond rouge // position des surfaces SDL_Rect posRect, posTexte1; posRect.x = 20; posRect.y = 80; posTexte1.x = 25; posTexte1.y = 85; SDL_BlitSurface(rectangle,NULL,ecran,&posRect); // on associe avec la fenêtre principale SDL_BlitSurface(texte1,NULL,ecran,&posTexte1); // idem pour superposer avec la précédente // Affichage du plateau de jeu board = IMG_Load("Images/hex.png"); // plateau de jeu la taille en pixels est celle de l'image SDL_Rect posBoard; // sa position posBoard.x = 280; posBoard.y = 100; SDL_BlitSurface(board,NULL,ecran,&posBoard); // on l'associe avec la surface principale // affichage du pion bleu SDL_Surface *pionBleu; pionBleu = IMG_Load("Images/button-blue22.png"); SDL_Rect posPionBleu; posPionBleu.x = 385; posPionBleu.y = 149; SDL_BlitSurface(pionBleu,NULL,ecran,&posPionBleu); // Affichege du pion rouge SDL_Surface *pionRouge = IMG_Load("Images/button-red22.png"); SDL_Rect posPionRouge; posPionRouge.x = 543; posPionRouge.y = 273; SDL_BlitSurface(pionRouge,NULL,ecran,&posPionRouge); SDL_Flip(ecran); //maj des surfaces // boucle des évènements continuer = true; // un furieux du c ferait plutôt une boucle infinie. Je préfère rester correct. SDLKey key_pressed ; while (continuer) { while ( SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEMOTION: printf("Ça bouge\n"); // sans intérêt, c'est juste pour montrer break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) { int clicX = event.motion.x; int clicY = event.motion.y; printf("X=%d Y=%d\n",clicX,clicY); // on récupère les coordonnées du clic } break; case SDL_KEYDOWN: key_pressed = event.key.keysym.sym; // on récupère la touche switch (key_pressed) { case SDLK_ESCAPE: /* Esc keypress quits the app... */ continuer = false; break; case SDLK_LEFT: printf("left +1\n"); // par exemple break; case SDLK_RIGHT: printf("right +1\n"); break; case SDLK_UP: printf("up +1\n"); break; case SDLK_DOWN: printf("down +1\n"); break; } break; case SDL_QUIT: continuer = false; break; default: break; } } // refresh screen // mettre ici tous les blit utiles s'il y a des changements dans les surfaces, board, nouveaux pions SDL_Flip(ecran); //maj des surfaces pour affichage } // /* Clean up the SDL library */ SDL_FreeSurface(ecran); SDL_FreeSurface(rectangle); SDL_FreeSurface(board); TTF_CloseFont(fontMenu); SDL_FreeSurface(texte1); TTF_Quit(); SDL_Quit(); return(0); }
SDLTrueTypeFont::~SDLTrueTypeFont() { TTF_CloseFont(mFont); }
Font::Font(std::string font, U32 size,Owner loc, C cs, C ce) { // Initialize SDL_ttf if (!TTF_WasInit()) { TTF_Init(); } static const std::string middle_path = "Resources/Fonts/"; font = BASE_PATHS[loc] + middle_path + font + ".ttf"; TTF_Font* f = TTF_OpenFont(font.c_str(), size); if (f == nullptr) { fprintf(stderr, "Failed to open TTF font %s\n", font); fflush(stderr); throw 281; } _fontHeight = TTF_FontHeight(f); _regStart = cs; _regLength = ce - cs + 1; int padding = size / 8; // First neasure all the regions glm::ivec4* glyphRects = new glm::ivec4[_regLength]; int i = 0, advance; for (char c = cs; c <= ce; c++) { TTF_GlyphMetrics(f, c, &glyphRects[i].x, &glyphRects[i].z, &glyphRects[i].y, &glyphRects[i].w, &advance); glyphRects[i].z -= glyphRects[i].x; glyphRects[i].x = 0; glyphRects[i].w -= glyphRects[i].y; glyphRects[i].y = 0; i++; } // Find best partitioning of glyphs int rows = 1, w, h, area = MAX_TEXTURE_RES * MAX_TEXTURE_RES, bestRows = 0; t.width = 0; t.height = 0; std::vector<int>* bestPartition = nullptr; while (rows <= _regLength) { h = rows * (padding + _fontHeight) + padding; auto gr = createRows(glyphRects, _regLength, rows, padding, w); // Desire a power of 2 texture w = closestPow2(w); h = closestPow2(h); // A texture must be feasible if (w > MAX_TEXTURE_RES || h > MAX_TEXTURE_RES) { rows++; delete[] gr; continue; } // Check for minimal area if (area >= w * h) { if (bestPartition) delete[] bestPartition; bestPartition = gr; t.width = w; t.height = h; bestRows = rows; area = t.width * t.height; rows++; } else { delete[] gr; break; } } // Can a bitmap font be made? if (!bestPartition) { fprintf(stderr, "Failed to Map TTF font %s to texture. Try lowering resolution.\n", font); fflush(stderr); throw 282; } // Create the texture glGenTextures(1, &t.id); glBindTexture(GL_TEXTURE_2D, t.id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, t.width, t.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // Now draw all the glyphs SDL_Color fg = { 255, 255, 255, 255 }; int ly = padding; for (int ri = 0; ri < bestRows; ri++) { int lx = padding; for (int ci = 0; ci < bestPartition[ri].size(); ci++) { int gi = bestPartition[ri][ci]; SDL_Surface* glyphSurface = TTF_RenderGlyph_Blended(f, (char)(cs + gi), fg); // Pre-multiplication occurs here unsigned char* sp = (unsigned char*)glyphSurface->pixels; int cp = glyphSurface->w * glyphSurface->h * 4; for (int i = 0; i < cp; i += 4) { float a = sp[i + 3] / 255.0f; sp[i] *= (unsigned char) a; sp[i + 1] = sp[i]; sp[i + 2] = sp[i]; } // Save glyph image and update coordinates glTexSubImage2D(GL_TEXTURE_2D, 0, lx, t.height - ly - 1 - glyphSurface->h, glyphSurface->w, glyphSurface->h, GL_BGRA, GL_UNSIGNED_BYTE, glyphSurface->pixels); glyphRects[gi].x = lx; glyphRects[gi].y = ly; glyphRects[gi].z = glyphSurface->w; glyphRects[gi].w = glyphSurface->h; SDL_FreeSurface(glyphSurface); glyphSurface = nullptr; lx += glyphRects[gi].z + padding; } ly += _fontHeight + padding; } // Draw the unsupported glyph int rs = padding - 1; int* pureWhiteSquare = new int[rs * rs]; memset(pureWhiteSquare, 0xffffffff, rs * rs * sizeof(int)); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, rs, rs, GL_RGBA, GL_UNSIGNED_BYTE, pureWhiteSquare); delete[] pureWhiteSquare; pureWhiteSquare = nullptr; // Set some texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Create spriteBatch glyphs _glyphs = new CharGlyph[_regLength + 1]; for (i = 0; i < _regLength; i++) { _glyphs[i].character = (char)(cs + i); _glyphs[i].size = glm::vec2(glyphRects[i].z, glyphRects[i].w); _glyphs[i].uvRect = glm::vec4( (float)glyphRects[i].x / (float)t.width, (float)glyphRects[i].y / (float)t.height, (float)glyphRects[i].z / (float)t.width, (float)glyphRects[i].w / (float)t.height ); } _glyphs[_regLength].character = ' '; _glyphs[_regLength].size = _glyphs[0].size; _glyphs[_regLength].uvRect = glm::vec4(0, 0, (float)rs / (float)t.width, (float)rs / (float)t.height); glBindTexture(GL_TEXTURE_2D, 0); delete[] glyphRects; delete[] bestPartition; TTF_CloseFont(f); }
bool font_init(void) { bool error = false; // we'll be bypassing the NXSurface automatic scaling features // and drawing at the real resolution so we can get better-looking fonts. sdl_screen = screen->GetSDLSurface(); // at 320x240 switch to bitmap fonts for better appearance #ifdef CONFIG_ENABLE_TTF if (SCALE == 1) #endif { stat("fonts: using bitmapped from %s", bmpfontfile); SDL_Surface *sheet = SDL_LoadBMP(bmpfontfile); if (!sheet) { staterr("Couldn't open bitmap font file: '%s'", bmpfontfile); return 1; } uint32_t fgindex = SDL_MapRGB(sheet->format, 255, 255, 255); error |= whitefont.InitBitmapChars(sheet, fgindex, 0xffffff); error |= greenfont.InitBitmapChars(sheet, fgindex, 0x00ff80); error |= bluefont.InitBitmapChars(sheet, fgindex, 0xa0b5de); error |= shadowfont.InitBitmapCharsShadowed(sheet, fgindex, 0xffffff, 0x000000); } #ifdef CONFIG_ENABLE_TTF else { stat("fonts: using truetype at %dpt", pointsize[SCALE]); // initilize normal TTF fonts if (TTF_Init() < 0) { staterr("Couldn't initialize SDL_ttf: %s", TTF_GetError()); return 1; } TTF_Font *font = TTF_OpenFont(ttffontfile, pointsize[SCALE]); if (!font) { staterr("Couldn't open font: '%s'", ttffontfile); return 1; } error |= whitefont.InitChars(font, 0xffffff); error |= greenfont.InitChars(font, 0x00ff80); error |= bluefont.InitChars(font, 0xa0b5de); error |= shadowfont.InitCharsShadowed(font, 0xffffff, 0x000000); TTF_CloseFont(font); } #endif error |= create_shade_sfc(); if (error) return 1; fontheight = (whitefont.letters['M']->h / SCALE); initilized = true; return 0; }
GLuint* description(GLuint *textureId, int type){ int ray = 0; int puissance = 0; int cadence = 0.0; int cost = 0; int timeConst; //en fonction du type de tower switch(type) { case 1: ray = 200; puissance = 700; cadence = 9; cost = 15; timeConst = 2; break; case 2: ray = 80; puissance = 100; cadence = 1; cost = 20; timeConst = 10; break; case 3: ray = 100; puissance = 70; cadence = 2; cost = 30; timeConst = 1; break; case 4: ray = 200; puissance = 200; cadence = 5; cost = 10; timeConst = 2; break; default: break; } char valeurRay[25] = "Rayon : "; char valeurPui[25] = "Puissance : "; char valeurCad[25] = "Cadence : 0."; char valeurCou[25] = "Cout : "; char valeurCons[30] = "Construction : "; sprintf(valeurRay+8, "%d", ray); sprintf(valeurPui+12, "%d", puissance); sprintf(valeurCad+12, "%d", cadence); sprintf(valeurCou+7, "%d", cost); sprintf(valeurCons+15, "%d", timeConst); //printf("%s", valeurRay); //printf("%s", valeurCons); //strcat(valeur," Cout : "); TTF_Font *police = NULL; SDL_Surface *texte = NULL; SDL_Color couleurBlanche = {255, 255, 255}; /* Chargement de la police */ police = TTF_OpenFont("images/hoog0656.ttf", 12); // Bind the texture object glEnable(GL_TEXTURE_2D); glBindTexture( GL_TEXTURE_2D, textureId[10]); // Set the texture's stretching properties glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glLoadIdentity(); glTranslatef(850,660,1); ////////////// /////TYPE//// ////////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ switch(type) { case 1: texte = TTF_RenderText_Blended(police, "Rocket", couleurBlanche); break; case 2: texte = TTF_RenderText_Blended(police, "Laser", couleurBlanche); break; case 3: texte = TTF_RenderText_Blended(police, "Mitraillette", couleurBlanche); break; case 4: texte = TTF_RenderText_Blended(police, "Hybride", couleurBlanche); break; default: texte = TTF_RenderText_Blended(police, "TYPE", couleurBlanche); break; } // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(0+texte->w, 100+texte->h); glTexCoord2f(0, 0); glVertex2f(0, 100+texte->h); glTexCoord2f(0, 1); glVertex2f(0,100); glTexCoord2f(1, 1); glVertex2f(0+texte->w, 100); glEnd(); ////////////// /////RAYON//// ////////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ texte = TTF_RenderText_Blended(police, valeurRay, couleurBlanche); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(0+texte->w, 80+texte->h); glTexCoord2f(0, 0); glVertex2f(0, 80+texte->h); glTexCoord2f(0, 1); glVertex2f(0,80); glTexCoord2f(1, 1); glVertex2f(0+texte->w, 80); glEnd(); ////////////////// /////PUISSANCE//// ////////////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ texte = TTF_RenderText_Blended(police, valeurPui, couleurBlanche); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(texte->w, 60+texte->h); glTexCoord2f(0, 0); glVertex2f(0, 60+texte->h); glTexCoord2f(0, 1); glVertex2f(0,60); glTexCoord2f(1, 1); glVertex2f(0+texte->w, 60); glEnd(); //////////////// /////CADENCE//// //////////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ texte = TTF_RenderText_Blended(police, valeurCad, couleurBlanche); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(texte->w, 40+texte->h); glTexCoord2f(0, 0); glVertex2f(0, 40+texte->h); glTexCoord2f(0, 1); glVertex2f(0,40); glTexCoord2f(1, 1); glVertex2f(texte->w, 40); glEnd(); ///////////// /////Cout//// ///////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ texte = TTF_RenderText_Blended(police, valeurCou, couleurBlanche); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(texte->w, 20+texte->h); glTexCoord2f(0, 0); glVertex2f(0, 20+texte->h); glTexCoord2f(0, 1); glVertex2f(0,20); glTexCoord2f(1, 1); glVertex2f(texte->w, 20); glEnd(); ///////////// /////Construction//// ///////////// /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */ texte = TTF_RenderText_Blended(police, valeurCons, couleurBlanche); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texte->w, texte->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texte->pixels ); glBegin(GL_QUADS); glColor3ub(255,255,255); glTexCoord2f(1, 0); glVertex2f(texte->w, texte->h); glTexCoord2f(0, 0); glVertex2f(0, texte->h); glTexCoord2f(0, 1); glVertex2f(0,0); glTexCoord2f(1, 1); glVertex2f(texte->w, 0); glEnd(); glBindTexture( GL_TEXTURE_2D, 0 ); glDisable(GL_TEXTURE_2D); TTF_CloseFont(police); SDL_FreeSurface(texte); return textureId; }
Typeface::~Typeface() { // just in case SDL_ttf is shut down before we get here if (TTF_WasInit()) { TTF_CloseFont(font); } }
void free_font() { if (font) { TTF_CloseFont(font); font = 0; } }
void clean_up() { //free all surfaces SDL_FreeSurface( background ); SDL_FreeSurface (frisbee1); SDL_FreeSurface (frisbee2); SDL_FreeSurface (frisbee3); SDL_FreeSurface (frisbee4); SDL_FreeSurface (frisbee5); SDL_FreeSurface (frisbee6); SDL_FreeSurface (frisbee7); SDL_FreeSurface (frisbee8); SDL_FreeSurface (frisbee9); SDL_FreeSurface (frisbee10); SDL_FreeSurface (frisbee11); SDL_FreeSurface (frisbee12); SDL_FreeSurface (frisbee13); SDL_FreeSurface (frisbee14); SDL_FreeSurface (frisbee15); SDL_FreeSurface (frisbee16); SDL_FreeSurface (frisbee17); SDL_FreeSurface (frisbee18); SDL_FreeSurface (frisbee19); SDL_FreeSurface (frisbee20); SDL_FreeSurface (frisbee21); SDL_FreeSurface (frisbee22); SDL_FreeSurface (frisbee23); SDL_FreeSurface (frisbee24); SDL_FreeSurface (frisbee25); SDL_FreeSurface (frisbee26); SDL_FreeSurface (frisbee27); SDL_FreeSurface (frisbee28); SDL_FreeSurface (frisbee29); SDL_FreeSurface (frisbee30); SDL_FreeSurface (frisbee31); SDL_FreeSurface (frisbee32); SDL_FreeSurface (frisbee33); SDL_FreeSurface (frisbee34); SDL_FreeSurface (frisbee35); SDL_FreeSurface (frisbee36); SDL_FreeSurface (frisbee37); SDL_FreeSurface (frisbee38); SDL_FreeSurface (frisbee39); SDL_FreeSurface (frisbee40); SDL_FreeSurface (frisbee41); SDL_FreeSurface (frisbee42); SDL_FreeSurface (frisbee43); SDL_FreeSurface (frisbee44); SDL_FreeSurface (frisbee45); SDL_FreeSurface (arrow0); SDL_FreeSurface (left45); SDL_FreeSurface (left30); SDL_FreeSurface (left15); SDL_FreeSurface (right45); SDL_FreeSurface (right30); SDL_FreeSurface (right15); SDL_FreeSurface (angle0); SDL_FreeSurface (angle3); SDL_FreeSurface (angle6); SDL_FreeSurface (angle9); SDL_FreeSurface (angle12); SDL_FreeSurface (angle15); SDL_FreeSurface (message); SDL_FreeSurface (p0); SDL_FreeSurface (p1); SDL_FreeSurface (p2); SDL_FreeSurface (p3); SDL_FreeSurface (p4); SDL_FreeSurface (p5); SDL_FreeSurface (p6); SDL_FreeSurface (p7); SDL_FreeSurface (p8); SDL_FreeSurface (p9); SDL_FreeSurface (p10); SDL_FreeSurface (p11); SDL_FreeSurface (p12); SDL_FreeSurface (p13); SDL_FreeSurface (p14); SDL_FreeSurface (p15); SDL_FreeSurface (horzText); SDL_FreeSurface (vertText); SDL_FreeSurface (scoreText); SDL_FreeSurface (scoreHoleText); SDL_FreeSurface (hitText); // free music Mix_FreeMusic(music); //close fonts TTF_CloseFont(font); TTF_CloseFont(font2); //Quit Mixer Mix_CloseAudio(); TTF_Quit(); std::cout<<"Quitting SDL..."<<std::endl; //quit sdl SDL_Quit(); }
ImageFromText::~ImageFromText() { TTF_CloseFont(font); }
void ReinforcementPictures<T>::displayLoop() { #if 0 // initialization logging.info("Starting SDL init (0).."); SDL_Init(0); logging.info("Starting SDL subsystem init (events, video, audio).."); if(SDL_InitSubSystem(SDL_INIT_EVENTS) != 0){ logging.error("SDL_Init(EVENTS) failed."); SDL_Quit(); running = false; return; } if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0){ logging.error("SDL_Init(VIDEO) failed."); SDL_Quit(); running = false; return; } if(SDL_InitSubSystem(SDL_INIT_AUDIO) != 0){ logging.error("SDL_Init(AUDIO) failed."); SDL_Quit(); running = false; return; } logging.info("SDL_Init() events, video, audio successful."); #endif // opens SDL display SDL_Window* window = NULL; int W = 640; int H = 480; SDL_DisplayMode mode; if(SDL_GetCurrentDisplayMode(0, &mode) == 0){ W = (3*mode.w)/4; H = (3*mode.h)/4; } else{ whiteice::logging.error("SDL_GetCurrentDisplayMode() failed"); running = false; SDL_Quit(); return; } #if 0 if(TTF_Init() != 0){ char buffer[80]; snprintf(buffer, 80, "TTF_Init failed: %s\n", TTF_GetError()); logging.error(buffer); TTF_Quit(); SDL_Quit(); running = false; return; } else logging.info("Starting TTF_Init() done.."); int flags = IMG_INIT_JPG | IMG_INIT_PNG; if(IMG_Init(flags) != flags){ char buffer[80]; snprintf(buffer, 80, "IMG_Init failed: %s\n", IMG_GetError()); logging.error(buffer); IMG_Quit(); TTF_Quit(); SDL_Quit(); running = false; return; } #endif window = SDL_CreateWindow("Tranquility", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, W, H, SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_INPUT_FOCUS); if(window == NULL){ whiteice::logging.error("SDL_CreateWindow() failed\n"); running = false; return; } SDL_RaiseWindow(window); SDL_UpdateWindowSurface(window); SDL_RaiseWindow(window); // loads font TTF_Font* font = NULL; TTF_Font* font2 = NULL; { double fontSize = 100.0*sqrt(((float)(W*H))/(640.0*480.0)); unsigned int fs = (unsigned int)fontSize; if(fs <= 0) fs = 10; font = TTF_OpenFont(fontname.c_str(), fs); fontSize = 25.0*sqrt(((float)(W*H))/(640.0*480.0)); fs = (unsigned int)fontSize; if(fs <= 0) fs = 10; font2 = TTF_OpenFont(fontname.c_str(), fs); } // loads all pictures std::vector<SDL_Surface*> images; images.resize(pictures.size()); actionFeatures.resize(pictures.size()); { for(unsigned int i=0;i<pictures.size();i++) images[i] = NULL; unsigned int numLoaded = 0; #pragma omp parallel for shared(images) shared(numLoaded) schedule(dynamic) for(unsigned int i=0;i<pictures.size();i++) { if(running == false) continue; SDL_Surface* image = NULL; #pragma omp critical { // IMG_loader functions ARE NOT thread-safe so // we cannot load files parallel image = IMG_Load(pictures[i].c_str()); } if(image == NULL){ char buffer[120]; snprintf(buffer, 120, "Loading image FAILED (%s): %s", SDL_GetError(), pictures[i].c_str()); whiteice::logging.warn(buffer); printf("ERROR: %s\n", buffer); image = SDL_CreateRGBSurface(0, W, H, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(image == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } SDL_FillRect(image, NULL, SDL_MapRGB(image->format, 0, 0, 0)); } SDL_Rect imageRect; SDL_Surface* scaled = NULL; if(image->w >= image->h){ double wscale = ((double)W)/((double)image->w); scaled = SDL_CreateRGBSurface(0, (int)(image->w*wscale), (int)(image->h*wscale), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(scaled == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0) whiteice::logging.warn("SDL_BlitScaled fails"); } else{ double hscale = ((double)H)/((double)image->h); scaled = SDL_CreateRGBSurface(0, (int)(image->w*hscale), (int)(image->h*hscale), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(scaled == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0) whiteice::logging.warn("SDL_BlitScaled fails"); } images[i] = scaled; if(image) SDL_FreeSurface(image); // creates feature vector (mini picture) of the image { actionFeatures[i].resize(this->dimActionFeatures); calculateFeatureVector(images[i], actionFeatures[i]); } numLoaded++; // displays pictures that are being loaded #pragma omp critical { imageRect.w = scaled->w; imageRect.h = scaled->h; imageRect.x = (W - scaled->w)/2; imageRect.y = (H - scaled->h)/2; SDL_Surface* surface = SDL_GetWindowSurface(window); if(surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0)); SDL_BlitSurface(scaled, NULL, surface, &imageRect); if(font){ SDL_Color white = { 255, 255, 255 }; char message[80]; snprintf(message, 80, "%d/%d", numLoaded, pictures.size()); SDL_Surface* msg = TTF_RenderUTF8_Blended(font, message, white); if(msg != NULL){ SDL_Rect messageRect; messageRect.x = (W - msg->w)/2; messageRect.y = (H - msg->h)/2; messageRect.w = msg->w; messageRect.h = msg->h; SDL_BlitSurface(msg, NULL, surface, &messageRect); SDL_FreeSurface(msg); } } SDL_UpdateWindowSurface(window); SDL_ShowWindow(window); SDL_FreeSurface(surface); } } SDL_Event event; while(SDL_PollEvent(&event)){ if(event.type == SDL_KEYDOWN){ keypresses++; continue; } } } } long long start_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); unsigned int index = 0; // selects HMM initial state randomly according to starting state probabilities auto pi = hmm.getPI(); currentHMMstate = hmm.sample(pi); while(running){ initialized = true; SDL_Event event; while(SDL_PollEvent(&event)){ if(event.type == SDL_KEYDOWN){ keypresses++; continue; } } if(dev->connectionOk() == false){ whiteice::logging.info("ReinforcementPictures: Device connection failed"); running = false; continue; } // waits for full picture show time { const long long end_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); long long delta_ms = end_ms - start_ms; if(delta_ms < DISPLAYTIME){ std::this_thread::sleep_for(std::chrono::milliseconds(DISPLAYTIME - delta_ms)); // usleep((DISPLAYTIME - delta_ms)*1000); } } // updates HMM hidden state after action { std::vector<float> after; std::vector<T> state; after.resize(dev->getNumberOfSignals()); for(auto& a : after) a = 0.0f; dev->data(after); state.resize(after.size()); for(unsigned int i=0;i<state.size();i++){ state[i] = after[i]; } const unsigned int o = clusters.getClusterIndex(state); unsigned int nextState = currentHMMstate; const double p = hmm.next_state(currentHMMstate, nextState, o); currentHMMstate = nextState; } // adds previous action to performedActionsQueue { std::lock_guard<std::mutex> lock(performedActionsMutex); performedActionsQueue.push_back(index); } // waits for a command (picture) to show index = 0; { while(running){ { std::lock_guard<std::mutex> lock(actionMutex); if(actionQueue.size() > 0){ index = actionQueue.front(); actionQueue.pop_front(); break; } } usleep(10); } if(!running) continue; } // if we are in random mode we choose random pictures if(random) index = rng.rand() % images.size(); { SDL_Surface* surface = SDL_GetWindowSurface(window); if(surface != NULL){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0)); SDL_Rect imageRect; imageRect.w = images[index]->w; imageRect.h = images[index]->h; imageRect.x = (W - images[index]->w)/2; imageRect.y = (H - images[index]->h)/2; SDL_BlitSurface(images[index], NULL, surface, &imageRect); if(font2 && message.size() > 0){ SDL_Color white = { 255, 255, 255 }; SDL_Surface* msg = TTF_RenderUTF8_Blended(font2, message.c_str(), white); if(msg != NULL){ SDL_Rect messageRect; messageRect.x = (W - msg->w)/2; messageRect.y = (H - msg->h)/2; messageRect.w = msg->w; messageRect.h = msg->h; SDL_BlitSurface(msg, NULL, surface, &messageRect); SDL_FreeSurface(msg); } } SDL_UpdateWindowSurface(window); SDL_ShowWindow(window); SDL_FreeSurface(surface); } } start_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); } SDL_DestroyWindow(window); if(font){ TTF_CloseFont(font); font = NULL; } if(font2){ TTF_CloseFont(font2); font2 = NULL; } #if 0 logging.info("SDL deinitialization started"); IMG_Quit(); TTF_Quit(); SDL_Quit(); logging.info("SDL deinitialization.. DONE"); #endif }
int main(int argc, char *argv[]) { char *argv0 = argv[0]; SDL_Window *window; SDL_GLContext context; TTF_Font *font; SDL_Surface *text; int ptsize; int i, done; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; GLenum gl_error; GLuint texture; int x, y, w, h; GLfloat texcoord[4]; GLfloat texMinX, texMinY; GLfloat texMaxX, texMaxY; float color[8][3]= {{ 1.0, 1.0, 0.0}, { 1.0, 0.0, 0.0}, { 0.0, 0.0, 0.0}, { 0.0, 1.0, 0.0}, { 0.0, 1.0, 1.0}, { 1.0, 1.0, 1.0}, { 1.0, 0.0, 1.0}, { 0.0, 0.0, 1.0}}; float cube[8][3]= {{ 0.5, 0.5, -0.5}, { 0.5, -0.5, -0.5}, {-0.5, -0.5, -0.5}, {-0.5, 0.5, -0.5}, {-0.5, 0.5, 0.5}, { 0.5, 0.5, 0.5}, { 0.5, -0.5, 0.5}, {-0.5, -0.5, 0.5}}; SDL_Event event; int renderstyle; int dump; enum { RENDER_LATIN1, RENDER_UTF8, RENDER_UNICODE } rendertype; char *message; /* Look for special execution mode */ dump = 0; /* Look for special rendering types */ renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; /* Default is black and white */ forecol = &black; backcol = &white; for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) { if ( strcmp(argv[i], "-utf8") == 0 ) { rendertype = RENDER_UTF8; } else if ( strcmp(argv[i], "-unicode") == 0 ) { rendertype = RENDER_UNICODE; } else if ( strcmp(argv[i], "-b") == 0 ) { renderstyle |= TTF_STYLE_BOLD; } else if ( strcmp(argv[i], "-i") == 0 ) { renderstyle |= TTF_STYLE_ITALIC; } else if ( strcmp(argv[i], "-u") == 0 ) { renderstyle |= TTF_STYLE_UNDERLINE; } else if ( strcmp(argv[i], "-dump") == 0 ) { dump = 1; } else if ( strcmp(argv[i], "-fgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } forecol->r = (Uint8)r; forecol->g = (Uint8)g; forecol->b = (Uint8)b; } else if ( strcmp(argv[i], "-bgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } backcol->r = (Uint8)r; backcol->g = (Uint8)g; backcol->b = (Uint8)b; } else { fprintf(stderr, Usage, argv0); return(1); } } argv += i; argc -= i; /* Check usage */ if ( ! argv[0] ) { fprintf(stderr, Usage, argv0); return(1); } /* Initialize the TTF library */ if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); SDL_Quit(); return(2); } /* Open the font file with the requested point size */ ptsize = 0; if ( argc > 1 ) { ptsize = atoi(argv[1]); } if ( ptsize == 0 ) { i = 2; ptsize = DEFAULT_PTSIZE; } else { i = 3; } font = TTF_OpenFont(argv[0], ptsize); if ( font == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, argv[0], SDL_GetError()); cleanup(2); } TTF_SetFontStyle(font, renderstyle); if( dump ) { for( i = 48; i < 123; i++ ) { SDL_Surface* glyph = NULL; glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol ); if( glyph ) { char outname[64]; sprintf( outname, "glyph-%d.bmp", i ); SDL_SaveBMP( glyph, outname ); } } cleanup(0); } /* Set a 640x480 video mode */ window = SDL_CreateWindow("glfont", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL); if ( window == NULL ) { fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError()); cleanup(2); } context = SDL_GL_CreateContext(window); if ( context == NULL ) { fprintf(stderr, "Couldn't create OpenGL context: %s\n", SDL_GetError()); cleanup(2); } /* Render and center the message */ if ( argc > 2 ) { message = argv[2]; } else { message = DEFAULT_TEXT; } switch (rendertype) { case RENDER_LATIN1: text = TTF_RenderText_Blended(font, message, *forecol); break; case RENDER_UTF8: text = TTF_RenderUTF8_Blended(font, message, *forecol); break; case RENDER_UNICODE: { /* This doesn't actually work because you can't pass UNICODE text in via command line, AFAIK, but... */ Uint16 unicode_text[BUFSIZ]; int index; for ( index = 0; (message[0] || message[1]); ++index ) { unicode_text[index] = ((Uint8 *)message)[0]; unicode_text[index] <<= 8; unicode_text[index] |= ((Uint8 *)message)[1]; message += 2; } text = TTF_RenderUNICODE_Blended(font, unicode_text, *forecol); } break; default: text = NULL; /* This shouldn't happen */ break; } if ( text == NULL ) { fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError()); TTF_CloseFont(font); cleanup(2); } x = (WIDTH - text->w)/2; y = (HEIGHT - text->h)/2; w = text->w; h = text->h; printf("Font is generally %d big, and string is %d big\n", TTF_FontHeight(font), text->h); /* Convert the text into an OpenGL texture */ glGetError(); texture = SDL_GL_LoadTexture(text, texcoord); if ( (gl_error = glGetError()) != GL_NO_ERROR ) { /* If this failed, the text may exceed texture size limits */ printf("Warning: Couldn't create texture: 0x%x\n", gl_error); } /* Make texture coordinates easy to understand */ texMinX = texcoord[0]; texMinY = texcoord[1]; texMaxX = texcoord[2]; texMaxY = texcoord[3]; /* We don't need the original text surface anymore */ SDL_FreeSurface(text); /* Initialize the GL state */ glViewport( 0, 0, WIDTH, HEIGHT ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glOrtho( -2.0, 2.0, -2.0, 2.0, -20.0, 20.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); /* Wait for a keystroke, and blit text on mouse press */ done = 0; while ( ! done ) { while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_MOUSEMOTION: x = event.motion.x - w/2; y = event.motion.y - h/2; break; case SDL_KEYDOWN: case SDL_QUIT: done = 1; break; default: break; } } /* Clear the screen */ glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Draw the spinning cube */ glBegin( GL_QUADS ); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[7]); glVertex3fv(cube[7]); glEnd( ); /* Rotate the cube */ glMatrixMode(GL_MODELVIEW); glRotatef(5.0, 1.0, 1.0, 1.0); /* Show the text on the screen */ SDL_GL_Enter2DMode(WIDTH, HEIGHT); glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(texMinX, texMinY); glVertex2i(x, y ); glTexCoord2f(texMaxX, texMinY); glVertex2i(x+w, y ); glTexCoord2f(texMinX, texMaxY); glVertex2i(x, y+h); glTexCoord2f(texMaxX, texMaxY); glVertex2i(x+w, y+h); glEnd(); SDL_GL_Leave2DMode(); /* Swap the buffers so everything is visible */ SDL_GL_SwapWindow(window); } SDL_GL_DeleteContext(context); TTF_CloseFont(font); cleanup(0); /* Not reached, but fixes compiler warnings */ return 0; }
int main() { char filename[106] = "data/grille.txt"; char buffer[500]; char buffer2[300]; SDL_Surface *screen, *temp, *sprite, *backbg, *monster, *wall, *trap, *life, *sword, *armor, *door, *text, *defatt; SDL_Rect rcSprite, rcGrass, rcMonster, rcWall, rcTrap, rcLife, rcSword, rcArmor, rcDoor, rcText, rcDefatt; SDL_Event event; TTF_Font *font; SDL_Color white = {255, 255, 255}; Uint8 *keystate; int colorkey, gameover = 0; SDL_Init(SDL_INIT_VIDEO); TTF_Init(); SDL_WM_SetCaption("Lab", "Lab"); screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0); colorkey = SDL_MapRGB(screen->format, 255, 0, 255); temp = IMG_Load("data/perso.bmp"); sprite = SDL_DisplayFormat(temp); SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); temp = IMG_Load("data/monstre.bmp"); monster = SDL_DisplayFormat(temp); SDL_SetColorKey(monster, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); font = TTF_OpenFont("data/a.ttf", 14); temp = SDL_LoadBMP("data/sol.bmp"); backbg = SDL_DisplayFormat(temp); temp = SDL_LoadBMP("data/mur.bmp"); wall = SDL_DisplayFormat(temp); temp = SDL_LoadBMP("data/piege.bmp"); trap = SDL_DisplayFormat(temp); temp = SDL_LoadBMP("data/potion.bmp"); life = SDL_DisplayFormat(temp); SDL_SetColorKey(life, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); temp = SDL_LoadBMP("data/epee.bmp"); sword = SDL_DisplayFormat(temp); SDL_SetColorKey(sword, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); temp = SDL_LoadBMP("data/armure.bmp"); armor = SDL_DisplayFormat(temp); SDL_SetColorKey(armor, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); temp = SDL_LoadBMP("data/porte.bmp"); door = SDL_DisplayFormat(temp); joueur * j = alloue_joueur(); grille * g = creer_grille(filename, j); monstre * m = creer_monstre(g); rcSprite.x = j->x*SPRITE_SIZE; rcSprite.y = j->y*SPRITE_SIZE; rcMonster.x = m->x*SPRITE_SIZE; rcMonster.y = m->y*SPRITE_SIZE; rcText.x = 32; rcText.y = SCREEN_HEIGHT - 32; rcDefatt.x = 32; rcDefatt.y = SCREEN_HEIGHT - 16; while ((gameover != 1)) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: gameover = 1; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: gameover = 1; case SDLK_q: gameover = 1; break; default: break; } break; } keystate = SDL_GetKeyState(NULL); if ((keystate[SDLK_LEFT]) && (gameover != 2) ) { deplacement(g,j,113); sprintf(buffer, "Remaining lives: %d", j->vie); text = TTF_RenderText_Solid(font, buffer, white); if (g->content[j->y][j->x] == 8) { sprintf(buffer, "You won! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } if (m -> vie > 0) deplacement_monstre(g, j, m); if (j->vie <=0 ) { sprintf(buffer, "You lost! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } rcSprite.x = (j->x)*STEP_SIZE; rcMonster.x = (m->x)*STEP_SIZE; sprintf(buffer2, "Points of attack: %d Points of defense: %d", j->attaque, j->defense); defatt = TTF_RenderText_Solid(font, buffer2, white); } if (keystate[SDLK_RIGHT] && (gameover != 2) ) { deplacement(g,j,100); sprintf(buffer, "Remaining lives: %d", j->vie); text = TTF_RenderText_Solid(font, buffer, white); if (g->content[j->y][j->x] == 8) { sprintf(buffer, "You won! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } if (m -> vie > 0) deplacement_monstre(g, j, m); if (j->vie <=0 ) { sprintf(buffer, "You lost! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } rcSprite.x = (j->x)*STEP_SIZE; rcMonster.x = (m->x)*STEP_SIZE; sprintf(buffer2, "Points of attack: %d Points of defense: %d", j->attaque, j->defense); defatt = TTF_RenderText_Solid(font, buffer2, white); } if (keystate[SDLK_UP] && (gameover != 2) ) { deplacement(g,j,122); sprintf(buffer, "Remaining lives: %d", j->vie); text = TTF_RenderText_Solid(font, buffer, white); if (g->content[j->y][j->x] == 8) { sprintf(buffer, "You won! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } if (m -> vie > 0) deplacement_monstre(g, j, m); if (j->vie <=0 ) { sprintf(buffer, "You lost! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } rcSprite.y = (j->y)*STEP_SIZE; rcMonster.y = (m->y)*STEP_SIZE; sprintf(buffer2, "Points of attack: %d Points of defense: %d", j->attaque, j->defense); defatt = TTF_RenderText_Solid(font, buffer2, white); } if (keystate[SDLK_DOWN] && (gameover != 2) ) { deplacement(g,j,115); sprintf(buffer, "Remaining lives: %d", j->vie); text = TTF_RenderText_Solid(font, buffer, white); if (g->content[j->y][j->x] == 8) { sprintf(buffer, "You won! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } if (m -> vie > 0) deplacement_monstre(g, j, m); if (j->vie <=0 ) { sprintf(buffer, "You lost! Press Q or ESC to quit"); text = TTF_RenderText_Solid(font, buffer, white); gameover = 2; } rcSprite.y = (j->y)*STEP_SIZE; rcMonster.y = (m->y)*STEP_SIZE; sprintf(buffer2, "Points of attack: %d Points of defense: %d", j->attaque, j->defense); defatt = TTF_RenderText_Solid(font, buffer2, white); } if ( rcSprite.x < 0 ) { rcSprite.x = 0; } else if ( rcSprite.x > SCREEN_WIDTH-SPRITE_SIZE ) { rcSprite.x = SCREEN_WIDTH-SPRITE_SIZE; } if ( rcSprite.y < 0 ) { rcSprite.y = 0; } else if ( rcSprite.y > SCREEN_HEIGHT-SPRITE_SIZE ) { rcSprite.y = SCREEN_HEIGHT-SPRITE_SIZE; } for (int i = 0; i < (g -> n); i++) { for (int j = 0; j < (g -> m); j++) { switch (g->content[i][j]) { case 0 : rcGrass.x = j * SPRITE_SIZE; rcGrass.y = i * SPRITE_SIZE; SDL_BlitSurface(backbg, NULL, screen, &rcGrass); break; case 1 : rcWall.x = j * SPRITE_SIZE; rcWall.y = i * SPRITE_SIZE; SDL_BlitSurface(wall, NULL, screen, &rcWall); break; case 2 : rcTrap.x = j * SPRITE_SIZE; rcTrap.y = i * SPRITE_SIZE; SDL_BlitSurface(trap, NULL, screen, &rcTrap); break; case 3 : rcGrass.x = j * SPRITE_SIZE; rcGrass.y = i * SPRITE_SIZE; SDL_BlitSurface(backbg, NULL, screen, &rcGrass); rcLife.x = j * SPRITE_SIZE; rcLife.y = i * SPRITE_SIZE; SDL_BlitSurface(life, NULL, screen, &rcLife); break; case 6 : rcGrass.x = j * SPRITE_SIZE; rcGrass.y = i * SPRITE_SIZE; SDL_BlitSurface(backbg, NULL, screen, &rcGrass); rcArmor.x = j * SPRITE_SIZE; rcArmor.y = i * SPRITE_SIZE; SDL_BlitSurface(armor, NULL, screen, &rcArmor); break; case 7 : rcGrass.x = j * SPRITE_SIZE; rcGrass.y = i * SPRITE_SIZE; SDL_BlitSurface(backbg, NULL, screen, &rcGrass); rcSword.x = j * SPRITE_SIZE; rcSword.y = i * SPRITE_SIZE; SDL_BlitSurface(sword, NULL, screen, &rcSword); break; case 8 : rcDoor.x = j * SPRITE_SIZE; rcDoor.y = i * SPRITE_SIZE; SDL_BlitSurface(door, NULL, screen, &rcDoor); break; default : rcGrass.x = j * SPRITE_SIZE; rcGrass.y = i * SPRITE_SIZE; SDL_BlitSurface(backbg, NULL, screen, &rcGrass); break; } } } drawRectCairo(screen); SDL_BlitSurface(sprite, NULL, screen, &rcSprite); if (m -> vie > 0) SDL_BlitSurface(monster, NULL, screen, &rcMonster); SDL_BlitSurface(text, NULL, screen, &rcText); SDL_BlitSurface(defatt, NULL, screen, &rcDefatt); SDL_UpdateRect(screen,0,0,0,0); } } TTF_CloseFont(font); TTF_Quit(); SDL_FreeSurface(sprite); SDL_FreeSurface(backbg); SDL_FreeSurface(monster); SDL_FreeSurface(wall); SDL_FreeSurface(trap); SDL_FreeSurface(life); SDL_FreeSurface(sword); SDL_FreeSurface(armor); SDL_FreeSurface(door); SDL_FreeSurface(text); SDL_FreeSurface(defatt); SDL_FreeSurface(temp); SDL_FreeSurface(screen); suppr_grille(g); suppr_joueur(j); suppr_monstre(m); SDL_Quit(); return 0; }
/* * FUNCIÓN main * Función que representa el punto de entrada del programa. Se encarga * básicamente de inicializar las librerías. */ int main(int argc, char * argv[]) { /* Datos del juego */ Uint8 Lifes = 5; /* Vidas del comecocos */ Uint32 Score = 0; /* Puntuación del comecocos */ Uint8 Option = 0; /* Opciones elejidas en el menu */ Sint32 End = 0; /* Indica si el jugador ha terminado de jugar */ Uint8 Level = 1; /* Nivel actual */ Uint32 Mode; /* Cadena temporal donde se escribe la ruta del escenario */ char LevelPath[32]; /* Nos aseguramos de que siempre se descargen las librerias */ atexit(SDL_Quit); atexit(TTF_Quit); /* Inicializamos la SDL */ if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) { fprintf(stderr, "Couldn't init SDL: %s \n", SDL_GetError()); exit(1); } /* Inicializamos la SDL_TTF */ if(TTF_Init()) { fprintf(stderr, "Couldn't init TTF: %s \n", TTF_GetError()); exit(2); } /* Activamos el modo de vídeo */ if (argc>1) Mode = SDL_SWSURFACE | SDL_FULLSCREEN; else Mode = SDL_HWSURFACE; creScreen = SDL_SetVideoMode(800, 600, 32, Mode); if(creScreen == NULL) { fprintf(stderr, "Couldn't init video mode: %s\n", SDL_GetError()); exit(3); } /* Inicialización de variables y opciones generales */ SDL_WM_SetCaption("COCONUT", "coconut"); SDL_ShowCursor(SDL_DISABLE); srandom(time(NULL)); CRE_SetFPS(42); /* Cargamos todos los ficheros gráficos y fuentes */ MGfMisc = CRE_LoadMGf(MGFMISC_PATH); MGfCoco = CRE_LoadMGf(MGFCOCO_PATH); MGfGhost = CRE_LoadMGf(MGFGHOST_PATH); MGfStar = CRE_LoadMGf(MGFSTAR_PATH); TTFCoco = TTF_OpenFont(TTFCOCO_PATH, 40); TTFCocoSmall = TTF_OpenFont(TTFCOCO_PATH, 20); /* Comprobamos que todos han sido cargados correctamente */ if(MGfMisc == NULL || MGfStar == NULL || MGfCoco == NULL || MGfGhost == NULL || TTFCoco == NULL) { fprintf(stderr, "Couldn't load some resource file."); exit(4); } /* Empezamos el juego */ while(1) { /* Mostramos el menu */ Option = COCO_MainMenu(); /* Si el usuario a elejido comenzar una nueva partida */ if(Option == OP_NEWGAME) { /* Iniciamos las variables para una partida nueva */ Lifes = 5; Score = 0; Level = 1; End = 0; /* Comenzamos el juego. Este bucle recorre todos los niveles */ while(!End) { /* Obtenemos la ruta del nivel actual */ sprintf(LevelPath, LEVELS_PATH, Level); switch(COCO_StartLevel(LevelPath, &Lifes, &Score)) { /* Indica que no quedan más niveles */ case LVL_MAPERROR: End = 1; PWinScreen.New(Score); CRE_StartLoop(); break; /* El jugador ha ganado */ case LVL_PLAYERWINS: Level++; break; /* El jugador ha abandonado */ default : End = 1; break; } } /* Sino significa que quiere salir */ } else break; } /* Descargamos todos los gráficos y funetes */ CRE_FreeMGf(MGfMisc); CRE_FreeMGf(MGfCoco); CRE_FreeMGf(MGfStar); CRE_FreeMGf(MGfGhost); TTF_CloseFont(TTFCoco); TTF_CloseFont(TTFCocoSmall); exit(0); }
void Resources::ClearFonts(){ for(std::unordered_map<string, TTF_Font*>::const_iterator index = fontTable.begin(); index != fontTable.end(); index++){ TTF_CloseFont(index->second); } fontTable.clear(); }
void CFontManager::Shutdown(void) { TTF_CloseFont(m_pTTFont); TTF_Quit(); }
void fonts_unload_custom_font(GFont font) { TTF_CloseFont((TTF_Font*)font); }
MainMenu::~MainMenu() { TTF_CloseFont(m_font); TTF_CloseFont(m_font2); }
int main(int argc, char *argv[]) { char *argv0 = argv[0]; SDL_Window *window; SDL_Renderer *renderer; TTF_Font *font; SDL_Surface *text; Scene scene; int ptsize; int i, done; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; SDL_Event event; int rendersolid; int renderstyle; int outline; int hinting; int kerning; int dump; enum { RENDER_LATIN1, RENDER_UTF8, RENDER_UNICODE } rendertype; char *message, string[128]; /* Look for special execution mode */ dump = 0; /* Look for special rendering types */ rendersolid = 0; renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; outline = 0; hinting = TTF_HINTING_NORMAL; kerning = 1; /* Default is black and white */ forecol = &black; backcol = &white; for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) { if ( strcmp(argv[i], "-solid") == 0 ) { rendersolid = 1; } else if ( strcmp(argv[i], "-utf8") == 0 ) { rendertype = RENDER_UTF8; } else if ( strcmp(argv[i], "-unicode") == 0 ) { rendertype = RENDER_UNICODE; } else if ( strcmp(argv[i], "-b") == 0 ) { renderstyle |= TTF_STYLE_BOLD; } else if ( strcmp(argv[i], "-i") == 0 ) { renderstyle |= TTF_STYLE_ITALIC; } else if ( strcmp(argv[i], "-u") == 0 ) { renderstyle |= TTF_STYLE_UNDERLINE; } else if ( strcmp(argv[i], "-s") == 0 ) { renderstyle |= TTF_STYLE_STRIKETHROUGH; } else if ( strcmp(argv[i], "-outline") == 0 ) { if ( sscanf (argv[++i], "%d", &outline) != 1 ) { fprintf(stderr, Usage, argv0); return(1); } } else if ( strcmp(argv[i], "-hintlight") == 0 ) { hinting = TTF_HINTING_LIGHT; } else if ( strcmp(argv[i], "-hintmono") == 0 ) { hinting = TTF_HINTING_MONO; } else if ( strcmp(argv[i], "-hintnone") == 0 ) { hinting = TTF_HINTING_NONE; } else if ( strcmp(argv[i], "-nokerning") == 0 ) { kerning = 0; } else if ( strcmp(argv[i], "-dump") == 0 ) { dump = 1; } else if ( strcmp(argv[i], "-fgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } forecol->r = (Uint8)r; forecol->g = (Uint8)g; forecol->b = (Uint8)b; } else if ( strcmp(argv[i], "-bgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } backcol->r = (Uint8)r; backcol->g = (Uint8)g; backcol->b = (Uint8)b; } else { fprintf(stderr, Usage, argv0); return(1); } } argv += i; argc -= i; /* Check usage */ if ( ! argv[0] ) { fprintf(stderr, Usage, argv0); return(1); } /* Initialize the TTF library */ if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); SDL_Quit(); return(2); } /* Open the font file with the requested point size */ ptsize = 0; if ( argc > 1 ) { ptsize = atoi(argv[1]); } if ( ptsize == 0 ) { i = 2; ptsize = DEFAULT_PTSIZE; } else { i = 3; } font = TTF_OpenFont(argv[0], ptsize); if ( font == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, argv[0], SDL_GetError()); cleanup(2); } TTF_SetFontStyle(font, renderstyle); TTF_SetFontOutline(font, outline); TTF_SetFontKerning(font, kerning); TTF_SetFontHinting(font, hinting); if( dump ) { for( i = 48; i < 123; i++ ) { SDL_Surface* glyph = NULL; glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol ); if( glyph ) { char outname[64]; sprintf( outname, "glyph-%d.bmp", i ); SDL_SaveBMP( glyph, outname ); } } cleanup(0); } /* Create a window */ if (SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) { fprintf(stderr, "SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError()); cleanup(2); } /* Show which font file we're looking at */ sprintf(string, "Font file: %s", argv[0]); /* possible overflow */ if ( rendersolid ) { text = TTF_RenderText_Solid(font, string, *forecol); } else { text = TTF_RenderText_Shaded(font, string, *forecol, *backcol); } if ( text != NULL ) { scene.captionRect.x = 4; scene.captionRect.y = 4; scene.captionRect.w = text->w; scene.captionRect.h = text->h; scene.caption = SDL_CreateTextureFromSurface(renderer, text); SDL_FreeSurface(text); } /* Render and center the message */ if ( argc > 2 ) { message = argv[2]; } else { message = DEFAULT_TEXT; } switch (rendertype) { case RENDER_LATIN1: if ( rendersolid ) { text = TTF_RenderText_Solid(font,message,*forecol); } else { text = TTF_RenderText_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UTF8: if ( rendersolid ) { text = TTF_RenderUTF8_Solid(font,message,*forecol); } else { text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UNICODE: { Uint16 *unicode_text = SDL_iconv_utf8_ucs2(message); if ( rendersolid ) { text = TTF_RenderUNICODE_Solid(font, unicode_text, *forecol); } else { text = TTF_RenderUNICODE_Shaded(font, unicode_text, *forecol, *backcol); } SDL_free(unicode_text); } break; default: text = NULL; /* This shouldn't happen */ break; } if ( text == NULL ) { fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError()); TTF_CloseFont(font); cleanup(2); } scene.messageRect.x = (WIDTH - text->w)/2; scene.messageRect.y = (HEIGHT - text->h)/2; scene.messageRect.w = text->w; scene.messageRect.h = text->h; scene.message = SDL_CreateTextureFromSurface(renderer, text); printf("Font is generally %d big, and string is %d big\n", TTF_FontHeight(font), text->h); draw_scene(renderer, &scene); /* Wait for a keystroke, and blit text on mouse press */ done = 0; while ( ! done ) { if ( SDL_WaitEvent(&event) < 0 ) { fprintf(stderr, "SDL_PullEvent() error: %s\n", SDL_GetError()); done = 1; continue; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: scene.messageRect.x = event.button.x - text->w/2; scene.messageRect.y = event.button.y - text->h/2; scene.messageRect.w = text->w; scene.messageRect.h = text->h; draw_scene(renderer, &scene); break; case SDL_KEYDOWN: case SDL_QUIT: done = 1; break; default: break; } } SDL_FreeSurface(text); TTF_CloseFont(font); SDL_DestroyTexture(scene.caption); SDL_DestroyTexture(scene.message); cleanup(0); /* Not reached, but fixes compiler warnings */ return 0; }