void game_menu(t_window *w, t_music *m, t_list *l, t_text *t, t_font *f, t_image *img) { int next; int height, width; SDL_Event event; SDL_Rect posBox; SDL_Surface *menu_box; SDL_Color white_color = {255,255,255,255}; SDL_Surface *texte = NULL; TTF_Font *font; next = 1; posBox.x = (atoi(w->sizeX) - atoi(w->sizeX) / 2.5) / 2; posBox.y = (atoi(w->sizeY) - (((atoi(w->sizeY) / 10) * 5) + ((atoi(w->sizeY) / 7) * 3))) / 2; if ((font = TTF_OpenFont(f->font_used, f->size_font + 10)) == NULL) show_error(4); f->posText.y = (atoi(w->sizeY) + atoi(w->sizeY) / 16 - (((atoi(w->sizeY) / 10) * 5) + ((atoi(w->sizeY) / 7) * 3))) / 2; menu_box = SDL_CreateRGBSurface(SDL_HWSURFACE, atoi(w->sizeX) / 2.5, atoi(w->sizeY) / 10, 32, 0, 0, 0, 0); SDL_FillRect(menu_box, NULL, SDL_MapRGB(w->screen->format, 0, 0, 0)); SDL_BlitSurface(w->background, NULL, w->screen, &w->posBack); f->posText.y += atoi(w->sizeY) / 7; posBox.y += atoi(w->sizeY) / 7; SDL_BlitSurface(menu_box, NULL, w->screen, &posBox); TTF_SizeText(font, "SAVE", &width, &height); f->posText.x = ((atoi(w->sizeX) + (atoi(w->sizeX) / 2.5)) - (width + (atoi(w->sizeX) / 2.5))) / 2; /* posText = ((TailleFenetre + TailleBox) - (TaillePolice + TailleBox)) / 2 */ texte = TTF_RenderText_Blended(font, "SAVE", white_color); SDL_BlitSurface(texte, NULL, w->screen, &f->posText); posBox.y += atoi(w->sizeY) / 7; SDL_BlitSurface(menu_box, NULL, w->screen, &posBox); TTF_SizeText(font, "LOAD GAME", &width, &height); f->posText.x = ((atoi(w->sizeX) + (atoi(w->sizeX) / 2.5)) - (width + (atoi(w->sizeX) / 2.5))) / 2; f->posText.y += atoi(w->sizeY) / 7; texte = TTF_RenderText_Blended(font, "LOAD GAME", white_color); SDL_BlitSurface(texte, NULL, w->screen, &f->posText); posBox.y += atoi(w->sizeY) / 7; SDL_BlitSurface(menu_box, NULL, w->screen, &posBox); TTF_SizeText(font, "SOUND", &width, &height); f->posText.x = ((atoi(w->sizeX) + (atoi(w->sizeX) / 2.5)) - (width + (atoi(w->sizeX) / 2.5))) / 2; f->posText.y += atoi(w->sizeY) / 7; texte = TTF_RenderText_Blended(font, "SOUND", white_color); SDL_BlitSurface(texte, NULL, w->screen, &f->posText); posBox.y += atoi(w->sizeY) / 7; SDL_BlitSurface(menu_box, NULL, w->screen, &posBox); TTF_SizeText(font, "GRAPHICS", &width, &height); f->posText.x = ((atoi(w->sizeX) + (atoi(w->sizeX) / 2.5)) - (width + (atoi(w->sizeX) / 2.5))) / 2; f->posText.y += atoi(w->sizeY) / 7; texte = TTF_RenderText_Blended(font, "GRAPHICS", white_color); SDL_BlitSurface(texte, NULL, w->screen, &f->posText); posBox.y += atoi(w->sizeY) / 7; SDL_BlitSurface(menu_box, NULL, w->screen, &posBox); TTF_SizeText(font, "QUIT GAME", &width, &height); f->posText.x = ((atoi(w->sizeX) + (atoi(w->sizeX) / 2.5)) - (width + (atoi(w->sizeX) / 2.5))) / 2; f->posText.y += atoi(w->sizeY) / 7; texte = TTF_RenderText_Blended(font, "QUIT GAME", white_color); SDL_BlitSurface(texte, NULL, w->screen, &f->posText); SDL_SetAlpha(f->text_support, SDL_SRCALPHA, 100); SDL_Flip(w->screen); while (next) { SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: clean_exit(w, m, l, t); break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) events2(w, m, l, t, f, img); break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_RETURN: break; case SDLK_SPACE: break; case SDLK_DOWN: break; case SDLK_UP: break; case SDLK_ESCAPE: events2(w, m, l, t, f, img); break; default: break; } break; default: break; } } }
//carrega recursos do jogo void load_files() { tileB = IMG_Load("tileB.png"); tileP = IMG_Load("tileP.png"); font = TTF_OpenFont( "arial.ttf", 28 ); }
TextPrinter &TextPrinter::font(const char* font_name,int size) { if(mFont != 0) TTF_CloseFont(mFont); mFont = TTF_OpenFont( font_name, size ); if(mFont == NULL) Logger::logError("Font is currently NULL!!!!!!!") << std::endl; return *this; }
int main(int argc, char** argv) { SDL_Event ev; int quit = 0; int sleepCycle[] = {16, 17, 17}; int sleepNth = 0; int sleepTotal = 0; int frameStart = 0; int frameEnd = 0; int frameDelta = 0; // int fps = 0, fpsreport = 0; nthlevel = 0; newlevelpause = 1; SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); TTF_Init(); sound_setup(); sound_set_song(2); sfx_player_jump = sound_synth_get(0); sfx_player_jump->waveform = SYNTH_SQUARE; sfx_player_jump->length = 100; sfx_player_jump->amp_start = 0.3; sfx_player_jump->amp_end = 0.2; sfx_player_jump->freq_start = 300; sfx_player_jump->freq_end = 500; sfx_player_scare = sound_synth_get(1); sfx_player_scare->waveform = SYNTH_NOISE; sfx_player_scare->length = 320; sfx_player_scare->amp_start = 0.1; sfx_player_scare->amp_end = 0.1; sfx_player_scare->freq_start = 3200; sfx_player_scare->freq_end = 4800; sfx_player_scare2 = sound_synth_get(2); sfx_player_scare2->waveform = SYNTH_SQUARE; sfx_player_scare2->length = 320; sfx_player_scare2->amp_start = 0.15; sfx_player_scare2->amp_end = 0.0; sfx_player_scare2->freq_start = 1200; sfx_player_scare2->freq_end = 1550; sfx_clear_goat1 = sound_synth_get(3); sfx_clear_goat1->waveform = SYNTH_SQUARE; sfx_clear_goat1->length = 50; sfx_clear_goat1->amp_start = 0.3; sfx_clear_goat1->amp_end = 0.3; sfx_clear_goat1->freq_start = 450; sfx_clear_goat1->freq_end = 450; sfx_clear_goat2 = sound_synth_get(4); sfx_clear_goat2->waveform = SYNTH_SQUARE; sfx_clear_goat2->length = 50; sfx_clear_goat2->delay = 50; sfx_clear_goat2->amp_start = 0.3; sfx_clear_goat2->amp_end = 0.3; sfx_clear_goat2->freq_start = 1250; sfx_clear_goat2->freq_end = 1250; sfx_hurting = sound_synth_get(5); sfx_hurting->waveform = SYNTH_SQUARE; sfx_hurting->length = 180; sfx_hurting->delay = 0; sfx_hurting->amp_start = 0.3; sfx_hurting->amp_end = 0; sfx_hurting->freq_start = 1000; sfx_hurting->freq_end = 2; sfx_c4 = sound_synth_get(6); sfx_c4->waveform = SYNTH_SQUARE; sfx_c4->length = 180; sfx_c4->delay = 0; sfx_c4->amp_start = 0.3; sfx_c4->amp_end = 0.1; sfx_c4->freq_start = 261.626; sfx_c4->freq_end = 261.626; sfx_f4 = sound_synth_get(7); sfx_f4->waveform = SYNTH_SQUARE; sfx_f4->length = 180; sfx_f4->delay = 0; sfx_f4->amp_start = 0.3; sfx_f4->amp_end = 0.1; sfx_f4->freq_start = 349.228; sfx_f4->freq_end = 349.228; level = 0; gravity = 0.8; framefn = &_introfn; memset(&controls, 0, sizeof(Controls)); memset(&player, 0, sizeof(Player)); player.hearts = 10; player.rect.w = 48; player.rect.h = 64; // level_place_player(); player.spriterect.x = 192; player.spriterect.y = 0; player.spriterect.w = 48; player.spriterect.h = 64; font = TTF_OpenFont("Vera.ttf", 16); screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE); load_sprites(); mygoats = (Goat**) malloc(sizeof(Goat*) * 16); memset(mygoats, 0, sizeof(Goat*) * 16); // mygoats[0] = goat_create(100, 10); // mygoats[1] = goat_create(300, 10); // mygoats[2] = goat_create(500, 10); myslimes = (Slime**) malloc(sizeof(Slime*) * 16); memset(myslimes, 0, sizeof(Slime*) * 16); // myslimes[0] = slime_create(400, 10, 1); // myslimes[0]->controls.left = 1; // fpsreport = SDL_GetTicks() + 1000; while (!quit) { frameDelta = SDL_GetTicks() - frameStart; frameStart = SDL_GetTicks(); framefn(frameDelta); while (SDL_PollEvent(&ev)) { switch (ev.type) { case SDL_KEYDOWN: switch (ev.key.keysym.sym) { case SDLK_LEFT: controls.left = 1; break; case SDLK_RIGHT: controls.right = 1; break; case SDLK_UP: // controls.up = 1; controls.button1 = 1; break; case SDLK_DOWN: controls.down = 1; break; case SDLK_z: case SDLK_SPACE: controls.button1 = 1; break; case SDLK_x: case SDLK_LCTRL: controls.button2 = 1; break; default: break; } break; case SDL_KEYUP: switch (ev.key.keysym.sym) { case SDLK_LEFT: controls.left = 0; break; case SDLK_RIGHT: controls.right = 0; break; case SDLK_UP: // controls.up = 0; controls.button1 = 0; break; case SDLK_DOWN: controls.down = 0; break; case SDLK_z: case SDLK_SPACE: controls.button1 = 0; break; case SDLK_x: case SDLK_LCTRL: controls.button2 = 0; break; default: break; } break; case SDL_QUIT: quit = 1; break; default: break; } } // ++fps; frameEnd = SDL_GetTicks(); // if (fpsreport <= frameEnd) // { // printf("%d fps\n", fps); // fps = 0; // fpsreport += 1000; // } if (sleepCycle[sleepNth] - (frameEnd - frameStart) > 0) { SDL_Delay(sleepCycle[sleepNth] - (frameEnd - frameStart)); } if (++sleepNth > 2) { sleepNth = 0; } } sound_quit(); TTF_CloseFont(font); TTF_Quit(); SDL_Quit(); return EXIT_SUCCESS; }
DungeonMasterUi* DungeonMasterUi_create(struct Player* player) { DungeonMasterUi* this = malloc(sizeof(DungeonMasterUi)); this->cards = List_create(); SDL_Renderer* renderer = player->scene->engine->renderer; TextureCache* tc = player->scene->engine->textureCache; this->player = player; this->background.x = player->scene->camera->translation.x; this->background.y = player->scene->camera->translation.y; this->background.w = player->scene->background->bounds.w; this->background.h = player->scene->background->bounds.h; this->cardFont = TTF_OpenFont("fonts/Black-Chancery.ttf", 16); SDL_Point p = {.x = player->scene->camera->translation.x, .y=250}; List_pushBack(this->cards, Card_create(p, renderer, tc, "images/uiWhiteKnight.png", CARD_SUMMON_WHITKNIGHT, 10, this->cardFont, "Summon Skeleton Knight")); p.x += ((Card*)this->cards->first->data)->background->bounds.w + 5; List_pushBack(this->cards, Card_create(p, renderer, tc, "images/blue/cursor.png", CARD_CONTROL_STRONGEST, 5, this->cardFont, "Control strongest enemy")); p.x += ((Card*)this->cards->first->data)->background->bounds.w + 5; //List_pushBack(this->cards, Card_create(renderer, tc, "images/uiWhiteKnight.png", CARD_SUMMON_WHITKNIGHT, 15, this->cardFont, "Summon Skeleton Knight")); SDL_Color white = {.r=255, .g=255, .b=255, .a=255}; p.x = player->scene->camera->translation.x; char hintActionHotkey[256]; char* hotkeyName = Input_keycodeToPrintable(Input_getHotkeyForAction(player->input, action)); sprintf(hintActionHotkey, "Use: %s", hotkeyName); free(hotkeyName); this->hintSummonHotkey = Sprite_create(SDL_CreateTextureFromSurface( renderer, TTF_RenderUTF8_Blended(this->cardFont, hintActionHotkey, white) ) ); this->hintSummonHotkey->bounds.x = p.x; this->hintSummonHotkey->bounds.y = p.y += ((Card*)this->cards->first->data)->background->bounds.h + 5; char hintNextHotkey[256]; hotkeyName = Input_keycodeToPrintable(Input_getHotkeyForAction(player->input, attackSword)); sprintf(hintNextHotkey, "N. %s", hotkeyName); free(hotkeyName); this->hintNextHotkey = Sprite_create(SDL_CreateTextureFromSurface( renderer, TTF_RenderUTF8_Blended(this->cardFont, hintNextHotkey, white) ) ); this->hintNextHotkey->bounds.x = p.x; this->hintNextHotkey->bounds.y = this->hintSummonHotkey->bounds.y + this->hintSummonHotkey->bounds.h; char hintPreviousHotkey[256]; hotkeyName = Input_keycodeToPrintable(Input_getHotkeyForAction(player->input, attackBow)); sprintf(hintPreviousHotkey, "P. %s", hotkeyName); free(hotkeyName); this->hintPreviousHotkey = Sprite_create(SDL_CreateTextureFromSurface( renderer, TTF_RenderUTF8_Blended(this->cardFont, hintPreviousHotkey, white) ) ); this->hintPreviousHotkey->bounds.x = p.x; this->hintPreviousHotkey->bounds.y = this->hintNextHotkey->bounds.y + this->hintNextHotkey->bounds.h; char indicatorpath[128]; sprintf(indicatorpath, "images/%s/indicator.png", player->scene->colorPrefix); this->indicator = Sprite_create(TextureCache_getForUnconstantPath(tc, indicatorpath)); this->indicator->bounds.y = ((Card*)this->cards->first->data)->background->bounds.y - this->indicator->bounds.h -2; this->selected = this->cards->first; return this; } void DungeonMasterUi_destroy(DungeonMasterUi* this) { FREE_LIST_WITH_ELMENTS(this->cards, Card_destroy); TTF_CloseFont(this->cardFont); } void DungeonMasterUi_summonSelectedCard(DungeonMasterUi* this, struct Scene* scene, SDL_Point tilePosition) { Card* card = this->selected->data; if (card && this->player->money >= card->cost) { Player_earnMoney(this->player, -card->cost); if (card->type == CARD_SUMMON_WHITKNIGHT) { if (Scene_getTile(scene, tilePosition) == NULL) { Enemy* enemy = Enemy_createWhiteKnight(scene, tilePosition); Scene_addEntity(scene, enemy->entity); } } else if (card->type == CARD_CONTROL_STRONGEST) { Entity* strongest = NULL; for (int i=0; i < scene->entities->usedElements; ++i) { Entity* e = scene->entities->elements[i]; if (e && (e->physics.belongsToGroups & COLLISION_GROUP_ENEMY)) { if (!strongest || e->attack1 > strongest->attack1) { strongest = e; } } } if (strongest) { ControlledEntity_set(&this->player->controlledEntity, strongest); } } } } void DungeonMasterUi_selectNext(DungeonMasterUi* this) { if (this->selected->next) { this->selected = this->selected->next; } } void DungeonMasterUi_selectPrevious(DungeonMasterUi* this) { if (this->selected->previous) { this->selected = this->selected->previous; } } void DungeonMasterUi_draw(DungeonMasterUi* this, SDL_Renderer* renderer) { SDL_SetRenderDrawColor(renderer, 100, 100, 100, 205); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_RenderFillRect(renderer, &this->background); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); ListNode* it = this->cards->first; while (it) { Card* card = it->data; if (card) { Card_draw(card, renderer); } it = it->next; } Card* selected = this->selected->data; this->indicator->bounds.x = selected->background->bounds.x + (selected->background->bounds.w/2) - (this->indicator->bounds.w/2); Sprite_draw(this->indicator, renderer); Sprite_draw(this->hintNextHotkey, renderer); Sprite_draw(this->hintPreviousHotkey, renderer); Sprite_draw(this->hintSummonHotkey, renderer); } void DungeonMasterUi_update(DungeonMasterUi* this, RawTime dt) { } Card* Card_create(SDL_Point p, SDL_Renderer* renderer, TextureCache* tc, const char* picture, int type, int cost, TTF_Font* font, const char* description) { Card* this = malloc(sizeof(Card)); this->background = Sprite_create(TextureCache_get(tc, "images/card.png")); this->coin = Sprite_create(TextureCache_get(tc, "images/uiCoin.png")); this->picture = Sprite_create(TextureCache_get(tc, picture)); this->cost = cost; this->type = type; SDL_Color white = {.r=255, .g=255, .b=255, .a=255}; this->description = Sprite_create( SDL_CreateTextureFromSurface( renderer, TTF_RenderUTF8_Blended(font, description, white) ) ); char costString[128]; sprintf(costString, "%d", cost); this->costLabel = Sprite_create( SDL_CreateTextureFromSurface( renderer, TTF_RenderUTF8_Blended(font, costString, white) ) ); this->background->bounds.x = p.x; this->background->bounds.y = p.y; this->costLabel->bounds.x = p.x + 7; this->costLabel->bounds.y = p.y + 90; this->coin->bounds.x = p.x + 7 + this->costLabel->bounds.w; this->coin->bounds.y = p.y + 90; this->picture->bounds.x = p.x + 38; this->picture->bounds.y = p.y + 45; this->description->bounds.x = p.x + 7; this->description->bounds.y = p.y + 90 + this->costLabel->bounds.h + 3; return this; } void Card_draw(Card* this, SDL_Renderer* renderer) { Sprite_draw(this->background, renderer); Sprite_draw(this->picture, renderer); Sprite_draw(this->description, renderer); Sprite_draw(this->costLabel, renderer); Sprite_draw(this->coin, renderer); } void Card_destroy(Card* this) { Sprite_destroy(this->background); Sprite_destroy(this->picture); Sprite_destroy(this->description); Sprite_destroy(this->costLabel); Sprite_destroy(this->coin); free(this); }
int FTinit(font_data *font, const char * fontname, int ptsize) { int i; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0x00 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; GLenum gl_error; texcoord_t texcoords; int minx = 0,miny = 0,maxx = 0,maxy = 0; /* We might support changing theese later */ /* Look for special rendering types */ renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; /* Default is black and white */ forecol = &white; backcol = &black; /* Initialize the TTF library */ /*if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); return(2); }*/ font->ttffont = TTF_OpenFont(fontname, ptsize); if ( font->ttffont == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, fontname, SDL_GetError()); return(2); } TTF_SetFontStyle(font->ttffont, renderstyle); font->list_base=glGenLists(next_p2(NUMCHARS)); /* Get the recommended spacing between lines of text for this font */ font->linespacing = TTF_FontLineSkip(font->ttffont); font->h = ptsize; for( i = 0; i < NUMCHARS; i++ ) { SDL_Surface *glyph = NULL; GLuint height = 0; /* kps - added default value */ forecol = &white; glyph = TTF_RenderGlyph_Blended( font->ttffont, i, *forecol ); if(glyph) { glGetError(); font->textures[i] = SDL_GL_LoadTexture(glyph, &texcoords); if ( (gl_error = glGetError()) != GL_NO_ERROR ) printf("Warning: Couldn't create texture: 0x%x\n", gl_error); font->W[i] = glyph->w; height = glyph->h; TTF_GlyphMetrics( font->ttffont, i, &minx,&maxx,&miny,&maxy,NULL); } SDL_FreeSurface(glyph); glNewList(font->list_base+i,GL_COMPILE); glBindTexture(GL_TEXTURE_2D, font->textures[i]); glTranslatef(1,0,0); glPushMatrix(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(texcoords.MinX, texcoords.MaxY); glVertex2i(0 , miny); glTexCoord2f(texcoords.MaxX, texcoords.MaxY); glVertex2i(font->W[i] , miny); glTexCoord2f(texcoords.MinX, texcoords.MinY); glVertex2i(0 ,miny+height ); glTexCoord2f(texcoords.MaxX, texcoords.MinY); glVertex2i(font->W[i] , miny+height); glEnd(); glPopMatrix(); glTranslatef((font->W[i]>3)?font->W[i]:(font->W[i] = 3) + 1,0,0); /*one would think this should be += 2... I guess they overlap or the edge * isn't painted */ font->W[i] += 1; glEndList(); } /*TTF_CloseFont(font->ttffont);*/ /*TTF_Quit();*/ return 0; }
//Main function int main(int argc, char* argv[]) { /* ----- // INITIALIZATION ----- */ //Seed RNG srand(time(NULL)); //Initialize all SDL subsystems if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { return 1; } //Initialize SDL_TTF TTF_Init(); TTF_Font * planetFont = TTF_OpenFont("corbel.ttf", 20); //Set up the screen SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE); //Make sure screen set up if (screen == NULL) { return false; } //Set the window caption SDL_WM_SetCaption("GAEM", NULL); //Create an event manager SDL_Event event; //Store keystates Uint8* keystates; //Set up camera SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT}; float camerax = 0; float cameray = 0; /* ----- GAME SETUP ----- */ //Set up ship stats std::vector<ShipStats> shipstats(10); for (int i = 0; i < 10; i++) { shipstats[i].attack = i+1; shipstats[i].defense = i+1; shipstats[i].speed = DEFAULT_FLEET_SPEED; shipstats[i].interceptRange = 200; shipstats[i].interceptDamage = 0.1; shipstats[i].interceptCD = 250; } //Set up ship type 1: Heavy ship shipstats[1].attack = 3; shipstats[1].defense = 2; shipstats[1].speed = DEFAULT_FLEET_SPEED/2; //Set up ship type 2: Fiery attack ship shipstats[2].attack = 2; shipstats[2].defense = 1; shipstats[2].speed = DEFAULT_FLEET_SPEED*1.25; //Set up buildings and building rules std::list<Building> buildings; std::vector<std::list<Building*> > buildRules; buildRules.resize(2); SDL_Surface* b01 = loadImage("b01.png"); SDL_Surface* bc01 = loadImage("bc01.png"); SDL_Surface* b02 = loadImage("b02.png"); SDL_Surface* bc02 = loadImage("bc02.png"); buildings.push_back(Building(b01, bc01, "build 0 2")); //0 buildings.push_back(Building(b02, bc02, "fire damage 2 1")); //1 buildings.push_back(Building(b01, bc01, "build 1 4")); //2 buildings.push_back(Building(b01, bc01, "build 2 2")); //3 buildings.push_back(Building(b02, bc02, "aura damage 1 total")); //4 //0 std::list<Building>::iterator bi = buildings.begin(); buildRules[0].push_back(&(*bi)); bi->setBuildTime(15000); bi++; //1 buildRules[0].push_back(&(*bi)); bi->setBuildTime(10000); bi->setRange(250); bi++; //2 buildRules[0].push_back(&(*bi)); bi->setBuildTime(15000); bi++; //3 buildRules[1].push_back(&(*bi)); bi->setBuildTime(15000); bi++; //4 buildRules[1].push_back(&(*bi)); bi->setBuildTime(10000); bi->setRange(200); bi->setCD(1000); //Building images are now in rotation caches SDL_FreeSurface(b01); SDL_FreeSurface(bc01); SDL_FreeSurface(b02); SDL_FreeSurface(bc02); //Create a list of planets std::list<Planet> planets; //The standard rate of production of basic ship 0 float ship0rate = 1.0; //The array of indicators SDL_Surface* indicator[3]; indicator[1] = loadImage("selectorb.png"); indicator[2] = loadImage("selectorr.png"); SDL_Surface* planet0img = loadImage("planet0.png"); SDL_Surface* planet1img = loadImage("planet1.png"); SDL_Surface* planet1_1img = loadImage("planet1-1.png"); //Create the planets at random //First, create two home planets std::vector<int> homestart; homestart.resize(1,3); planets.push_back(Planet(planet0img, 1.0, Vec2f(rand()%100, 100 + rand()%(LEVEL_HEIGHT-200)), 0)); planets.back().setOwner(1, indicator); planets.back().setShipRate(0, ship0rate); planets.back().setRotSpeed(M_PI/20); planets.back().addShips(3, 0); planets.push_back(Planet(planet0img, 1.0, Vec2f(LEVEL_WIDTH-(2*UNSCALED_PLANET_RADIUS)-(rand()%100), 100 + rand()%(LEVEL_HEIGHT-200)), 0)); planets.back().setOwner(2, indicator); planets.back().setShipRate(0, ship0rate); planets.back().setRotSpeed(M_PI/20); planets.back().addShips(3, 0); //Now repeatedly create planets until either a target density is reached //or we go too many tries without finding a spot for a new planet. char tries = 0; char maxTries = 10; double density = 0.13; double totalSize = LEVEL_WIDTH*LEVEL_HEIGHT; double currentSize = M_PI*UNSCALED_PLANET_RADIUS*UNSCALED_PLANET_RADIUS*2; double spacing = 23; while (currentSize/totalSize < density && tries < maxTries) { //Create a new planet at a completely random location with a random size //For now, make half normal and half volcanic float psize = (double(rand())/double(RAND_MAX))*0.7 + 0.5; Planet p(planet0img, psize, Vec2f(rand()%(LEVEL_WIDTH-int(2*UNSCALED_PLANET_RADIUS*psize)), rand()%(LEVEL_HEIGHT-int(2*UNSCALED_PLANET_RADIUS*psize))), 0);; if (rand()%2 == 0) { p.setType(0); p.setImage(planet0img); } else { p.setType(1); p.setImage(planet1img); } //Make sure it doesn't collide with any other planets bool skip = false; for (planetIter pi = planets.begin(); pi != planets.end(); pi++) { Vec2f ppos = p.pos()+Vec2f(UNSCALED_PLANET_RADIUS*p.size(),UNSCALED_PLANET_RADIUS*p.size()); Vec2f pipos = pi->pos()+Vec2f(UNSCALED_PLANET_RADIUS*pi->size(),UNSCALED_PLANET_RADIUS*pi->size()); if ((pipos-ppos).length() < p.size()*UNSCALED_PLANET_RADIUS + pi->size()*UNSCALED_PLANET_RADIUS + spacing) { //There's a collision. Increment tries and try again tries++; skip = true; break; } } if (skip) continue; //At this point, we know there's no collision. Reset tries tries = 0; //Add a few more random attributes p.setOwner(0, indicator); p.setShipRate(0, ship0rate); p.setRotSpeed((fmod(rand(),M_PI)/5) - M_PI/10); p.setDifficulty(p.size()*20 + rand()%15 - 9); //Add this planet to the current size currentSize += M_PI*(UNSCALED_PLANET_RADIUS*p.size())*(UNSCALED_PLANET_RADIUS*p.size()); //Add it to the list planets.push_back(p); } //Set up fleet list std::list<Fleet> fleets; //Set up projectile list std::list<Projectile> projectiles; //Filler to act as NULL planetIter planNull; //The currently selected planet planetIter selectPlanet = planNull; //Set up AI std::list<GalconAI> ai; //For now, AI controls player 2 GalconAISettings aiSet; aiSet.attackFraction = .8; aiSet.surplusDefecitThreshold = .25; aiSet.attackExtraNeutral = .2; aiSet.attackExtraEnemy = .7; aiSet.perPlanetAttackStrength = .5; aiSet.delay = 200; aiSet.maximumBuildingFraction = .8; aiSet.minimumDefenseForBuilding = 10; aiSet.distancePower = 1.15; ai.push_back(GalconAI(2, aiSet)); ai.begin()->init(planets, shipstats); ai.begin()->activate(); //The number of the locally playing player char localPlayer = 1; //The type of ship that will currently be sent int shipSendType = 0; //A line drawer for the main surface LineDrawer linedraw(screen); /* ----- MAIN LOOP ----- */ int time = SDL_GetTicks(); uint8_t quit = 0; while (quit == 0) { //Update time and dt //Cap FPS int dt = SDL_GetTicks() - time; float minms = 1000.0/float(FPS_CAP); if (dt < minms) SDL_Delay(minms-dt); time = SDL_GetTicks(); //Update keystates keystates = SDL_GetKeyState(NULL); //Check for arrow keys/wasd if (keystates[SDLK_UP] || keystates[SDLK_w]) { cameray -= CAMERA_SPEED * (dt/1000.0); if (cameray < 0) cameray = 0; } if (keystates[SDLK_RIGHT] || keystates[SDLK_d]) { camerax += CAMERA_SPEED * (dt/1000.0); if (camerax > LEVEL_WIDTH - SCREEN_WIDTH) camerax = LEVEL_WIDTH - SCREEN_WIDTH; } if (keystates[SDLK_DOWN] || keystates[SDLK_s]) { cameray += CAMERA_SPEED * (dt/1000.0); if (cameray > LEVEL_HEIGHT - SCREEN_HEIGHT) cameray = LEVEL_HEIGHT - SCREEN_HEIGHT; } if (keystates[SDLK_LEFT] || keystates[SDLK_a]) { camerax -= CAMERA_SPEED * (dt/1000.0); if (camerax < 0) camerax = 0; } //Update camera from camerax and cameray to struct camera.x = camerax; camera.y = cameray; //Handle events while (SDL_PollEvent(&event)) { //Quit if requested if (event.type == SDL_QUIT) { quit = 1; } //Check for escape key, QWERTY to construct buildings, or numbers to select //ship type. //BUILDING CONSTRUCTION AND TYPE SELECTION THIS WAY IS TEMPORARY if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: quit = 1; break; case SDLK_q: if (selectPlanet != planNull) { if (selectPlanet->owner() != localPlayer || buildRules[selectPlanet->type()].size() < 1) break; selectPlanet->build(*(buildRules[selectPlanet->type()].begin()), buildRules); } break; case SDLK_w: if (selectPlanet != planNull) { if (selectPlanet->owner() != localPlayer || buildRules[selectPlanet->type()].size() < 2) break; selectPlanet->build(*(++buildRules[selectPlanet->type()].begin()), buildRules); } break; case SDLK_e: if (selectPlanet != planNull) { if (selectPlanet->owner() != localPlayer || buildRules[selectPlanet->type()].size() < 3) break; std::list<Building*>::iterator i; i = buildRules[selectPlanet->type()].begin(); i++; i++; selectPlanet->build(*i, buildRules); } break; case SDLK_1: shipSendType = 0; break; case SDLK_2: shipSendType = 1; break; case SDLK_3: shipSendType = 2; break; case SDLK_4: shipSendType = 3; break; case SDLK_5: shipSendType = 4; break; default: break; } } //Check for mouse clicks if (event.type == SDL_MOUSEBUTTONDOWN) { //Left click if (event.button.button == SDL_BUTTON_LEFT) { //Used to select a planet //Check if any are being clicked on selectPlanet = planNull; //Adjust mouse coordinates based on camera Vec2f click(event.button.x + camera.x, event.button.y + camera.y); for (planetIter i = planets.begin(); i != planets.end(); i++) { //See if distance from center is less than planet radius Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()), i->y() + (UNSCALED_PLANET_RADIUS * i->size())); if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size()) { //Ensure the planet belongs to this person if ((*i).owner() == localPlayer) { selectPlanet = i; break; } } } } //Right click if (event.button.button == SDL_BUTTON_RIGHT) { //Used to choose the destination for a fleet //See if we have a selected planet if (selectPlanet != planNull) { //Adjust mouse coordinates based on camera Vec2f click(event.button.x + camera.x, event.button.y + camera.y); //Check to see if any are being clicked on for (planetIter i = planets.begin(); i != planets.end(); i++) { Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()), i->y() + (UNSCALED_PLANET_RADIUS * i->size())); //See if distance from center is less than planet radius if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size()) { //Split ships from the source planet int transfer = (*selectPlanet).splitShips(0.5, shipSendType); //Make sure we actually have a ship in the fleet if (transfer > 0) { //Add the new fleet fleets.push_back(Fleet(transfer, shipSendType, shipstats[shipSendType], &(*selectPlanet), &(*i))); break; } } } } } } } //Draw a white background SDL_Rect back = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT}; SDL_FillRect(screen, &back, 0xFFFFFF); //Update and display fleets for (fleetIter i = fleets.begin(); i != fleets.end(); i++) { (*i).update(); //Check for arrival at destination //See if distance from center is less than planet radius Vec2f tar((*i).dest()->x() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()), (*i).dest()->y() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size())); if ((tar-i->pos()).length() < UNSCALED_PLANET_RADIUS * (i->dest())->size()) { //Check if friendly or hostile if ((*i).dest()->owner() == (*i).owner()) { //Add the fleet to the new planet (*((*i).dest())).addShips(i->ships(), i->type()); } else //Hostile { //Attack! //Get ship counts before the attack std::vector<int> ships1 = i->dest()->shipcount(); int oldowner = i->dest()->owner(); //Actually do the attack (*((*i).dest())).takeAttack(i->ships(), i->type(), i->owner(), shipstats, indicator); //If the attack changed ownership of the selected planet, //deselect it if (oldowner != i->dest()->owner() && i->dest() == &(*selectPlanet)) selectPlanet = planNull; //Get ship counts after the attack std::vector<int> ships2 = i->dest()->shipcount(); //Notify the defending AI about the losses for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++) { if (oldowner != j->player()) continue; float newdefense = 0; for (unsigned int k = 0; k < ships1.size(); k++) { int diff; //If ownership has changed if (oldowner != i->dest()->owner()) { diff = ships1[k]; j->notifyPlanetLoss(i->dest()); } else { diff = ships1[k] - ships2[k]; } newdefense += diff * shipstats[k].defense; } j->notifyDefendLoss(newdefense); } //Notify the attacking AI about the losses for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++) { if (i->owner() != j->player()) continue; float lost; //If the attack failed if (i->dest()->owner() != i->owner()) { //Lost everything lost = i->ships(); } else //Successful attack { //Lose the difference lost = i->ships() - i->dest()->totalDefense(shipstats); j->notifyPlanetGain(i->dest()); } j->notifyAttackLoss(lost); } } //Delete all projectiles with this fleet as its target for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++) { if (pi->target() == &(*(i))) { pi = projectiles.erase(pi); pi--; } } //Delete the fleet i = fleets.erase(i); i--; continue; } //Check for interception //Compare against every other fleet for (fleetIter j = fleets.begin(); j != fleets.end(); j++) { //Atempt interception char status = i->intercept(&(*j), shipstats); //Greater than 0: Draw line if (status <= 0) continue; SDL_Color red = {255, 0, 0}; SDL_Color orange = {255, 255, 0}; linedraw.line(i->pos(), j->pos(), orange, red); //Equal to 2: Dealt damage, but didn't notify if (status == 2) { //Notify the AI before we go around deleting things for (std::list<GalconAI>::iterator k = ai.begin(); k != ai.end(); k++) { if (k->player() == j->owner()) { k->notifyFleetDamage(std::min(double(shipstats[i->type()].interceptDamage), double(j->totalDefense(shipstats)))); } } } //Equal to 3: Destroy target if (status != 3) break; //We can have the projectile code handle the cleanup later //Create a fake projectile right on top of it to deal the final blow std::stringstream convertnum; convertnum << "damage "; convertnum << shipstats[i->type()].interceptDamage*i->ships()*2; projectiles.push_back(Projectile(j->pos(), &(*j), convertnum.str(), shipstats[j->type()].speed*2)); //Don't attack more than one ship break; } (*i).display(screen, camera); } //Update and display planets for (planetIter i = planets.begin(); i != planets.end(); i++) { //Get ship counts before the update std::vector<int> ships1 = i->shipcount(); //Update the planet (*i).update(); //Get ship counts after the update std::vector<int> ships2 = i->shipcount(); //Notify a controlling AI about the construction for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++) { if (i->owner() != j->player()) continue; float newattack = 0; float newdefense = 0; for (unsigned int k = 0; k < ships1.size(); k++) { int diff = ships2[k] - ships1[k]; newattack += diff * shipstats[k].attack; newdefense += diff * shipstats[k].defense; } j->notifyConstruction(newattack, newdefense); } //If this planet is selected, add an indicator if (i == selectPlanet) { SDL_Rect temprect = {Sint16((*i).x()-10 - camera.x), Sint16((*i).y()-10 - camera.y), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20)}; SDL_FillRect(screen, &temprect, SDL_MapRGB(screen->format, 100, 100, 100)); } //If this is a lava planet and it is depleted, replace the image if (i->typeInfo() < 0 && i->type() == 1) { i->setImage(planet1_1img); i->setTypeInfo(0); i->setRotSpeed(0); i->setShipRate(0, ship0rate * PLANET1_DEPLETION_PENALTY); } //Iterate over all buildings to handle effects from buildings to other objects for (unsigned int j = 0; j < i->buildcount(); j++) { //Get the building BuildingInstance* b = i->building(j); //Skip over nonexistant and incomplete buildings if (!(b->exists()) || j == Uint32(i->buildIndex())) continue; //Try to make it fire, remember result bool fire = b->fire(); //Create a string stream and vector for tokens std::stringstream ss(b->effect()); std::string item; std::vector<std::string> tokens; while (std::getline(ss, item, ' ')) { tokens.push_back(item); } //Ensure the size is at least two if (tokens.size() < 3) continue; //Parse it and apply effects that involve multiple objects //Fire projectile: fire <effect> <effectvars> <speed as multiplier> if (tokens[0] == "fire") { //Ensure size of four if (tokens.size() != 4) continue; //Loop over all potential target fleets, find closest Fleet* closest = NULL; float closestDist = -1; Vec2f coords = i->buildcoords(j); for (fleetIter k = fleets.begin(); k != fleets.end(); k++) { //Only check further if it's an enemy fleet if (k->owner() == i->owner()) continue; //Compute the distance between them double dist = (coords-k->pos()).length(); //Continue if the fleet is out of range if (dist > b->range()) continue; //Compare with previous best if (dist < closestDist || closestDist < -0.5) { closestDist = dist; closest = &(*k); } } //Fire a projectile from the building to the fleet if (closest != NULL) { if (fire) { //Create a proper string for the projectile std::string projstr; for (unsigned int word = 1; word < tokens.size()-1; word++) { projstr += tokens[word] + " "; } projectiles.push_back(Projectile(coords, closest, projstr, std::atof(tokens[tokens.size()-1].c_str()))); } } } //Aura: aura <effect> <effectvars> if (tokens[0] == "aura") { //Find number of ships in range int shipcount = 0; for (fleetIter k = fleets.begin(); k != fleets.end(); k++) { //Only check further if it's an enemy fleet if (k->owner() == i->owner()) continue; //Compute the distance between them double dist = (i->buildcoords(j)-k->pos()).length(); if (dist <= b->range()) shipcount += k->ships(); } //Deal damage with a fake projectile if (fire) { bool hit = false; for (fleetIter k = fleets.begin(); k != fleets.end(); k++) { //Only check further if it's an enemy fleet if (k->owner() == i->owner()) continue; //Compute the distance between them double dist = (i->buildcoords(j)-k->pos()).length(); if (dist > b->range()) continue; hit = true; std::string projstr; //Divide appropriately if needed if (tokens[tokens.size()-1] == "total") { std::stringstream toa; toa << atof(tokens[tokens.size()-2].c_str())*float(k->ships())/float(shipcount); tokens[tokens.size()-1] = toa.str(); } //Depleted volcanic planets don't do as much if (i->type() == 1 && i->typeInfo() <= 0) { std::stringstream toa; toa << atof(tokens[tokens.size()-2].c_str())*PLANET1_DEPLETION_PENALTY; tokens[tokens.size()-1] = toa.str(); } //Create the projectile for (unsigned int word = 1; word < tokens.size()-1; word++) { projstr += tokens[word] + " "; } projectiles.push_back(Projectile(k->pos(), &(*k), projstr, 1)); } //Volcanic planets will lost some fuel if (i->type() == 1 && hit && i->typeInfo() != 0) { i->setTypeInfo(i->typeInfo()-PLANET1_DEPLETION_RATE); if (i->typeInfo() == 0) i->setTypeInfo(-1); } } } } //for each building (*i).display(screen, planetFont, camera); } //Update and display projectiles for (projectileIter i = projectiles.begin(); i != projectiles.end(); i++) { (*i).update(); //Check if the projectile has hit its target fleet if ((i->pos() - i->target()->pos()).length() < 12.345) //MAGIC NUMBER >:( { //Tokenize string to determine effect std::stringstream ss(i->effect()); std::string item; std::vector<std::string> tokens; while (std::getline(ss, item, ' ')) { tokens.push_back(item); } //Damage: damage <amount> if (tokens[0] == "damage") { //Ensure size of two if (tokens.size() != 2) continue; //Deliver the damage //Notify the AI before we go around deleting things for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++) { if (j->player() == i->target()->owner()) { j->notifyFleetDamage(std::min(std::atof(tokens[1].c_str()), double(i->target()->totalDefense(shipstats)))); } } //Check to see if the fleet is destroyed by this if (!(i->target()->takeHit(std::atof(tokens[1].c_str()), shipstats))) { //Delete the fleet for (fleetIter fi = fleets.begin(); fi != fleets.end(); fi++) { if (&(*fi) == &(*(i->target()))) { fleets.erase(fi); break; } } //Delete all projectiles with this fleet as the target for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++) { if (pi->target() == i->target()) { if (pi == i) continue; pi = projectiles.erase(pi); pi--; } } } //Either way, destroy this projectile i = projectiles.erase(i); i--; continue; } } (*i).display(screen, camera); } //Perform AI calculations for (std::list<GalconAI>::iterator i = ai.begin(); i != ai.end(); i++) { //Get the command list commandList com = i->update(planets, fleets, shipstats, buildRules); //Execute each command for (commandList::iterator j = com.begin(); j != com.end(); j++) { //Extract the info from the command Planet* source = j->first; int amount = j->second.first; Planet* dest = j->second.second; //Handle building construction if (source == dest) { std::list<Building*>::iterator build = buildRules[source->type()].begin(); while (amount > 0) { amount--; build++; } //Build it! source->build((*build), buildRules); continue; } //Get the number of ships from the source std::vector<int> ships = source->shipcount(); //Send out a fleet for each ship type used std::vector<int> newfleet; newfleet.resize(ships.size()); int total = 0; for (unsigned int k = 0; k < ships.size(); k++) { //Handle it differently for attack or defense float typeTotal; if (dest->owner() == source->owner()) { //Check the total defense of this ship type typeTotal = ships[k] * shipstats[k].defense; } else { //Check the total attack of this ship type typeTotal = ships[k] * shipstats[k].attack; } //If there's more ships requested than there are of this type if (total + typeTotal <= amount) { //Add them all newfleet[k] += ships[k]; total += typeTotal; } else //More ships than space in the requested fleet { //Find the proper amount //# of ships to send = defense requested / def per ship float properAmount = (amount - total) / (typeTotal / ships[k]); newfleet[k] += properAmount; break; } } //Fleet is built, send each type that has some ships for (unsigned int k = 0; k < newfleet.size(); k++) { if (newfleet[k] == 0) continue; fleets.push_back(Fleet(newfleet[k], k, shipstats[k], source, dest)); //Also subtract the fleet from the original planet newfleet[k] *= -1; source->addShips(newfleet[k], k); } } } //Flipoo if (SDL_Flip(screen) == -1) { return 1; } } //Free surfaces SDL_FreeSurface(indicator[1]); SDL_FreeSurface(indicator[2]); SDL_FreeSurface(planet0img); SDL_FreeSurface(planet1img); SDL_FreeSurface(planet1_1img); //Clean up TTF TTF_CloseFont(planetFont); TTF_Quit(); SDL_Quit(); }
char ModeloFactory::nuevoElegirMisiones(std::list<ParserYaml::stEscenario>& listaEscenarios){ bool quit = false; bool clicBotonMouseIzquierdo = false; int posicionMouseX, posicionMouseY; char misionElegida; SDL_Event event; TTF_Font *fuente = NULL; SDL_Color textColor = { 255, 255, 255 }; //color blanco SDL_Surface* pantalla = NULL; SDL_Init( SDL_INIT_EVERYTHING ); pantalla = SDL_SetVideoMode( PANTALLA_ANCHO, PANTALLA_ALTO, SCREEN_BPP, SDL_SWSURFACE ); TTF_Init(); SDL_WM_SetCaption( "Misiones", NULL ); SDL_Surface *imagenDeFondo = NULL; imagenDeFondo = ImageLoader::getInstance().load_image( "./img/background4.png" ); fuente = TTF_OpenFont( "./fonts/Verdana.ttf", 28 ); SDL_Surface* textoMisionCarnicero = TTF_RenderText_Solid( fuente, "Mision Carnicero", textColor ); SDL_Surface* textoMisionBanderas = TTF_RenderText_Solid( fuente, "Mision Banderas", textColor ); SDL_BlitSurface( imagenDeFondo, NULL, pantalla, NULL ); SDL_Rect offset; offset.x = 50; offset.y = 190; SDL_BlitSurface( textoMisionCarnicero, NULL, pantalla, &offset ); rectangleRGBA( pantalla, 48, 190, 295, 225, 0, 255, 0, 255); offset.x = 350; offset.y = 190; SDL_BlitSurface( textoMisionBanderas, NULL, pantalla, &offset ); rectangleRGBA( pantalla, 348, 190, 595, 225, 0, 255, 0, 255); SDL_Flip( pantalla ); while( quit == false ) { while( SDL_PollEvent( &event ) ) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_MOUSEMOTION: posicionMouseX = event.motion.x; posicionMouseY = event.motion.y; break; case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: clicBotonMouseIzquierdo = true; break; } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: clicBotonMouseIzquierdo = false; break; } break; } } if (clicBotonMouseIzquierdo && posicionMouseX >48 && posicionMouseX <295 && posicionMouseY >190 && posicionMouseY <225){ misionElegida = 1; std::cout << "Mision Elegida Carnicero" << std::endl; Log::getInstance().log(1,__FILE__,__LINE__,"Mision Elegida Carnicero"); std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin(); advance(it, 0); std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl; this->juegoElegido.nombreEscenario = (*it).nombre; this->juegoElegido.escenario = (*it); SDL_FreeSurface( imagenDeFondo ); SDL_FreeSurface( textoMisionCarnicero ); SDL_FreeSurface( textoMisionBanderas ); SDL_FreeSurface( pantalla ); TTF_CloseFont( fuente ); TTF_Quit(); SDL_Quit(); return misionElegida; } else if (clicBotonMouseIzquierdo && posicionMouseX >348 && posicionMouseX <595 && posicionMouseY >190 && posicionMouseY <225){ misionElegida = 2; std::cout << "Mision Elegida Banderas" << std::endl; Log::getInstance().log(1,__FILE__,__LINE__,"Mision Elegida Banderas"); std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin(); advance(it, 1); std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl; this->juegoElegido.nombreEscenario = (*it).nombre; this->juegoElegido.escenario = (*it); SDL_FreeSurface( imagenDeFondo ); SDL_FreeSurface( textoMisionCarnicero ); SDL_FreeSurface( textoMisionBanderas ); SDL_FreeSurface( pantalla ); TTF_CloseFont( fuente ); TTF_Quit(); SDL_Quit(); return misionElegida; } } SDL_FreeSurface( imagenDeFondo ); SDL_FreeSurface( textoMisionCarnicero ); SDL_FreeSurface( textoMisionBanderas ); SDL_FreeSurface( pantalla ); TTF_CloseFont( fuente ); TTF_Quit(); SDL_Quit(); return 3; }
/* Setup SDL */ void InitGFX(){ static int flags=0; /* Define the program icon */ #ifdef _WIN32 program_icon = SDL_LoadBMP("irixbasic-icon-32px.bmp"); #else program_icon = SDL_LoadBMP("irixbasic-icon-128px.bmp"); #endif char *msg; /* Initialize SDL */ if (SDL_Init (SDL_INIT_VIDEO) < 0) { sprintf (msg, "Couldn't initialize SDL: %s\n", SDL_GetError ()); /*MessageBox (0, msg, "Error", program_icon);*/ free (msg); exit (1); } atexit (SDL_Quit); /* Set video mode */ screen = SDL_SetVideoMode (screen_width, screen_height, 16, SDL_HWSURFACE | SDL_DOUBLEBUF); if (screen == NULL) { sprintf (msg, "Couldn't set %dx%dx16 video mode: %s\n", screen_width, screen_height, SDL_GetError ()); printf("%s",msg); free (msg); exit (2); } flags = screen->flags; /* Check if the enable fullscreen argument is turned on */ if(enable_fullscreen){ screen = SDL_SetVideoMode(0, 0, 0, screen->flags ^ SDL_FULLSCREEN); screen_width = screen->w; screen_height = screen->h; if(screen == NULL) { screen = SDL_SetVideoMode(0, 0, 0, flags); /* If toggle FullScreen failed, then switch back */ } if(screen == NULL) { exit(1); /* If you can't switch back for some reason, then fail */ } } SDL_WM_SetIcon(program_icon, NULL); SDL_WM_SetCaption ("IRIXBASIC", "IRIXBASIC"); /* Create background screen colors*/ screen_color = SDL_MapRGB(screen->format, 66, 66, 231); frame_color = SDL_MapRGB(screen->format, 165, 165, 255); debug_color = SDL_MapRGB(screen->format, 126, 126, 126); /* light blue */ foreground_color.r = 165; foreground_color.g = 165; foreground_color.b = 255; /* dark blue */ background_color.r = 66; background_color.g = 66; background_color.b = 231; /* Setup a rect for the full screen */ screen_rect.h = screen->h; screen_rect.w = screen->w; /* frame border width 36px / height 45px */ display_area_rect.x = 36; display_area_rect.y = 45; display_area_rect.w = screen->w-(36*2); display_area_rect.h = screen->h-(45*2); /* Set up the SDL_TTF */ TTF_Init(); atexit(TTF_Quit); /* TTF_Init() is like SDL_Init(), but with no parameters. Basically, it initializes SDL_TTF. There's really not much to it. Remember, when the program ends, we have to call TTF_Quit(). atexit(TTF_Quit) ensures that when we call exit(), the program calls TTF_Quit() for us. */ fntc64 = TTF_OpenFont( "./C64_User_Mono_v1.0-STYLE.ttf", fontsize ); /* Get the size of a character in pixels */ if(TTF_SizeText(fntc64,"B",&character_with,&character_height)) { printf("SDL_TTF error: %s", TTF_GetError()); } else { total_text_rows = (display_area_rect.h/character_height)-1; total_text_cols = (display_area_rect.w/character_with)-1; printf("Current Screen Size: width=%d height=%d\n", screen_width, screen_height); printf("Text Settings: %d=points rows=%d columns=%d \n", fontsize, total_text_rows, total_text_cols); printf("\n"); } /*Wait a moment for the screen to switch*/ if(enable_fullscreen) { SDL_Flip(screen); SDL_Delay(1500); } /*------------------------------- * Fill the screen * ------------------------------- */ /* Fill the screen with the light blue frame */ SDL_FillRect(screen, NULL, frame_color); /*Fill the center of the screen with dark blue */ SDL_FillRect(screen, &display_area_rect, screen_color); /* Make sure everything is displayed on screen */ SDL_Flip(screen); isbutton_down = 0; }
int main(int argc, char* argv[]) { AVFormatContext *pFormatCtx; AVFormatContext *pFormatCtx_o; //_o表示和输出有关联 AVFormatContext *pFormatCtx_test; //_test表示读取外置文件,推流时需要读取其头信息 unsigned int videoindex_test; unsigned int i, videoindex; unsigned int videoindex_o; AVCodecContext *pCodecCtx; AVCodecContext *pCodecCtx_o; AVCodec *pCodec; AVCodec *pCodec_o; AVPacket pkt_o; AVStream *video_st_o; unsigned int frame_cnt; AVOutputFormat *fmt_o; AVFrame *pFrame_o; unsigned int picture_size; uint8_t *picture_buf; ofstream error_log("error_log.log"); unsigned int start=0; unsigned int start1=0; unsigned int j=1; //j记录的是pkt的pts信息 HANDLE Handle_encode=NULL; //编码h.264线程 HANDLE Handle_flushing=NULL; //清空内存视频缓存数据线程 HANDLE Handle_dis=NULL; //刷新显示线程 av_register_all(); avformat_network_init(); pFormatCtx = avformat_alloc_context(); //Open File //char filepath[]="src01_480x272_22.h265"; //avformat_open_input(&pFormatCtx,filepath,NULL,NULL) //Register Device avdevice_register_all(); //注册libavdevice //Windows #ifdef _WIN32 //Show Dshow Device show_dshow_device(); //Show Device Options show_dshow_device_option(); //Show VFW Options show_vfw_device(); #if USE_DSHOW AVInputFormat *ifmt=av_find_input_format("dshow"); AVDictionary* options = NULL; av_dict_set(&options,"video_size","320x240",0); //设置更改分辨率 //av_set_options_string(); //Set own video device's name if(avformat_open_input(&pFormatCtx,"video=QuickCam Orbit/Sphere AF",ifmt,&options)!=0){ printf("Couldn't open input stream.(无法打开输入流)\n"); return -1; } #else AVInputFormat *ifmt=av_find_input_format("vfwcap"); if(avformat_open_input(&pFormatCtx,"0",ifmt,NULL)!=0){ printf("Couldn't open input stream.(无法打开输入流)\n"); return -1; } #endif #endif //Linux #ifdef linux AVInputFormat *ifmt=av_find_input_format("video4linux2"); if(avformat_open_input(&pFormatCtx,"/dev/video0",ifmt,NULL)!=0){ printf("Couldn't open input stream.(无法打开输入流)\n"); return -1; } #endif 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("Couldn'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; } AVFrame *pFrame,*pFrameYUV; pFrame=avcodec_alloc_frame(); pFrameYUV=avcodec_alloc_frame(); uint8_t *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); //SDL---------------------------- if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { printf( "Could not initialize SDL - %s\n", SDL_GetError()); return -1; } int screen_w=0; int screen_h=0; SDL_Surface *screen; ////////////////////////////////////////////////////////////////////////// //王全洲 2015年5月29日19:46:56 增加在YUV上显示时间的功能 SDL_Surface *pText; TTF_Font *font; char szTime[32]={"hello world"}; //初始化字体库 if (TTF_Init()==-1) { cout<<"初始化字库失败!"<<endl; return 0; } /* 打开simfang.ttf 字库,设字体为20号 */ font=TTF_OpenFont("C:\\Windows\\Fonts\\Arial.ttf",20); if (font==NULL) { cout<<"error load C:\\Windows\Fonts\\Arial.ttf,please make sure it is existed"<<endl; return 0; }
//No es usado por hilos bool ModeloFactory::nuevoElegirEscenario(std::list<ParserYaml::stEscenario>& listaEscenarios){ bool quit = false; bool clicBotonMouseIzquierdo = false; int posicionMouseX, posicionMouseY; SDL_Event event; TTF_Font *fuente = NULL; SDL_Color textColor = { 255, 255, 255 }; //color blanco SDL_Surface* pantalla = NULL; SDL_Init( SDL_INIT_EVERYTHING ); pantalla = SDL_SetVideoMode( PANTALLA_ANCHO, PANTALLA_ALTO, SCREEN_BPP, SDL_SWSURFACE ); TTF_Init(); SDL_WM_SetCaption( "Menu", NULL ); SDL_Surface *imagenDeFondo3 = NULL; imagenDeFondo3 = ImageLoader::getInstance().load_image( IMG_CARNICERO ); fuente = TTF_OpenFont( FUENTE_USADA, 28 ); SDL_Rect offsetDelFondo; offsetDelFondo.x = 0; offsetDelFondo.y = 0; SDL_BlitSurface( imagenDeFondo3, NULL, pantalla, &offsetDelFondo ); vector <SDL_Surface*> vectorDeNombresDeEscenarios; for (std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin() ; it != listaEscenarios.end(); it++ ){ const char* nombreDeEscenario = it->nombre.c_str(); vectorDeNombresDeEscenarios.push_back( TTF_RenderText_Solid( fuente, nombreDeEscenario, textColor ) ); } int x = 100; int y = 65; for (std::vector<SDL_Surface*>::iterator it=vectorDeNombresDeEscenarios.begin() ; it != vectorDeNombresDeEscenarios.end(); it++ ){ SDL_Rect offsetDelTextoNombreDelEscenario; offsetDelTextoNombreDelEscenario.x = x; offsetDelTextoNombreDelEscenario.y = y; SDL_BlitSurface( *it, NULL, pantalla, &offsetDelTextoNombreDelEscenario ); rectangleRGBA( pantalla, x-5, y-5, x+400, y+35, 0, 255, 0, 255); y += 100; } SDL_Flip( pantalla ); while( quit == false ) { while( SDL_PollEvent( &event ) ) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_MOUSEMOTION: posicionMouseX = event.motion.x; posicionMouseY = event.motion.y; break; case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: clicBotonMouseIzquierdo = true; break; } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: clicBotonMouseIzquierdo = false; break; } break; } } x = 100; y = 65; int k = 1; while (k <= vectorDeNombresDeEscenarios.size() ) { if (clicBotonMouseIzquierdo && posicionMouseX > x-5 && posicionMouseX < x+400 && posicionMouseY > y-5 && posicionMouseY < y+35){ std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin(); for ( int a = 1; a <= k-1; a++ ){ it++; } std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl; this->juegoElegido.nombreEscenario = (*it).nombre; this->juegoElegido.escenario = (*it); while (vectorDeNombresDeEscenarios.size() != 0) { SDL_Surface * nombreDeEscenario = NULL; nombreDeEscenario = vectorDeNombresDeEscenarios.back(); SDL_FreeSurface ( nombreDeEscenario ); vectorDeNombresDeEscenarios.pop_back(); } SDL_FreeSurface( pantalla ); SDL_FreeSurface( imagenDeFondo3 ); TTF_CloseFont( fuente ); TTF_Quit(); SDL_Quit(); return true; } y+=100; k++; } } while (vectorDeNombresDeEscenarios.size() != 0) { SDL_Surface * nombreDeEscenario = NULL; nombreDeEscenario = vectorDeNombresDeEscenarios.back(); SDL_FreeSurface ( nombreDeEscenario ); vectorDeNombresDeEscenarios.pop_back(); } SDL_FreeSurface( pantalla ); SDL_FreeSurface( imagenDeFondo3 ); TTF_CloseFont( fuente ); TTF_Quit(); SDL_Quit(); return false; }
int main(int argc, char* argv[]) { SDL_Window *window; // Declare a pointer if(init_SDL_all() != 0) { return 1; } // Create an application window with the following settings: window = SDL_CreateWindow( WINDOW_NAME, // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position SCREEN_WIDTH, // width, in pixels SCREEN_HEIGHT, // height, in pixels SDL_WINDOW_OPENGL // flags - see below ); if (window == NULL) { return logSDLError("Could not create window"); } SDL_Renderer* ren; ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { return logSDLError("Could not create renderer"); } dropData = getDrops(); srand(time(NULL)); //Open the font font = TTF_OpenFont(fontFile, fontSize); if (font == NULL){ return logSDLError("TTF_OpenFont"); } background = loadTexture("images/bkg.png", ren); SDL_Texture *image = loadTexture("images/image.bmp", ren); if (background == NULL || image == NULL) { return 4; } SDL_Texture *sheet = loadTexture("images/sheet.png", ren); blocks = loadTexture("images/blocks.png", ren); //iW and iH are the clip width and height //We'll be drawing only clips so get a center position for the w/h of a clip int iW = 100, iH = 100; int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; //Setup the clips for our image SDL_Rect clips[4]; int i; for (i = 0; i < 4; ++i){ clips[i].x = i / 2 * iW; clips[i].y = i % 2 * iH; clips[i].w = iW; clips[i].h = iH; } //Specify a default clip to start with for(i=0; i < NUMBER_OF_BLOCKS; i++) { blockClips[i].x = i * BLOCK_SIZE; blockClips[i].y = 0; blockClips[i].w = BLOCK_SIZE; blockClips[i].h = BLOCK_SIZE; } nextPiece = pickNewPiece(); useClip = pickNewPiece(); //SDL_Delay(3000); // Pause execution for 3000 milliseconds, for example //Our event structure SDL_Event e; bool quit = false; while (!quit){ SDL_Delay(FRAME_TIME_DELAY); // Event loop for each possible game mode if(mode == MODE_GAMEOVER) { printf("\nGAME OVER\nScore: %lu\n\n", score); quit = true; break; } else if(mode == MODE_PAUSE) { while (SDL_PollEvent(&e)) { if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym){ case SDLK_p: mode = MODE_RUNNING; break; case SDLK_q: case SDLK_ESCAPE: quit = true; break; default: break; } } } } else if(mode == MODE_RUNNING) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) quit = true; if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_UP: rotation += 1; if(!checkIfValidPosition()) { rotation -= 1; } draw_required = true; break; case SDLK_ESCAPE: case SDLK_q: quit = true; break; case SDLK_DOWN: drop_y += 1; draw_required = true; if(!checkIfValidPosition()) { drop_y -= 1; dropPiece(); } break; case SDLK_LEFT: drop_x -= 1; draw_required = true; if(!checkIfValidPosition()) drop_x += 1; break; case SDLK_RIGHT: drop_x += 1; draw_required = true; if(!checkIfValidPosition()) drop_x -= 1; break; case SDLK_SPACE: draw_required = true; dropPiece(); break; case SDLK_p: if(mode == MODE_PAUSE) mode = MODE_RUNNING; else mode = MODE_PAUSE; break; default: break; } } } } if(mode == MODE_RUNNING) { fallTimer++; if(fallTimer >= fallTimerLimit) { fallTimer = 0; drop_y += 1; draw_required = true; if(!checkIfValidPosition()) { drop_y -= 1; dropPiece(); } } } if(draw_required) { SDL_RenderClear(ren); //Render the scene switch(mode) { case MODE_RUNNING: draw_game_running(ren); break; case MODE_PAUSE: draw_game_paused(ren); break; default: break; } draw_score(ren); SDL_RenderPresent(ren); } } // Close and destroy the window SDL_DestroyTexture(background); SDL_DestroyTexture(image); SDL_DestroyTexture(sheet); SDL_DestroyTexture(blocks); TTF_CloseFont(font); SDL_DestroyRenderer(ren); SDL_DestroyWindow(window); // Clean up SDL_Quit(); return 0; }
int main(int argc , char ** argv) { char a; struct key key; int loop; int menu; int selectedMenu; /* Initialisation simple */ if (argc == 1) a = argv[0][0]; if (SDL_Init(SDL_INIT_VIDEO) != 0 ) { fprintf(stdout,"Échec de l'initialisation de la SDL (%s)\n",SDL_GetError()); return -1; } //writeScore("Flo 2", 92); TTF_Init(); /* Création de la fenêtre */ SDL_Window* pWindow = NULL; SDL_Renderer* pRenderer = NULL; SDL_Surface* pSurface = NULL; TTF_Font* font = TTF_OpenFont("/Library/Fonts/Microsoft/Arial.ttf", 72); pWindow = SDL_CreateWindow("Space Invaders",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_PRESENTVSYNC); /* Initialisation du texte */ if ( pWindow ) { loop = 1; menu = 1; selectedMenu = 1; while (loop == 1) { key = getKey(key); if (key.exit == 1) loop = 0; if (menu == 1) { if (key.down == 1 && selectedMenu < 4) selectedMenu++; else if (key.up == 1 && selectedMenu > 1) selectedMenu--; else if (key.enter == 1) { if (selectedMenu == 1) menu = 0; else if (selectedMenu == 2) menu = 1; //doing nothing yet else if (selectedMenu == 3) menu = 2; else if (selectedMenu == 4) loop = 0; } pRenderer = drawMenu(pRenderer, selectedMenu, font, pSurface); } else if (menu == 2) { if (key.enter == 1) menu = 1; else pRenderer = drawHighScores(pRenderer, font, pSurface); } else pRenderer = drawGame(pRenderer); SDL_Delay(100); } } TTF_CloseFont(font); SDL_DestroyWindow(pWindow); TTF_Quit(); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { /* initialize SDL and its subsystems */ if (SDL_Init(SDL_INIT_EVERYTHING) == -1) die(); if (TTF_Init() == -1) die(); /* set the height and width of the main window, as well as the number of bits per pixel; this needs to be done prior to initializing the main window (*screen, below) */ initWindowAttributes(); /* the frame buffer */ SDL_Surface *screen = SDL_SetVideoMode(W_WIDTH, W_HEIGHT, W_COLOR_DEPTH, SDL_HWSURFACE|SDL_FULLSCREEN); if (!screen) die(); /* hide the mouse cursor */ SDL_ShowCursor(SDL_DISABLE); /* the background color of the screen */ const Uint32 clearColor = CLEAR_COLOR(screen->format); clearScreen(screen, clearColor); /* clearColor as an SDL_Color, for use with TTF */ Uint8 r, g, b; SDL_GetRGB(clearColor, screen->format, &r, &g, &b); SDL_Color bgColor = { r: r, g: g, b: b }; /* the score font */ TTF_Font *font = TTF_OpenFont("resources/VeraMono.ttf", FONT_SIZE); if (!font) die(); SDL_Color fontColor = FONT_COLOR; /* the score text; we'll allow three digits plus the terminating '\0' */ char *lScoreStr = malloc(sizeof(char) * 4); char *rScoreStr = malloc(sizeof(char) * 4); if (!lScoreStr || !rScoreStr) die(); SDL_Surface *lScore = NULL, *rScore = NULL; SDL_Rect lScorePos = { x: C_X+FONT_SIZE, y: C_HEIGHT/5, w: F_WIDTH, h: F_HEIGHT }; SDL_Rect rScorePos = { x: (C_X+C_WIDTH)-3*FONT_SIZE, y: C_HEIGHT/5, w: F_WIDTH, h: F_HEIGHT }; /* set up the playing court */ Court *court = makeCourt(screen); if (!court) die(); /* set up the players and their paddles */ Player *lPlayer = makePlayer(screen); Player *rPlayer = makePlayer(screen); if (!lPlayer || !rPlayer) die(); rPlayer->paddle.rect.x = C_X + C_WIDTH - P_WIDTH; /* add the ball */ Ball *ball = makeBall(screen); if (!ball) die(); /* because SDL_KEY(UP|DOWN) occurs only once, not continuously while the key is pressed, we need to keep track of whether a key is (still) pressed */ bool lPlayerShouldMoveUp = false, lPlayerShouldMoveDown = false, rPlayerShouldMoveUp = false, rPlayerShouldMoveDown = false; Uint32 startTime; /* denotes the beginning of each iteration of the main event loop */ bool running = true; /* true till the application should exit */ while (running) { startTime = SDL_GetTicks(); /* clear the previous frame's paddles and ball */ SDL_FillRect(screen, &lPlayer->paddle.rect, clearColor); SDL_FillRect(screen, &rPlayer->paddle.rect, clearColor); SDL_FillRect(screen, &ball->rect, clearColor); /* clear the previous frame's score */ SDL_FillRect(screen, &lScorePos, clearColor); SDL_FillRect(screen, &rScorePos, clearColor); /* redraw the walls in case they were clipped by the ball in a previous frame */ SDL_FillRect(screen, &court->upperWall, court->color); SDL_FillRect(screen, &court->lowerWall, court->color); /* get the current state of the players' controls */ readPlayerInput(&running, &lPlayerShouldMoveUp, &lPlayerShouldMoveDown, &rPlayerShouldMoveUp, &rPlayerShouldMoveDown); /* save the current position of the paddles */ lPlayer->paddle.prevY = lPlayer->paddle.rect.y; rPlayer->paddle.prevY = rPlayer->paddle.rect.y; /* move the paddles if appropriate */ if (lPlayerShouldMoveUp) movePaddle(court, &lPlayer->paddle, UP); else if (lPlayerShouldMoveDown) movePaddle(court, &lPlayer->paddle, DOWN); if (rPlayerShouldMoveUp) movePaddle(court, &rPlayer->paddle, UP); else if (rPlayerShouldMoveDown) movePaddle(court, &rPlayer->paddle, DOWN); /* move the ball */ moveBall(court, ball, lPlayer, rPlayer); /* update the score */ updateScore(ball, lPlayer, rPlayer); /* update the on-screen score */ if (lScore) SDL_FreeSurface(lScore); snprintf(lScoreStr, 4, "%2d", lPlayer->points); lScore = TTF_RenderText_Shaded(font, lScoreStr, fontColor, bgColor); if (rScore) SDL_FreeSurface(rScore); snprintf(rScoreStr, 4, "%2d", rPlayer->points); rScore = TTF_RenderText_Shaded(font, rScoreStr, fontColor, bgColor); /* draw the score */ SDL_BlitSurface(lScore, NULL, screen, &lScorePos); SDL_BlitSurface(rScore, NULL, screen, &rScorePos); /* draw the paddles */ SDL_FillRect(screen, &lPlayer->paddle.rect, lPlayer->paddle.color); SDL_FillRect(screen, &rPlayer->paddle.rect, rPlayer->paddle.color); /* draw the ball */ SDL_FillRect(screen, &ball->rect, ball->color); /* render frame to screen */ SDL_Flip(screen); /* keep a steady frame rate */ Uint8 elapsedTime = SDL_GetTicks() - startTime; if (elapsedTime < FRAME_DURATION) SDL_Delay(FRAME_DURATION - elapsedTime); } /* free resources */ free(lScoreStr); free(rScoreStr); free(court); free(lPlayer); free(rPlayer); free(ball); TTF_CloseFont(font); TTF_Quit(); SDL_FreeSurface(lScore); SDL_FreeSurface(rScore); SDL_Quit(); return EXIT_SUCCESS; }
bool Card::loadingText(SDL_Renderer* r, std::string svHeader, std::string svText, std::string enHeader, std::string enText, std::vector<std::string> svCat, std::vector<std::string> enCat){ // /Library/Fonts Arial.ttf bool success = true; // Loading font if( TTF_Init() == -1 ) { printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } TTF_Font *gFont = NULL; gFont = TTF_OpenFont( "/Library/Fonts/Arial.ttf", 100 ); // Apple: "/Library/Fonts/Arial.ttf" if( gFont == NULL ) { printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } SDL_Color textColor = { 0, 0, 0}; // Loading text SDL_Surface* textSurface = NULL; // Svenska header textSurface = TTF_RenderText_Blended( gFont, svHeader.c_str(), textColor); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels headersSv.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( headersSv[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } // Svenska text textSurface = NULL; textSurface = TTF_RenderText_Blended_Wrapped( gFont, svText.c_str(), textColor, 3000); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels infoTextSv.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( infoTextSv[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } // Svenska kategorier textSurface = NULL; std::string catString = "Kategorier som kortet tillhˆr kommer synas h‰r"; for (int i = 0; i < svCat.size(); i++) { if (i > 0) { catString += " - "; catString += svCat[i].c_str() ; } else { catString = svCat[i].c_str() ; } } textSurface = TTF_RenderText_Blended( gFont, catString.c_str(), textColor); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels catTextSv.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( catTextSv[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } // English header textSurface = NULL; textSurface = TTF_RenderText_Blended( gFont, enHeader.c_str(), textColor); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels headersEn.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( headersEn[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } // English text textSurface = NULL; textSurface = TTF_RenderText_Blended_Wrapped( gFont, enText.c_str(), textColor, 3000); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels infoTextEn.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( infoTextEn[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } // Engelska kategorier textSurface = NULL; catString = "Categories for the cards will be here"; for (int i = 0; i < enCat.size(); i++) { if (i > 0) { catString += " - "; catString += enCat[i].c_str() ; } else { catString = enCat[i].c_str() ; } } textSurface = TTF_RenderText_Blended( gFont, catString.c_str(), textColor); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Create texture from surface pixels catTextEn.push_back( SDL_CreateTextureFromSurface( r, textSurface )); if( catTextEn[infoIndex] == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); success = false; } //Get rid of old surface SDL_FreeSurface( textSurface ); } TTF_CloseFont( gFont ); gFont = NULL; return success; }
int main(int argc, char *argv[]) { SDL_Surface *screen = NULL, *image = NULL, *scaledImage = NULL, *name = NULL; SDL_Rect picturePortion; TTF_Font *font = NULL; double scale = 1.0; int currentImageNumber = 1, showFileName = TRUE, runSlideShow = FALSE, isRunning = TRUE; SDL_TimerID slideShowTimer = 0; // Process command line if (argc < 2) { fprintf(stderr, "\n" " imgv v%s. Syntax: imgv <image files>\n\n" " Hotkeys:\n" " 'f' fit to screen\n" " 'z' zoom at pixel level\n" " 'i' zoom in 'o' zoom out\n" " 'l' rotate left 'r' rotate right\n" " 'n' next image 'p' previous image\n" " 'd' show / hide file name\n" " 's' start / stop slide show\n" " 'arrows' pan 'ESC' quit\n\n", VERSION); exit(0); } screen = initScreen(); font = TTF_OpenFont("font.ttf", 11); if (font == (TTF_Font *) (NULL)) { font = TTF_OpenFont("/usr/share/imgv/font.ttf", 11); } if (font == (TTF_Font *) (NULL)) { font = TTF_OpenFont("/usr/share/fonts/ttf-dejavu/DejaVuSans.ttf", 11); } picturePortion.w = SCREENWIDTH; picturePortion.h = SCREENHEIGHT; image = loadImage(argv[1]); if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) { scaledImage = zoom100(image, &picturePortion, &scale); } else { scaledImage = zoomFit(image, &picturePortion, &scale); } name = drawFileName(argv[currentImageNumber], font, runSlideShow); drawImage(scaledImage, &picturePortion, screen, name); do { SDL_Event event; if (SDL_WaitEvent(&event) && event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_LEFT: // PAN LEFT pan(scaledImage, &picturePortion, -PANSTEP, 0); break; case SDLK_RIGHT: // PAN RIGHT pan(scaledImage, &picturePortion, PANSTEP, 0); break; case SDLK_UP: // PAN UP pan(scaledImage, &picturePortion, 0, -PANSTEP); break; case SDLK_DOWN: // PAN DOWN pan(scaledImage, &picturePortion, 0, PANSTEP); break; case SDLK_i: // ZOOM IN SDL_FreeSurface(scaledImage); scaledImage = zoomIn(image, &picturePortion, &scale); break; case SDLK_o: // ZOOM OUT SDL_FreeSurface(scaledImage); scaledImage = zoomOut(image, &picturePortion, &scale); break; case SDLK_f: // ZOOM TO FIT SCREEN SDL_FreeSurface(scaledImage); scaledImage = zoomFit(image, &picturePortion, &scale); break; case SDLK_z: // ZOOM TO ORIGINAL SIZE SDL_FreeSurface(scaledImage); scaledImage = zoom100(image, &picturePortion, &scale); break; case SDLK_l: // ROTATE LEFT { SDL_FreeSurface(scaledImage); SDL_Surface *tmp = rotateSurface90Degrees(image, 3); SDL_FreeSurface(image); image = tmp; scaledImage = zoomSurface(image, scale, scale, SMOOTHING_ON); int x = picturePortion.x; picturePortion.x = picturePortion.y + SCREENHEIGHT/2 - SCREENWIDTH/2; picturePortion.y = scaledImage->h - x - SCREENHEIGHT/2 - SCREENWIDTH/2; pan(scaledImage, &picturePortion, 0, 0); } break; case SDLK_r: // ROTATE RIGHT { SDL_FreeSurface(scaledImage); SDL_Surface *tmp = rotateSurface90Degrees(image, 1); SDL_FreeSurface(image); image = tmp; scaledImage = zoomSurface(image, scale, scale, SMOOTHING_ON); int x = picturePortion.x; picturePortion.x = scaledImage->w - picturePortion.y - SCREENWIDTH/2 - SCREENHEIGHT/2; picturePortion.y = x + SCREENWIDTH/2 - SCREENHEIGHT/2; pan(scaledImage, &picturePortion, 0, 0); } break; case SDLK_n: // NEXT IMAGE if (currentImageNumber < argc-1) { ++currentImageNumber; SDL_FreeSurface(image); SDL_FreeSurface(scaledImage); SDL_FreeSurface(name); image = loadImage(argv[currentImageNumber]); if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) { scaledImage = zoom100(image, &picturePortion, &scale); } else { scaledImage = zoomFit(image, &picturePortion, &scale); } name = drawFileName(argv[currentImageNumber], font, runSlideShow); } else { if (runSlideShow) { SDL_RemoveTimer(slideShowTimer); runSlideShow = FALSE; name = drawFileName(argv[currentImageNumber], font, runSlideShow); } } break; case SDLK_p: // PREVIOUS IMAGE if (currentImageNumber > 1) { --currentImageNumber; SDL_FreeSurface(image); SDL_FreeSurface(scaledImage); SDL_FreeSurface(name); image = loadImage(argv[currentImageNumber]); if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) { scaledImage = zoom100(image, &picturePortion, &scale); } else { scaledImage = zoomFit(image, &picturePortion, &scale); } name = drawFileName(argv[currentImageNumber], font, runSlideShow); } break; case SDLK_s: // START / STOP SLIDESHOW runSlideShow = 1 - runSlideShow; name = drawFileName(argv[currentImageNumber], font, runSlideShow); if (runSlideShow) { slideShowTimer = SDL_AddTimer(SLIDESHOWTIMEOUT, timerCallback, NULL); } else { SDL_RemoveTimer(slideShowTimer); } break; case SDLK_d: // SHOW / HIDE FILENAME showFileName = 1 - showFileName; break; case SDLK_ESCAPE: // QUIT case SDLK_q: isRunning = FALSE; break; default: break; } // end of switch (event.key.keysym.sym) } // end of if(SDL_WaitEvent()) drawImage(scaledImage, &picturePortion, screen, showFileName ? name : 0); } while(isRunning); // end of do SDL_FreeSurface(image); SDL_FreeSurface(scaledImage); SDL_FreeSurface(screen); TTF_CloseFont(font); TTF_Quit(); SDL_Quit(); return 0; }
static void _init_overlay(game *g) { overlay *o = &g->o; // Texture values o->tex_format = GL_RGBA; o->int_format = GL_RGBA8; o->tex_type = GL_UNSIGNED_INT_8_8_8_8; o->alignment = 4; // Font values o->update_text_max = 8; o->label_text_max = 32; o->text_pad = 0.5; o->font_spacing = 1.2; // Surface values Uint32 rmask = 0xff000000; Uint32 gmask = 0x00ff0000; Uint32 bmask = 0x0000ff00; Uint32 amask = 0x000000ff; // Overlay stuff o->size = 0.4; o->mvp = malloc(sizeof(mat4x4)); mat4x4_ortho(*o->mvp, -g->aspect, g->aspect, -1.0, 1.0, 0, 10); int win_width, win_height, overlay_width, overlay_height; SDL_GetWindowSize(g->win, &win_width, &win_height); overlay_width = win_width * o->size; overlay_height = win_height * o->size; float overlay_triangles[8] = { -g->aspect*o->size, o->size, // Top left -g->aspect*o->size, -o->size, // Bottom left g->aspect*o->size, -o->size, // Bottom right g->aspect*o->size, o->size, // Top right }; GLubyte overlay_elements[6] = { 0, 1, 2, 0, 2, 3 }; float overlay_tex_coords[8] = { 0.0, 0.0, // Top left 0.0, 1.0, // Bottom left 1.0, 1.0, // Bottom right 1.0, 0.0, // Top right }; o->matrix_id = glGetUniformLocation(g->overlay_shader, "MVP"); o->tex_coords_id = glGetAttribLocation(g->overlay_shader, "tex_coord"); glUseProgram(g->overlay_shader); glUniformMatrix4fv(o->matrix_id, 1, GL_FALSE, (GLfloat *) o->mvp); glUseProgram(0); glGenBuffers(1, &o->vert_buf); glBindBuffer(GL_ARRAY_BUFFER, o->vert_buf); glBufferData(GL_ARRAY_BUFFER, sizeof(overlay_triangles), &overlay_triangles, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &o->tex_coord_buf); glBindBuffer(GL_ARRAY_BUFFER, o->tex_coord_buf); glBufferData(GL_ARRAY_BUFFER, sizeof(overlay_tex_coords), &overlay_tex_coords, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &o->el_buf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, o->el_buf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(overlay_elements), &overlay_elements, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Set up font things char *res_path = get_res_path(""), *font_path = join_path(res_path, "DejaVuSansMono.ttf"); o->font = TTF_OpenFont(font_path, 14); free(res_path); free(font_path); o->font_text = calloc(o->update_text_max+1, sizeof(char)); o->bg = SDL_CreateRGBSurface( 0, overlay_width, overlay_height, 32, rmask, gmask, bmask, amask ); if (o->bg == NULL) { printf("BLARGH: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } o->font_text[0] = 'W'; SDL_Surface *temp_surf; temp_surf = TTF_RenderText_Solid(o->font, o->font_text, o->font_col); int font_w = temp_surf->w; int font_h = temp_surf->h; SDL_free(temp_surf); o->font_surf = SDL_CreateRGBSurface( 0, font_w * o->update_text_max + 1, font_h, 32, rmask, gmask, bmask, amask ); // Render static text _update_colors(g, g->color_scheme); glGenTextures(1, &o->tex); glBindTexture(GL_TEXTURE_2D, o->tex); glPixelStorei(GL_UNPACK_ALIGNMENT, o->alignment); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, o->int_format, o->bg->w, o->bg->h, 0, o->tex_format, o->tex_type, o->bg->pixels); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); }
void loadFonts(Font *font) { font->font[EX_FONT] = TTF_OpenFont(FILE_FONT, SIZE_EX_FONT ); }
SpriteFont::SpriteFont(const char* font, int size, char cs, char ce) { // Initialize SDL_ttf if (!TTF_WasInit()) { TTF_Init(); } TTF_Font* f = TTF_OpenFont(font, 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, bestWidth = 0, bestHeight = 0, area = MAX_TEXTURE_RES * MAX_TEXTURE_RES, bestRows = 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; bestWidth = w; bestHeight = h; bestRows = rows; area = bestWidth * bestHeight; 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, &_texID); glBindTexture(GL_TEXTURE_2D, _texID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bestWidth, bestHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // 'w 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 (size_t 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] *= a; sp[i + 1] = sp[i]; sp[i + 2] = sp[i]; } // Save glyph image and update coordinates glTexSubImage2D(GL_TEXTURE_2D, 0, lx, bestHeight - 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)bestWidth, (float)glyphRects[i].y / (float)bestHeight, (float)glyphRects[i].z / (float)bestWidth, (float)glyphRects[i].w / (float)bestHeight ); } _glyphs[_regLength].character = ' '; _glyphs[_regLength].size = _glyphs[0].size; _glyphs[_regLength].uvRect = glm::vec4(0, 0, (float)rs / (float)bestWidth, (float)rs / (float)bestHeight); glBindTexture(GL_TEXTURE_2D, 0); delete[] glyphRects; delete[] bestPartition; TTF_CloseFont(f); }
int main(int argc, char ** argv) { SDL_Window * window; SDL_Renderer * renderer; SDL_Surface * set; KW_GUI * gui; TTF_Font * font; SDL_Rect geometry = {0, 0, 320, 240}; KW_Widget * frame, * button; int i; SDL_Event ev; /* initialize SDL */ SDL_Init(SDL_INIT_EVERYTHING); #if defined(ANDROID) /* enjoy all the screen size on android */ i = SDL_GetNumVideoDisplays(); if (i < 1) exit(1); SDL_GetDisplayBounds(0, &geometry); #endif SDL_CreateWindowAndRenderer(geometry.w, geometry.h, SDL_WINDOW_RESIZABLE, &window, &renderer); SDL_SetRenderDrawColor(renderer, 100, 200, 100, 1); TTF_Init(); /* load tileset */ set = IMG_Load("tileset.png"); /* initialize gui */ gui = KW_Init(renderer, set); font = TTF_OpenFont("SourceSansPro-Semibold.ttf", 12); TTF_SetFontHinting(font, TTF_HINTING_NONE); KW_SetFont(gui, font); geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875; frame = KW_CreateScrollbox(gui, NULL, &geometry); KW_AddWidgetDragStartHandler(frame, DragStart); KW_AddWidgetDragHandler(frame, Drag); KW_AddWidgetDragStopHandler(frame, DragStop); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); geometry.x = 10; geometry.y = 0; geometry.h = 40; geometry.w = 230; for (i = 0; i < 5; i++) { button = KW_CreateButton(gui, frame, "Drag me, resize me.", &geometry); KW_AddWidgetDragStartHandler(button, DragStart); KW_AddWidgetDragHandler(button, Drag); KW_AddWidgetDragStopHandler(button, DragStop); geometry.y += geometry.h; } /* create another parent frame */ while (!SDL_QuitRequested()) { while (SDL_PollEvent(&ev)) { if (ev.type == SDL_WINDOWEVENT && ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { geometry.w = ev.window.data1; geometry.h = ev.window.data2; geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875; KW_SetWidgetGeometry(frame, &geometry); } } SDL_RenderClear(renderer); KW_Paint(gui); SDL_RenderPresent(renderer); SDL_Delay(1); } TTF_CloseFont(font); TTF_Quit(); KW_Quit(gui); SDL_FreeSurface(set); SDL_Quit(); return 0; }
int main(int argc, char * argv[]) { input_init(); std::string path_to_exe(""); { std::string path_with_exe(argv[0]); unsigned found = path_with_exe.find_last_of("/\\"); path_to_exe = path_with_exe.substr(0,found+1); } std::cout<<path_to_exe<<std::endl; SDL_Init( SDL_INIT_EVERYTHING ); TTF_Init(); SDL_Surface * screen = SDL_SetVideoMode( 640, 480, 32, SDL_HWSURFACE); GUI_Init(screen); { std::string font_path(path_to_exe); font_path += "freefont/FreeMono.ttf"; GUI_standard_font = TTF_OpenFont( font_path.c_str(), 15 ); } std::cout<<"fontptr: "<<GUI_standard_font<<std::endl; Area * screen_widget = new Area(0, 0, 640, 480); Area * test_widget = new Area(20, 20, 200, 200, screen_widget); test_widget->set_colour(200, 100, 100); Area * another_test_widget = new Area(240, 20, 200, 200, screen_widget); another_test_widget->set_colour(100, 200, 100); Area * ultra_test_widget = new Area(20, 20, 160, 160, another_test_widget); ultra_test_widget->set_colour(100, 100, 200); Label * test_label = new Label(10, 10, 140, 20, ultra_test_widget); test_label->set_colour(120, 120, 220); test_label->set_text("Hallo Welt!"); Button * test_button = new Button(10, 40, 120, 20, ultra_test_widget); test_button->set_colour(100, 200, 200); test_button->set_text("Test!"); Button * end_button = new Button(20, 240, 120, 20, screen_widget); end_button->set_colour(255, 0, 0); end_button->set_text("Ende!"); Text_Edit * text_edit = new Text_Edit(20, 280, 160, 20, screen_widget); text_edit->set_text("aender mich!"); input_update(); while(!key_hit(SDLK_ESCAPE) && !end_button->released)// && !mouse_hit(1)) { SDL_Surface * screen_surface = screen_widget->get_sdl_surface(); SDL_BlitSurface(screen_surface, NULL, screen, NULL); screen_widget->update(); if(test_button->released) { test_label->set_text("Button geklickt!"); } SDL_Flip(screen); flush_keys(); flush_mouse(); SDL_Delay(1000/60); input_update(); } //SDL_Delay(2000); return 0; }
// based on http://www.willusher.io/sdl2%20tutorials/2013/08/17/lesson-1-hello-world/ int main( int argc, char* args[] ) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; cleanExit(1); } std::cout << "SDL initialised OK!\n"; // Initialise the audio mixer and also explained the variables. // 44100 - Common hertz level for these things // MIX_DEFAULT_FORMAT - Like the SDL_INIT_EVERYTHING, some init settings // 2 - Audio Channels for stereo play // 2048 - Sample size, can affect lag time for effect to play // != 0 - Same as other init stuff, not sure why, just needs it. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) != 0) { std::cout << "SDL_Mixer init error: " << Mix_GetError() << std::endl; cleanExit(1); } std::cout << "SDP_Mixer Initialised OK!" << std::endl; //create window win = SDL_CreateWindow("SDL Hello World!", 100, 100, screenW, screenH, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); //error handling if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; cleanExit(1); } std::cout << "SDL CreatedWindow OK!\n"; ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; cleanExit(1); } player = new sprite("./assets/spritesheet.png", 50.0f, 520.0f, 24.0f, 32.0f, ren); player->srcRect.x = 0.0f; player->srcRect.y = 96.0f; player->srcRect.w = 24.0f; player->srcRect.h = 32.0f; player->playerScore = 0; player->bufferMax = 5; #pragma region Hens hen1 = new enemy("./assets/spritesheet.png", 500, 100, 24, 40, ren); hens.push_back(hen1); hen1->state = enemy::moveRight; hen1->flipDirection = true; hen1->xTarget1 = 200.0f; hen1->xTarget2 = 250.0f; hen1->srcRect.x = 0.0f; hen1->srcRect.y = 0.0f; hen1->srcRect.w = 24.0f; hen1->srcRect.h = 40.0f; hen2 = new enemy("./assets/spritesheet.png", 700, 530, 24, 40, ren); hens.push_back(hen2); hen2->state = enemy::moveLeft; hen2->xTarget1 = 100.0f; hen2->xTarget2 = 750.0f; hen2->srcRect.x = 0.0f; hen2->srcRect.y = 0.0f; hen2->srcRect.w = 24.0f; hen2->srcRect.h = 40.0f; hen3 = new enemy("./assets/spritesheet.png", 600, 280, 24, 40, ren); hens.push_back(hen3); hen3->state = enemy::moveRight; hen3->xTarget1 = 100.0f; hen3->xTarget2 = 750.0f; hen3->srcRect.x = 0.0f; hen3->srcRect.y = 0.0f; hen3->srcRect.w = 24.0f; hen3->srcRect.h = 40.0f; #pragma endregion #pragma region Audio stuff // This is formatted in the same way to the default code from John as it makes sense and I want to stick to it. jumpEffect = Mix_LoadWAV("./assets/jump.wav"); if (jumpEffect == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } pickup1 = Mix_LoadWAV("./assets/pickup1.wav"); if (pickup1 == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } pickup2 = Mix_LoadWAV("./assets/pickup2.wav"); if (pickup2 == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } background = Mix_LoadMUS("./assets/background_music.wav"); if (background == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } #pragma endregion if( TTF_Init() == -1 ) { std::cout << "TTF_Init Failed: " << TTF_GetError() << std::endl; cleanExit(1); } TTF_Font* sans = TTF_OpenFont("./assets/Hack-Regular.ttf", 96); if (sans == nullptr) { std::cout << "TTF_OpenFont Error: " << TTF_GetError() << std::endl; cleanExit(1); } SDL_Color White = { 255, 255, 255 }; SDL_Color Purple = { 165, 0, 220 }; std::string lives = "Lives: " + std::to_string(player->playerLives); const char* lifeCounts = lives.c_str(); loading = new text(ren, "Loading...", 200, 200, 400, 130, sans, White); Load(); scoreCount = new text(ren, player->playerScore, 0, 0, 180, 60, sans, Purple); lifeCount = new text(ren, lifeCounts, 600, 0, 180, 60, sans, Purple); drawTileMap(); loading->isShowing = false; Mix_PlayMusic(background, -1); while (!done) //loop until done flag is set) { handleInput(); // this should ONLY SET VARIABLES updateSimulation(); // this should ONLY SET VARIABLES according to simulation render(); // this should render the world state according to VARIABLES SDL_Delay(20); // unless vsync is on?? } cleanExit(0); return 0; }
void InitLoginStore(struct typelogin *loginstore,struct DIVERSsysteme *systeme) { loginstore->police = TTF_OpenFont("rs/divers/police1.ttf", TAILLE_POLICE_LOGIN); loginstore->pseudo.img.texture = imprime ("pseudo :", screenw, BLEU, systeme, &loginstore->pseudo.lenght, NULL); loginstore->mdp.img.texture = imprime ("mot de passe :", screenw, BLEU, systeme, &loginstore->mdp.lenght, NULL); setPos4(&loginstore->login.pos, 0, 0, screenw, screenh); setPos4(&loginstore->pointeur.pos, 0, 0, 40, 60); setPos4(&loginstore->blueBox.pos, 0, 0, 0, 0); setPos4(&loginstore->whiteBox.pos, 0, 0, 0, 0); setPos4(&loginstore->tdialogue.pos, screenw/8, (screenh/12)*5, (screenw/8)*6, (screenh/6)); setPos4(&loginstore->cachermdp.pos, screenw*0.75, screenh*0.3, screenw/6, screenh/12); setPos4(&loginstore->coche.pos, screenw*0.75, screenh*0.3, loginstore->cachermdp.pos.w/3, loginstore->cachermdp.pos.h*1.3); loginstore->login.texture = loadTexture("rs/fonds/login.png"); loginstore->pointeur.texture = loadTexture("rs/images/p.png"); loginstore->blueBox.texture = loadTexture("rs/images/blueBox.png"); loginstore->whiteBox.texture = loadTexture("rs/images/whiteBox.png"); loginstore->tdialogue.texture = loadTexture("rs/ui/fenetreinfo.png"); loginstore->cachermdp.texture = loadTexture("rs/images/cachermdp.png"); loginstore->coche.texture = loadTexture("rs/images/coche.png"); loginstore->noir.texture = 0; loginstore->couleurNoir.r = 0; loginstore->couleurNoir.g = 0; loginstore->couleurNoir.b = 0; loginstore->couleurNoir.a = 0; loginstore->couleurBleu.r = 0; loginstore->couleurBleu.g = 75; loginstore->couleurBleu.b = 255; loginstore->couleurBleu.a = 0; loginstore->pecran.x = 0; loginstore->pecran.y = 0; loginstore->pecran.w = screenw; loginstore->pecran.h = screenh; loginstore->noir.pos.x = 0; loginstore->noir.pos.y = 0; loginstore->noir.pos.w = 3; loginstore->noir.pos.h = TAILLE_POLICE_LOGIN; loginstore->noir.texture = 0; loginstore->pcase.w = screenw*0.25; loginstore->pcase.h = screenh*0.05; loginstore->pcase.x = (screenw-loginstore->pcase.w)*0.5; loginstore->pcase.y = screenh/2; loginstore->pcase2.w = screenw*0.25; loginstore->pcase2.h = screenh*0.05; loginstore->pcase2.x = (screenw-loginstore->pcase2.w)*0.5; loginstore->pcase2.y = (screenh*0.5)-(screenh*0.125); loginstore->LEmdp.img.pos.h = screenh/20; loginstore->LEmdp.img.pos.x = loginstore->pcase.x + 10; loginstore->LEmdp.img.pos.y = (screenh*0.5)-(screenh*0.125)+2; loginstore->LEpseudo.img.pos.h = screenh/20; loginstore->LEpseudo.img.pos.x = loginstore->pcase.x + 10; loginstore->LEpseudo.img.pos.y = (screenh/2)+2; loginstore->pseudo.img.pos.w = (screenw/4)-2; loginstore->pseudo.img.pos.h = screenh/20; loginstore->pseudo.img.pos.x = (screenw-loginstore->pseudo.img.pos.w)/2; loginstore->pseudo.img.pos.y = (screenh/2)+(screenh/8)-loginstore->pseudo.img.pos.h; loginstore->mdp.img.pos.w = (screenw/4)-2; loginstore->mdp.img.pos.h = screenh/20; loginstore->mdp.img.pos.x = (screenw-loginstore->mdp.img.pos.w)/2; loginstore->mdp.img.pos.y = (screenh/2)-loginstore->pseudo.img.pos.h; loginstore->saisiepseudo = true; loginstore->saisiemdp = false; loginstore->clignote = true; loginstore->continuer = 1; loginstore->longpseudo = 0; loginstore->i = 0; loginstore->longmdp = 0; loginstore->menu = false; loginstore->optionactif = 0; loginstore->mdpcacher = 1; loginstore->tpact = 0; loginstore->tpapr = 0; loginstore->tpcurseur = 0; loginstore->lettre = '0'; /*récupération du type de clavier utilisé*/ loginstore->fichier = fopen("rs/options.RSsave", "r"); systeme->typeclavier = fgetc(loginstore->fichier); fclose(loginstore->fichier); for (loginstore->i = 0 ; loginstore->i < 21 ; loginstore->i++) { loginstore->mdpshow[loginstore->i] = '\0'; } if (systeme->typeclavier == '1') {loginstore->azerty.etat = B_CLIQUER;} else if (systeme->typeclavier == '2') {loginstore->qwerty.etat = B_CLIQUER;} else if (systeme->typeclavier == '3') {loginstore->qwertz.etat = B_CLIQUER;} sprintf(loginstore->info, "Pseudo incorrect \n\nveuillez entrer un pseudo et un mot de passe."); sprintf(loginstore->info2, "Pseudo incorrect\n\nLe pseudo que vous avez entre existe deja, veuillez en choisir un autre."); sprintf(loginstore->info3, "Identifiants incorrects\n\nVotre personnage n'existe pas, creez en un sans attendre !"); sprintf(loginstore->info4, "Identifiants incorrects\n\nVotre mot de passe et votre pseudo ne correspondent pas.\n\nessayer un autre mot de passe."); loginstore->ttextedialogue = -1; }
int main(int argc, char **argv) { if (!init()) { return 1; } if (!loadMedia()) { return 2; } SDL_Event e; bool running = true; MyTimer timer; std::stringstream ss; while (running) { while (SDL_PollEvent(&e)) { if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_RETURN: if (timer.isStarted()) timer.stop(); else timer.start(); break; case SDLK_p: if (timer.isPaused()) timer.unpause(); else timer.pause(); break; default: break; } } if (e.type == SDL_QUIT) { running = false; } } ss.str(""); ss << "Milliseconds from start time: " << timer.getTicks(); //draw something SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff); SDL_RenderClear(renderer); promptText->rendering((800 - promptText->getWidth()) / 2, 0); promptText2->rendering((800 - promptText2->getWidth()) / 2, promptText->getHeight()); timerText->loadText(TTF_OpenFont("font/Amble-Bold.ttf", 30), ss.str().c_str(), { 0, 0xff, 0}, { 0, 0, 0 }); timerText->rendering((800 - timerText->getWidth()) / 2, (600 - timerText->getHeight()) / 2); SDL_RenderPresent(renderer); } close(); return 0; }
/**@brief:constructor de QuestionEngine que * @param:ninguno * @pre:ninguno * @post:ninguno */ QuestionEngine::QuestionEngine(){ //Setting font colors //Background bgcolor.r=255; bgcolor.g=0; bgcolor.b=0; //Question qfcolor.r=32; qfcolor.g=178; qfcolor.b=170; //Answer afcolor.r=255; afcolor.g=255; afcolor.b=255; correct=0; for (int i=0; i<4; i++) { rect[i].y = 20+(i*100); rect[i].x = (i==0) ? 20 : 50; rect[i].w = (i==0) ? 500 : 470; } font = TTF_OpenFont("/Library/Fonts/Arial.ttf", 30); ifstream file; stringstream ss, iss; string line, sType; string question, answ[3]; int type, correct, i=0; int counter=1; std::cout << "Constructor de QuestionEngine" << std::endl; file.open("/Users/Donflopez/Downloads/preguntas.tjData"); if(file.good()){ while (file.eof()!=true) { getline(file,line); ss << line; getline(ss, sType, ';'); type = atoi(sType.c_str()); std::cout << "Type before: " << type << std::endl; getline(ss, question, ';'); getline(ss, answ[0], ';'); getline(ss, answ[1], ';'); getline(ss, answ[2], ';'); getline(ss, sType, ';'); correct = atoi(sType.c_str()); std::cout <<"Type: " << type << "and i: " << i << std::endl; questions[type][i] = new QandA(question, answ, correct); std::cout << "Total cargado: " << counter << "%" << std::endl; counter++; //std::cout << "Pregunta " << i << " tipo " << type << ":" << questions[type][i]->getQuestion() << std::endl; if (i<19) { i++; }else { i=0; } } } /*for (int i=0; i<5; i++) { for (int j=0; j<20; j++) { questions[i][j]=new QandA(); } }*/ }
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; }
int main(int argc, char *argv[]) { srandom(time(0) * getpid()); int done; SDL_Event event; if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen=SDL_SetVideoMode(screen_width,screen_height, 16, SDL_OPENGL | SDL_RESIZABLE); if (screen == NULL) { fprintf(stderr, "Couldn't set 800x600x%i video mode: %s\n", 16, SDL_GetError()); SDL_Quit(); exit(2); } glEnable( GL_TEXTURE_2D ); glViewport( 0, 0, screen_width, screen_height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho(0.0f, screen_width, 0.0f, screen_height, -1.0f, 1.0f); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); // Enable Blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); SDL_GL_SwapBuffers(); addtimers(500,84000); unsigned int mousex; unsigned int mousey; TTF_Init(); TTF_Font* font = TTF_OpenFont("tower.app/Contents/Resources/" "Vera.ttf", 12); // FIXME: make this global if (font == NULL){ printf("Unable to load font, exiting!\n"); exit(1); } Globals *g = new Globals(); g->screen_width = screen_width; g->screen_height = screen_height; g->font = font; textureManager *tm = new textureManager(); g->tm = tm; GameTime *gt = new GameTime(); g->gt = gt; tm->loadAll(); g->bgim = tm->textures["buildingsbg"]; bgdraw *bg = new bgdraw(g); floormanager *fm = new floormanager(); fgdraw *fg = new fgdraw(g,fm); menudraw *mg = new menudraw(g); ////////////////////////////////////////////////////// fm->build_floor(0,10,40); fm->build_floor(1,12,38); fm->build_floor(2,14,36); fm->changeFloorLeft(1, 11); office *of = new office(11,1,tm,gt); fm->addBuilding(1, of); of->occupied = true; office *of2 = new office(20,1,tm,gt); fm->addBuilding(1, of2); ////////////////////////////////////////////////////// done = 0; while ( !done ) { /* Check for events */ while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_MOUSEMOTION: mousex = event.motion.x; mousey = event.motion.y; break; case SDL_USEREVENT: if(event.type==SDL_USEREVENT) { glClear( GL_COLOR_BUFFER_BIT ); bg->drawBG(); fg->drawFG(); mg->drawMenu(); SDL_GL_SwapBuffers(); Uint32 time = 50; timer1 = SDL_AddTimer(time, game_event_push, NULL); } break; case (SDL_USEREVENT+1): if(event.type==(SDL_USEREVENT+1)) { // timer2 = SDL_AddTimer(84000, rent_event_push, 0); } break; case SDL_MOUSEBUTTONDOWN: // toolLayerClicked(event.button.x,event.button.y); break; case SDL_MOUSEBUTTONUP: //toolLayerUnClicked(event.button.x,event.button.y); break; case SDL_VIDEORESIZE: screen_width = event.resize.w; screen_height = event.resize.h; /*screen=SDL_SetVideoMode(screen_width,screen_height, 16, SDL_OPENGL | SDL_RESIZABLE); if (screen == NULL) { fprintf(stderr,"Unable to grab surface after resize event: %s\n",SDL_GetError()); exit(1); }*/ glOrtho(0.0f, 1000, 1000, 0.0f, -1.0f, 1.0f); glViewport( 0, 0, screen_width, screen_height ); glLoadIdentity(); break; case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_q: removetimers(); SDL_Quit(); break; case SDLK_UP: g->y -= 10; glViewport( 0+g->x, 0+g->y, screen_width, screen_height ); glLoadIdentity(); break; case SDLK_DOWN: g->y += 10; glViewport( 0+g->x, 0+g->y, screen_width, screen_height ); glLoadIdentity(); break; case SDLK_LEFT: g->x += 10; glViewport( 0+g->x, 0+g->y, screen_width, screen_height ); glLoadIdentity(); break; case SDLK_RIGHT: g->x -= 10; glViewport( 0+g->x, 0+g->y, screen_width, screen_height ); glLoadIdentity(); break; default: break; } break; case SDL_QUIT: puts("Quitting"); removetimers(); done = 1; break; default: break; } } } /* Clean up the SDL library */ puts("reached SDL_QUIT"); SDL_Quit(); return(0); }
static void menu_preload(void) { if(s_preloaded) { return; } int index = 0; // used for the many loops in this function TTF_Init(); // beforehand, load the font file to render texts const char* font_path = DATA_PATH FONT_NAME; TTF_Font *font_28 = TTF_OpenFont(font_path, 28); if(!font_28) { fprintf(stderr, "Couldn't open font: %s!\n", TTF_GetError()); exit(EXIT_FAILURE); } const char* sec_font_path = DATA_PATH FONT_SEC_NAME; TTF_Font *font_20 = TTF_OpenFont(sec_font_path, 20); if(!font_20) { fprintf(stderr, "Couldn't open font: %s!\n", TTF_GetError()); exit(EXIT_FAILURE); } SDL_Color text_color = sdlutils_color(255, 255, 255); SDL_Color text_focus_color = sdlutils_color(255, 155, 0); // first, load the lists (of themes, level sets, levels) s_themes_names = theme_enumerate_themes(&s_themes_names_length); s_sets_names_length = level_enumerate_levelsets(&s_sets_names, &s_sets_levels); GLuint **alloc_array[] = { &s_pre_tex_set_names, &s_pre_tex_set_names_focus, &s_list_set_names, &s_list_set_names_focus, &s_pre_tex_theme_names, &s_pre_tex_theme_names_focus, &s_list_theme_names, &s_list_theme_names_focus }; int alloc_length_array[] = { s_sets_names_length, s_sets_names_length, s_sets_names_length, s_sets_names_length, s_themes_names_length, s_themes_names_length, s_themes_names_length, s_themes_names_length }; for(index = 0; index < 8; index++) { *(alloc_array[index]) = malloc(sizeof(GLuint) * alloc_length_array[index]); if(!*(alloc_array[index])) { fprintf(stderr, "Couldn't allocate %zu bytes!\n", sizeof(GLuint) * alloc_length_array[index]); exit(EXIT_FAILURE); } } /* * pre-render everything */ int w = 0, h = 0; int y_offset = 30; // pre-render main title s_pre_tex_main_title = glutils_load_texture_from_file(DATA_PATH IMG_MAIN_TITLE); glutils_get_texture_dim(s_pre_tex_main_title, &w, &h); s_list_main_title = glutils_create_list( s_pre_tex_main_title, w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); // pre-render menu text labels y_offset = 150; for(index = 0; index < __MENU_LABEL_LAST; index++) { s_pre_tex_labels[index] = glutils_render_text_to_texture( font_28, s_str_labels[index], text_color ); glutils_get_texture_dim(s_pre_tex_labels[index], &w, &h); s_options_y[index] = y_offset + h; // store y coordinate s_list_labels[index] = glutils_create_list( s_pre_tex_labels[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); // same for focused labels (only the color changes) s_pre_tex_labels_focus[index] = glutils_render_text_to_texture( font_28, s_str_labels[index], text_focus_color ); s_list_labels_focus[index] = glutils_create_list( s_pre_tex_labels_focus[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); y_offset += h*2; } // pre-render menu text components for(index = 0; index < __MENU_COMPONENT_LAST; index++) { s_pre_tex_components[index] = glutils_render_text_to_texture( font_20, s_str_components[index], text_color ); glutils_get_texture_dim(s_pre_tex_components[index], &w, &h); switch(index) { case COMPONENT_COMPUTER: case COMPONENT_HUMAN: y_offset = s_options_y[LABEL_SECOND_PLAYER]; break; case COMPONENT_ACTIVE: y_offset = 0; break; case COMPONENT_PLUS: case COMPONENT_MINUS: y_offset = s_options_y[LABEL_SOUND_VOLUME]; break; } s_list_components[index] = glutils_create_list( s_pre_tex_components[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); // same for focused components (only the color changes) s_pre_tex_components_focus[index] = glutils_render_text_to_texture( font_20, s_str_components[index], text_focus_color ); s_list_components_focus[index] = glutils_create_list( s_pre_tex_components_focus[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); } // pre-render level set names glutils_get_texture_dim(s_pre_tex_labels[LABEL_LEVEL_SET], &w, &h); y_offset = s_options_y[LABEL_LEVEL_SET]; for(index = 0; index < s_sets_names_length; index++) { s_pre_tex_set_names[index] = glutils_render_text_to_texture( font_20, s_sets_names[index], text_color ); glutils_get_texture_dim(s_pre_tex_set_names[index], &w, &h); s_list_set_names[index] = glutils_create_list( s_pre_tex_set_names[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); s_pre_tex_set_names_focus[index] = glutils_render_text_to_texture( font_20, s_sets_names[index], text_focus_color ); s_list_set_names_focus[index] = glutils_create_list( s_pre_tex_set_names_focus[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); } // pre-render theme names glutils_get_texture_dim(s_pre_tex_labels[LABEL_THEME], &w, &h); y_offset = s_options_y[LABEL_THEME]; for(index = 0; index < s_themes_names_length; index++) { s_pre_tex_theme_names[index] = glutils_render_text_to_texture( font_20, s_themes_names[index], text_color ); glutils_get_texture_dim(s_pre_tex_theme_names[index], &w, &h); s_list_theme_names[index] = glutils_create_list( s_pre_tex_theme_names[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); s_pre_tex_theme_names_focus[index] = glutils_render_text_to_texture( font_20, s_themes_names[index], text_focus_color ); s_list_theme_names_focus[index] = glutils_create_list( s_pre_tex_theme_names_focus[index], w, h, WINDOW_WIDTH / 2 - w / 2, y_offset ); } // pre-render numbers const char *numbers[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; for(index = 0; index < 10; index++) { s_pre_tex_numbers[index] = glutils_render_text_to_texture( font_20, numbers[index], text_color ); glutils_get_texture_dim(s_pre_tex_numbers[index], &w, &h); s_list_numbers[index] = glutils_create_list( s_pre_tex_numbers[index], w, h, 0, 0 ); s_pre_tex_numbers_focus[index] = glutils_render_text_to_texture( font_20, numbers[index], text_focus_color ); s_list_numbers_focus[index] = glutils_create_list( s_pre_tex_numbers_focus[index], w, h, 0, 0 ); } TTF_CloseFont(font_28); TTF_CloseFont(font_20); s_preloaded = true; atexit(menu_free); }
void StringSDL::init(const std::string &font_name, int size) { _font = TTF_OpenFont(font_name.c_str(), size); if (_font == NULL) _TTF_Error("TTF_OpenFont", false); }
int main(int argc, char *argv[]){ Uint32 renderstart = 0; Uint32 stepstart = 0; Uint32 delay = 250000; bool paused = false, baractive = true; Grid grid(ROWS, COLS, 0.15); initialise("Game of Life"); font16 = TTF_OpenFont("Prototype.ttf", 16); StatusBar bar(screen->w, 20, font16, &grid); for(int i=0; i<50000; ++i){ renderstart = SDL_GetTicks(); while(SDL_PollEvent(&event)){ grid.inputHandler(event); if(event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_PERIOD){ delay += 50000; } if(event.key.keysym.sym == SDLK_COMMA){ if(delay >= 50000) delay -= 50000; } /* if(event.key.keysym.sym == SDLK_UP){ grid.decPortal_y(); } if(event.key.keysym.sym == SDLK_DOWN){ grid.incPortal_y(); } if(event.key.keysym.sym == SDLK_LEFT){ grid.decPortal_x(); } if(event.key.keysym.sym == SDLK_RIGHT){ grid.incPortal_x(); } */ if(event.key.keysym.sym == SDLK_p){ paused = !paused; } if(event.key.keysym.sym == SDLK_b){ baractive = !baractive; } if(event.key.keysym.sym == SDLK_r){ grid.reset(0.15); } if(event.key.keysym.sym == SDLK_z){ grid.zoomIn(); } if(event.key.keysym.sym == SDLK_x){ grid.zoomOut(); } if(event.key.keysym.sym == SDLK_l){ grid.zoomReset(); } if(event.key.keysym.sym == SDLK_q){ exit(0); } if(event.key.keysym.sym == SDLK_h){ HelpPanel *hp = new HelpPanel(480, 400, font16, "Help Panel"); bool wasPaused = paused; if(!wasPaused) paused = true; hp->draw(screen); while(SDL_WaitEvent(&event)){ if(event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_SPACE) break; } } delete hp; if(!wasPaused) paused = false; } if(event.key.keysym.sym == SDLK_a){ AboutPanel *ap = new AboutPanel(480, 400, font16, "Game of Life"); bool wasPaused = paused; if(!wasPaused) paused = true; ap->draw(screen); while(SDL_WaitEvent(&event)){ if(event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_SPACE) break; } } delete ap; if(!wasPaused) paused = false; } if(event.key.keysym.sym == SDLK_w){ //grid.pstep(4); grid.writeBMP("gol-01.bmp"); } if(event.key.keysym.sym == SDLK_f){ //grid.readBMP("gol-01.bmp"); //grid.readBMP("glider.bmp"); //grid.readBMP("rabbits.bmp"); grid.readBMP("gun.bmp"); } } } if(!paused && ((SDL_GetTicks() - stepstart) > delay/1000)) { stepstart = SDL_GetTicks(); //grid.step(); grid.pstep(4); } // SDL_LockSurface(screen); grid.update(); grid.draw(screen); if(baractive) bar.paint(screen, paused, delay); // SDL_UnlockSurface(screen); SDL_Flip(screen); // fprintf(stderr, "Delay: %d\n", delay); if( (SDL_GetTicks() - renderstart) < 1000/FPS ){ // fprintf(stderr, "[%d] In render delay.\n", i); // fprintf(stderr, "---- Margin %d vs. %d ---- In delay for %d", \ (SDL_GetTicks() - renderstart) , (1000/FPS - delay/1000), \ (1000/FPS - (SDL_GetTicks() - renderstart) + delay/1000 )); SDL_Delay(1000/FPS - (SDL_GetTicks() - renderstart) ); } }