int main(int argc, char* argv[]) { unsigned int width = 0; unsigned int height = 0; if(argc > 1) { for(int i = 1; i < argc; i++) { if(strcmp(argv[i], "-w") == 0) { width = atoi(argv[i + 1]); i++; //skip the argument value }else if(strcmp(argv[i], "-h") == 0) { height = atoi(argv[i + 1]); i++; //skip the argument value }else if(strcmp(argv[i], "--gamelist-only") == 0) { Settings::getInstance()->setBool("PARSEGAMELISTONLY", true); }else if(strcmp(argv[i], "--ignore-gamelist") == 0) { Settings::getInstance()->setBool("IGNOREGAMELIST", true); }else if(strcmp(argv[i], "--draw-framerate") == 0) { Settings::getInstance()->setBool("DRAWFRAMERATE", true); }else if(strcmp(argv[i], "--no-exit") == 0) { Settings::getInstance()->setBool("DONTSHOWEXIT", true); }else if(strcmp(argv[i], "--debug") == 0) { Settings::getInstance()->setBool("DEBUG", true); Log::setReportingLevel(LogDebug); }else if(strcmp(argv[i], "--dimtime") == 0) { Settings::getInstance()->setInt("DIMTIME", atoi(argv[i + 1]) * 1000); i++; //skip the argument value }else if(strcmp(argv[i], "--windowed") == 0) { Settings::getInstance()->setBool("WINDOWED", true); }else if(strcmp(argv[i], "--help") == 0) { std::cout << "EmulationStation, a graphical front-end for ROM browsing.\n"; std::cout << "Command line arguments:\n"; std::cout << "-w [width in pixels] set screen width\n"; std::cout << "-h [height in pixels] set screen height\n"; std::cout << "--gamelist-only skip automatic game detection, only read from gamelist.xml\n"; std::cout << "--ignore-gamelist ignore the gamelist (useful for troubleshooting)\n"; std::cout << "--draw-framerate display the framerate\n"; std::cout << "--no-exit don't show the exit option in the menu\n"; std::cout << "--debug even more logging\n"; std::cout << "--dimtime [seconds] time to wait before dimming the screen (default 30, use 0 for never)\n"; #ifdef USE_OPENGL_DESKTOP std::cout << "--windowed not fullscreen\n"; #endif std::cout << "--help summon a sentient, angry tuba\n\n"; std::cout << "More information available in README.md.\n"; return 0; } } } #ifdef _RPI_ bcm_host_init(); #endif bool running = true; //make sure the config directory exists std::string home = getHomePath(); std::string configDir = home + "/.emulationstation"; if(!fs::exists(configDir)) { std::cout << "Creating config directory \"" << configDir << "\"\n"; fs::create_directory(configDir); } //start the logger Log::open(); LOG(LogInfo) << "EmulationStation - " << PROGRAM_VERSION_STRING; //the renderer also takes care of setting up SDL for input and sound bool renderInit = Renderer::init(width, height); if(!renderInit) { std::cerr << "Error initializing renderer!\n"; Log::close(); return 1; } Window window; //don't call Window.init() because we manually pass the resolution to Renderer::init window.getInputManager()->init(); //try loading the system config file if(!fs::exists(SystemData::getConfigPath())) //if it doesn't exist, create the example and quit { std::cerr << "A system config file in " << SystemData::getConfigPath() << " was not found. An example will be created.\n"; SystemData::writeExampleConfig(); std::cerr << "Set it up, then re-run EmulationStation.\n"; running = false; }else{ SystemData::loadConfig(); if(SystemData::sSystemVector.size() == 0) //if it exists but was empty, notify the user and quit { std::cerr << "A system config file in " << SystemData::getConfigPath() << " was found, but contained no systems.\n"; std::cerr << "Does at least one system have a game present?\n"; running = false; }else{ //choose which GUI to open depending on Input configuration if(fs::exists(InputManager::getConfigPath())) { //an input config already exists - we have input, proceed to the gamelist as usual. GuiGameList::create(&window); }else{ window.pushGui(new GuiDetectDevice(&window)); } } } bool sleeping = false; unsigned int timeSinceLastEvent = 0; int lastTime = 0; while(running) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_JOYHATMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_KEYDOWN: case SDL_KEYUP: case SDL_JOYAXISMOTION: if(window.getInputManager()->parseEvent(event)) { sleeping = false; timeSinceLastEvent = 0; } break; case InputManager::SDL_USEREVENT_POLLDEVICES: //try to poll input devices, but do not necessarily wake up... window.getInputManager()->parseEvent(event); break; case SDL_QUIT: running = false; break; } } if(sleeping) { lastTime = SDL_GetTicks(); sleep(1); //this doesn't need to accurate continue; } int curTime = SDL_GetTicks(); int deltaTime = curTime - lastTime; lastTime = curTime; window.update(deltaTime); Renderer::swapBuffers(); //swap here so we can read the last screen state during updates (see ImageComponent::copyScreen()) window.render(); if(Settings::getInstance()->getBool("DRAWFRAMERATE")) { static int timeElapsed = 0; static int nrOfFrames = 0; static std::string fpsString; nrOfFrames++; timeElapsed += deltaTime; //wait until half a second has passed to recalculate fps if (timeElapsed >= 500) { std::stringstream ss; ss << std::fixed << std::setprecision(1) << (1000.0f * (float)nrOfFrames / (float)timeElapsed) << "fps, "; ss << std::fixed << std::setprecision(2) << ((float)timeElapsed / (float)nrOfFrames) << "ms"; fpsString = ss.str(); nrOfFrames = 0; timeElapsed = 0; } Renderer::drawText(fpsString, 50, 50, 0x00FF00FF, Renderer::getDefaultFont(Renderer::MEDIUM)); } //sleep if we're past our threshold //sleeping entails setting a flag to start skipping frames //and initially drawing a black semi-transparent rect to dim the screen timeSinceLastEvent += deltaTime; if(timeSinceLastEvent >= (unsigned int)Settings::getInstance()->getInt("DIMTIME") && Settings::getInstance()->getInt("DIMTIME") != 0) { sleeping = true; timeSinceLastEvent = 0; Renderer::drawRect(0, 0, Renderer::getScreenWidth(), Renderer::getScreenHeight(), 0x000000A0); Renderer::swapBuffers(); } Log::flush(); } Renderer::deinit(); SystemData::deleteSystems(); std::cout << "EmulationStation cleanly shutting down...\n"; Log::close(); #ifdef _RPI_ bcm_host_deinit(); #endif return 0; }
void play_controller::init(CVideo& video){ util::scoped_resource<loadscreen::global_loadscreen_manager*, util::delete_item> scoped_loadscreen_manager; loadscreen::global_loadscreen_manager* loadscreen_manager = loadscreen::global_loadscreen_manager::get(); if (!loadscreen_manager) { scoped_loadscreen_manager.assign(new loadscreen::global_loadscreen_manager(video)); loadscreen_manager = scoped_loadscreen_manager.get(); } loadscreen::start_stage("load level"); // If the recorder has no event, adds an "game start" event // to the recorder, whose only goal is to initialize the RNG if(recorder.empty()) { recorder.add_start(); } else { recorder.pre_replay(); } recorder.set_skip(false); bool snapshot = level_["snapshot"].to_bool(); if (level_["modify_placing"].to_bool()) { LOG_NG << "modifying placing...\n"; place_sides_in_preferred_locations(); } BOOST_FOREACH(const config &t, level_.child_range("time_area")) { tod_manager_.add_time_area(t); } LOG_NG << "initialized teams... " << (SDL_GetTicks() - ticks_) << "\n"; loadscreen::start_stage("init teams"); resources::teams->resize(level_.child_count("side")); // This *needs* to be created before the show_intro and show_map_scene // as that functions use the manager state_of_game // Has to be done before registering any events! events_manager_.reset(new game_events::manager(level_)); std::set<std::string> seen_save_ids; std::vector<team_builder_ptr> team_builders; int team_num = 0; BOOST_FOREACH(const config &side, level_.child_range("side")) { std::string save_id = get_unique_saveid(side, seen_save_ids); seen_save_ids.insert(save_id); if (first_human_team_ == -1) { const std::string &controller = side["controller"]; if (controller == "human" && side["id"] == preferences::login()) { first_human_team_ = team_num; } else if (controller == "human") { first_human_team_ = team_num; } } team_builder_ptr tb_ptr = gamedata_.create_team_builder(side, save_id, teams_, level_, map_, units_, snapshot, gamestate_.replay_start()); ++team_num; gamedata_.build_team_stage_one(tb_ptr); team_builders.push_back(tb_ptr); } BOOST_FOREACH(team_builder_ptr tb_ptr, team_builders) { gamedata_.build_team_stage_two(tb_ptr); }
void reguleFPS(Timer *timer) { timer->ellapsedTime = SDL_GetTicks() - timer->lastTime; if (timer->ellapsedTime < FPS) SDL_Delay(FPS-timer->ellapsedTime); }
// This needs to be visible from outside pp_uint32 PPGetTickCount() { return SDL_GetTicks(); }
void RenderBackend::startFrame() { if (m_isframelimit) { m_frame_start = SDL_GetTicks(); } }
unsigned int Engine::TimeSDL2Adapter::GetTime() { return SDL_GetTicks(); }
void GLWindow::MainLoop() { bool loop = true; while (loop) { SDL_Event event; while (SDL_PollEvent(&event)) { for (Helpers::EventHandling::BaseEventHanler *handler : this->eventHandlers) { handler->HandleEvent(event); } if (event.type == SDL_QUIT) { loop = false; } if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: loop = false; break; default: break; } } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); unsigned long timeSpan = SDL_GetTicks(); for (BaseRenderHandler *handler : this->renderHandlers) { handler->BeforeFrameRender(timeSpan - this->prevFrameStartedTime, timeSpan - this->prevFrameFinishedTime); } for (RenderObjectShaderProgram *prog : this->programs) { prog->RenderObjects(timeSpan); } for (BaseRenderHandler *handler : this->renderHandlers) { handler->OnFrameRendering(); } fpsTimer += timeSpan - this->prevFrameStartedTime; ++fpcChechCount; if (fpsTimer > FPS_RENEW_CYCLE) { this->fps = (float)fpcChechCount / ((float)fpsTimer / FPS_RENEW_CYCLE); fpsTimer = 0; fpcChechCount = 0; } this->RenderText(5, 5, "FPS: " + std::to_string(fps)); this->prevFrameStartedTime = timeSpan; unsigned long prevFinishTmp = this->prevFrameFinishedTime; this->prevFrameFinishedTime = SDL_GetTicks(); for (BaseRenderHandler *handler : this->renderHandlers) { handler->AfterFrameRender(this->prevFrameFinishedTime - timeSpan, this->prevFrameFinishedTime - prevFinishTmp); } SDL_GL_SwapWindow(this->mainWindow); } }
/* Get pl_name from user; other strings are text displayed by dialog: */ void NameEntry(char* pl_name, const char* s1, const char* s2, const char* s3) { char UTF8_buf[HIGH_SCORE_NAME_LENGTH * 3] = {'\0'}; SDL_Rect loc; SDL_Rect redraw_rect; int redraw = 0; int first_draw = 1; int finished = 0; Uint32 frame = 0; Uint32 start = 0; wchar_t wchar_buf[HIGH_SCORE_NAME_LENGTH + 1] = {'\0'}; const int NAME_FONT_SIZE = 32; const int BG_Y = 100; const int BG_WIDTH = 400; const int BG_HEIGHT = 200; if (!pl_name) return; /* We need to get Unicode vals from SDL keysyms */ SDL_EnableUNICODE(SDL_ENABLE); DEBUGMSG(debug_highscore, "Enter NameEntry()\n" ); DrawTitleScreen(); /* Red "Stop" circle in upper right corner to go back to main menu: */ if (stop_button) { SDL_BlitSurface(stop_button, NULL, screen, &stop_rect); } /* Draw translucent background for text: */ { SDL_Rect bg_rect; bg_rect.x = (screen->w)/2 - BG_WIDTH/2; bg_rect.y = BG_Y; bg_rect.w = BG_WIDTH; bg_rect.h = BG_HEIGHT; T4K_DrawButton(&bg_rect, 15, REG_RGBA); bg_rect.x += 10; bg_rect.y += 10; bg_rect.w -= 20; bg_rect.h = 60; T4K_DrawButton(&bg_rect, 10, SEL_RGBA); } /* Draw headings: */ { SDL_Surface* surf = T4K_BlackOutline(_(s1), DEFAULT_MENU_FONT_SIZE, &white); if (surf) { loc.x = (screen->w/2) - (surf->w/2); loc.y = 110; SDL_BlitSurface(surf, NULL, screen, &loc); SDL_FreeSurface(surf); } surf = T4K_BlackOutline(_(s2), DEFAULT_MENU_FONT_SIZE, &white); if (surf) { loc.x = (screen->w/2) - (surf->w/2); loc.y = 140; SDL_BlitSurface(surf, NULL, screen, &loc); SDL_FreeSurface(surf); } surf = T4K_BlackOutline(_(s3), DEFAULT_MENU_FONT_SIZE, &white); if (surf) { loc.x = (screen->w/2) - (surf->w/2); loc.y = 170; SDL_BlitSurface(surf, NULL, screen, &loc); SDL_FreeSurface(surf); } } if (_(s3) != NULL) T4K_Tts_say(DEFAULT_VALUE,DEFAULT_VALUE,APPEND,"%s %s %s",_(s1),_(s2),_(s3)); else if(_(s2) != NULL) T4K_Tts_say(DEFAULT_VALUE,DEFAULT_VALUE,APPEND,"%s %s",_(s1),_(s2)); else T4K_Tts_say(DEFAULT_VALUE,DEFAULT_VALUE,APPEND,"%s",_(s1)); /* and update: */ SDL_UpdateRect(screen, 0, 0, 0, 0); while (!finished) { start = SDL_GetTicks(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: { cleanup(); } case SDL_MOUSEBUTTONDOWN: /* "Stop" button - go to main menu: */ { if (T4K_inRect(stop_rect, event.button.x, event.button.y )) { finished = 1; playsound(SND_TOCK); break; } } case SDL_KEYDOWN: { DEBUGMSG(debug_highscore, "Before keypress, string is %S\tlength = %d\n", wchar_buf, (int)wcslen(wchar_buf)); switch (event.key.keysym.sym) { case SDLK_ESCAPE: case SDLK_RETURN: case SDLK_KP_ENTER: { finished = 1; playsound(SND_TOCK); break; } case SDLK_BACKSPACE: { if (wcslen(wchar_buf) > 0) wchar_buf[(int)wcslen(wchar_buf) - 1] = '\0'; redraw = 1; break; } /* For any other keys, if the key has a Unicode value, */ /* we add it to our string: */ default: { if ((event.key.keysym.unicode > 0) && (wcslen(wchar_buf) < HIGH_SCORE_NAME_LENGTH)) { wchar_buf[(int)wcslen(wchar_buf)] = event.key.keysym.unicode; redraw = 1; T4K_Tts_say(DEFAULT_VALUE,DEFAULT_VALUE,INTERRUPT,"%C",event.key.keysym.unicode); } } } /* end 'switch (event.key.keysym.sym)' */ DEBUGMSG(debug_highscore, "After keypress, string is %S\tlength = %d\n", wchar_buf, (int)wcslen(wchar_buf)); /* Now draw name, if needed: */ if (redraw) { SDL_Surface* s = NULL; redraw = 0; /* Convert text to UTF-8 so T4K_BlackOutline() can handle it: */ // wcstombs((char*) UTF8_buf, wchar_buf, HIGH_SCORE_NAME_LENGTH * 3); T4K_ConvertToUTF8(wchar_buf, UTF8_buf, HIGH_SCORE_NAME_LENGTH * 3); /* Redraw background and shading in area where we drew text last time: */ if (!first_draw) { SDL_BlitSurface(current_bkg(), &redraw_rect, screen, &redraw_rect); T4K_DrawButton(&redraw_rect, 0, REG_RGBA); SDL_UpdateRect(screen, redraw_rect.x, redraw_rect.y, redraw_rect.w, redraw_rect.h); } s = T4K_BlackOutline(UTF8_buf, NAME_FONT_SIZE, &yellow); if (s) { /* set up loc and blit: */ loc.x = (screen->w/2) - (s->w/2); loc.y = 230; SDL_BlitSurface(s, NULL, screen, &loc); /* Remember where we drew so we can update background next time through: */ /* (for some reason we need to update a wider area to get clean image) */ redraw_rect.x = loc.x - 20; redraw_rect.y = loc.y - 10; redraw_rect.h = s->h + 20; redraw_rect.w = s->w + 40; first_draw = 0; SDL_UpdateRect(screen, redraw_rect.x, redraw_rect.y, redraw_rect.w, redraw_rect.h); SDL_FreeSurface(s); s = NULL; } } } } } HandleTitleScreenAnimations(); /* Wait so we keep frame rate constant: */ while ((SDL_GetTicks() - start) < 33) { SDL_Delay(20); } frame++; } // End of while (!finished) loop /* Turn off SDL Unicode lookup (because has some overhead): */ SDL_EnableUNICODE(SDL_DISABLE); /* Now copy name into location pointed to by arg: */ strncpy(pl_name, UTF8_buf, HIGH_SCORE_NAME_LENGTH * 3); DEBUGMSG(debug_highscore, "Leaving NameEntry(), final string is: %s\n", pl_name); if (wcslen(wchar_buf) != 0) T4K_Tts_say(DEFAULT_VALUE,DEFAULT_VALUE,INTERRUPT,"%S.",wchar_buf); }
void Enemy::update() { m_position.setX(m_position.getX() + 1); m_position.setY(m_position.getY() + 1); m_currentFrame = int((SDL_GetTicks() / 100) % 6); }
void App::run() { is_running = true; //inicjalizacja SDL i utworzenie okan if(SDL_Init(SDL_INIT_VIDEO) == 0) { m_window = SDL_CreateWindow("TANKS", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, AppConfig::windows_rect.w, AppConfig::windows_rect.h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if(m_window == nullptr) return; if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) return; if(TTF_Init() == -1) return; srand(time(NULL)); //inicjowanie generatora pseudolosowego Engine& engine = Engine::getEngine(); engine.initModules(); engine.getRenderer()->loadTexture(m_window); engine.getRenderer()->loadFont(); m_app_state = new Menu; double FPS; Uint32 time1, time2, dt, fps_time = 0, fps_count = 0, delay = 15; time1 = SDL_GetTicks(); while(is_running) { time2 = SDL_GetTicks(); dt = time2 - time1; time1 = time2; if(m_app_state->finished()) { AppState* new_state = m_app_state->nextState(); delete m_app_state; m_app_state = new_state; } if(m_app_state == nullptr) break; eventProces(); m_app_state->update(dt); m_app_state->draw(); SDL_Delay(delay); //FPS fps_time += dt; fps_count++; if(fps_time > 200) { FPS = (double)fps_count / fps_time * 1000; if(FPS > 60) delay++; else if(delay > 0) delay--; fps_time = 0; fps_count = 0; } } engine.destroyModules(); } SDL_DestroyWindow(m_window); m_window = nullptr; TTF_Quit(); IMG_Quit(); SDL_Quit(); }
void init_text(int splash) { char fname[256]; SDL_Surface *tmp; if (!text_screen) { text_screen=SDL_CreateRGBSurface(prSDLScreen->flags,prSDLScreen->w,prSDLScreen->h,prSDLScreen->format->BitsPerPixel,prSDLScreen->format->Rmask,prSDLScreen->format->Gmask,prSDLScreen->format->Bmask,prSDLScreen->format->Amask); window_screen=SDL_CreateRGBSurface(prSDLScreen->flags,prSDLScreen->w,prSDLScreen->h,prSDLScreen->format->BitsPerPixel,prSDLScreen->format->Rmask,prSDLScreen->format->Gmask,prSDLScreen->format->Bmask,prSDLScreen->format->Amask); tmp=SDL_LoadBMP(MENU_FILE_TEXT); if (text_screen==NULL || tmp==NULL) exit(-1); text_image=SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp); if (text_image==NULL) exit(-2); SDL_SetColorKey(text_image,(SDL_SRCCOLORKEY | SDL_RLEACCEL),SDL_MapRGB(text_image -> format, 0, 0, 0)); tmp=SDL_LoadBMP(MENU_FILE_BACKGROUND); if (tmp==NULL) exit(-3); text_background=SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp); if (text_background==NULL) exit(-3); tmp=SDL_LoadBMP(MENU_FILE_WINDOW); if (tmp==NULL) exit(-4); SDL_Rect dest; dest.w=32; dest.h=24; for (int y=0;y<10;y++) { //text_window_background dest.y=24*y; for(int x=0;x<10;x++) { dest.x=32*x; SDL_BlitSurface(tmp,NULL,window_screen,&dest); } } SDL_FreeSurface(tmp); } if (splash) { SDL_Surface *sur; SDL_Rect r; int i,j; obten_colores(); if (skipintro) goto skipintro; tmp=SDL_LoadBMP(MENU_FILE_SPLASH); if (tmp==NULL) exit(-6); sur = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp); r.x=(text_screen->w - sur->w)/2; r.y=(text_screen->h - sur->h)/2; r.h=sur->w; r.w=sur->h; SDL_FillRect(text_screen,NULL,0xFFFFFFFF); for (i=128;i>-8;i-=8) { SDL_Delay(50); SDL_FillRect(text_screen,NULL,0xFFFFFFFF); SDL_BlitSurface(sur,NULL,text_screen,&r); fade16(text_screen,i); text_flip(); } SDL_Delay(3000); for(i=0;i<128;i+=16) { SDL_Delay(50); SDL_FillRect(text_screen,NULL,0xFFFFFFFF); SDL_BlitSurface(sur,NULL,text_screen,&r); fade16(text_screen,i); text_flip(); } for(i=128;i>-8;i-=8) { SDL_Delay(50); text_draw_background(); fade16(text_screen,i); text_flip(); } SDL_FreeSurface(sur); } else { SDL_FillRect(text_screen,NULL,0xFFFFFFFF); text_flip(); uae4all_resume_music(); } skipintro: menu_msg_time=SDL_GetTicks(); }
void Gource::interactUsers() { // update quad tree Bounds2D quadtreebounds = user_bounds; quadtreebounds.min -= vec2f(1.0f, 1.0f); quadtreebounds.max += vec2f(1.0f, 1.0f); update_user_tree_time = SDL_GetTicks(); if(userTree != 0) delete userTree; int max_depth = 1; //dont use deep quad tree initially when all the nodes are in one place if(dir_bounds.area() > 10000.0) { max_depth = gGourceMaxQuadTreeDepth; } userTree = new QuadTree(quadtreebounds, max_depth, 1); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { RUser* user = it->second; user->updateQuadItemBounds(); userTree->addItem(user); } //move users - interact with other users and files for(std::map<std::string,RUser*>::iterator ait = users.begin(); ait!=users.end(); ait++) { RUser* a = ait->second; std::set<int> seen; std::set<int>::iterator seentest; std::vector<QuadItem*> inbounds; int found = userTree->getItemsInBounds(inbounds, a->quadItemBounds); for(std::vector<QuadItem*>::iterator it = inbounds.begin(); it != inbounds.end(); it++) { RUser* b = (RUser*) (*it); if(b==a) continue; if((seentest = seen.find(b->getTagID())) != seen.end()) { continue; } seen.insert(b->getTagID()); a->applyForceUser(b); gGourceUserInnerLoops++; } a->applyForceToActions(); } update_user_tree_time = SDL_GetTicks() - update_user_tree_time; }
void Gource::draw(float t, float dt) { display.mode2D(); drawBackground(dt); if(draw_loading) { loadingScreen(); draw_loading = false; return; } Frustum frustum(camera); trace_time = SDL_GetTicks(); mousetrace(frustum,dt); trace_time = SDL_GetTicks() - trace_time; glMatrixMode(GL_PROJECTION); glLoadIdentity(); camera.focus(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //draw tree drawTree(frustum, dt); glColor4f(1.0, 1.0, 0.0, 1.0); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { trace_debug ? it->second->drawSimple(dt) : it->second->draw(dt); } glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); //draw bloom drawBloom(frustum, dt); root->drawNames(font,frustum); if(!(gGourceSettings.hide_usernames || gGourceSettings.hide_users)) { for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { it->second->drawName(); } } //draw selected item names again so they are over the top if(selectedUser !=0) selectedUser->drawName(); if(selectedFile !=0) { vec2f dirpos = selectedFile->getDir()->getPos(); glPushMatrix(); glTranslatef(dirpos.x, dirpos.y, 0.0); selectedFile->drawName(); glPopMatrix(); } if(debug) { glDisable(GL_TEXTURE_2D); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); track_users ? user_bounds.draw() : dir_bounds.draw(); } if(gGourceQuadTreeDebug) { glDisable(GL_TEXTURE_2D); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glLineWidth(1.0); dirNodeTree->outline(); glColor4f(0.0f, 1.0f, 1.0f, 1.0f); userTree->outline(); } glColor4f(1.0f, 1.0f, 1.0f, 1.0f); display.mode2D(); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); vec3f campos = camera.getPos(); if(logotex!=0) { glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glColor4f(1.0, 1.0, 1.0, 1.0); glBindTexture(GL_TEXTURE_2D, logotex->textureid); vec2f logopos = vec2f(display.width, display.height) - vec2f(logotex->w, logotex->h) - gGourceSettings.logo_offset; glPushMatrix(); glTranslatef(logopos.x, logopos.y, 0.0); glBegin(GL_QUADS); glTexCoord2f(0.0f,0.0f); glVertex2i(0, 0); glTexCoord2f(1.0f,0.0f); glVertex2i(logotex->w, 0); glTexCoord2f(1.0f,1.0f); glVertex2i(logotex->w, logotex->h); glTexCoord2f(0.0f,1.0f); glVertex2i(0, logotex->h); glEnd(); glPopMatrix(); } if(splash>0.0f) { int logowidth = fontlarge.getWidth("Gource"); int logoheight = 100; int cwidth = font.getWidth("Software Version Control Visualization"); int awidth = font.getWidth("(C) 2009 Andrew Caudwell"); vec2f corner(display.width/2 - logowidth/2 - 30.0f, display.height/2 - 40); glDisable(GL_TEXTURE_2D); glColor4f(0.0f, 0.5f, 1.0f, splash * 0.015f); glBegin(GL_QUADS); glVertex2f(0.0f, corner.y); glVertex2f(0.0f, corner.y + logoheight); glVertex2f(display.width, corner.y + logoheight); glVertex2f(display.width, corner.y); glEnd(); glEnable(GL_TEXTURE_2D); glColor4f(1.0,1.0,1.0,1.0); fontlarge.draw(display.width/2 - logowidth/2,display.height/2 - 30, "Gource"); font.draw(display.width/2 - cwidth/2,display.height/2 + 10, "Software Version Control Visualization"); font.draw(display.width/2 - awidth/2,display.height/2 + 30, "(C) 2009 Andrew Caudwell"); } // text using the specified font goes here glColor4f(gGourceSettings.font_colour.x, gGourceSettings.font_colour.y, gGourceSettings.font_colour.z, 1.0f); if(!gGourceSettings.hide_date) { fontmedium.draw(display.width/2 - date_x_offset, 20, displaydate); } if(gGourceSettings.title.size()>0) { fontmedium.alignTop(false); fontmedium.draw(10, display.height - 10, gGourceSettings.title); fontmedium.alignTop(true); } if(message_timer>0.0f) { fontmedium.draw(1, 3, message); } // end text glColor4f(1.0f, 1.0f, 1.0f, 1.0f); if(debug) { font.print(1,20, "FPS: %.2f", fps); font.print(1,40,"Days Per Second: %.2f", gGourceSettings.days_per_second); font.print(1,60,"Time Scale: %.2f", time_scale); font.print(1,80,"Users: %d", users.size()); font.print(1,100,"Files: %d", files.size()); font.print(1,120,"Dirs: %d", gGourceDirMap.size()); font.print(1,140,"Log Position: %.4f", commitlog->getPercent()); font.print(1,160,"Camera: (%.2f, %.2f, %.2f)", campos.x, campos.y, campos.z); font.print(1,180,"Gravity: %.2f", gGourceForceGravity); font.print(1,200,"Update Tree: %u ms", update_dir_tree_time); font.print(1,220,"Draw Tree: %u ms", draw_tree_time); font.print(1,240,"Mouse Trace: %u ms", trace_time); font.print(1,260,"Logic Time: %u ms", logic_time); font.print(1,280,"Draw Time: %u ms", SDL_GetTicks() - draw_time); font.print(1,300,"File Inner Loops: %d", gGourceFileInnerLoops); font.print(1,320,"User Inner Loops: %d", gGourceUserInnerLoops); font.print(1,340,"Dir Inner Loops: %d (QTree items = %d, nodes = %d)", gGourceDirNodeInnerLoops, dirNodeTree->item_count, dirNodeTree->node_count); if(selectedUser != 0) { } if(selectedFile != 0) { font.print(1,360,"%s: %d files (%d visible)", selectedFile->getDir()->getPath().c_str(), selectedFile->getDir()->fileCount(), selectedFile->getDir()->visibleFileCount()); } } glDisable(GL_TEXTURE_2D); if(canSeek()) slider.draw(dt); mousemoved=false; mouseclicked=false; }
void Gource::drawTree(Frustum& frustum, float dt) { draw_tree_time = SDL_GetTicks(); root->calcEdges(); //switch to 2d glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, display.width, display.height, 0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(!gGourceSettings.hide_tree) { glBindTexture(GL_TEXTURE_2D, beamtex->textureid); root->drawEdgeShadows(dt); root->drawEdges(dt); } //switch back glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //draw shadows if(!gGourceSettings.hide_users) { for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { it->second->drawShadow(dt); } } if(!gGourceSettings.hide_files) { root->drawShadows(frustum, dt); } drawActions(dt); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(!trace_debug) { if(!gGourceSettings.hide_files) { root->drawFiles(frustum,dt); } } else { root->drawSimple(frustum,dt); } draw_tree_time = SDL_GetTicks() - draw_tree_time; }
void Watch::reset() { elapsed = lastUpdate = 0; lastRun = SDL_GetTicks(); }
/** * @brief Displays the introduction sequence. * * @brief text Path of text file to use. * @brief mus Type of music to use (run through music.lua). * @return 0 on success. */ int intro_display( const char *text, const char *mus ) { double offset; /* distance from bottom of the top line. */ double line_height; /* # pixels per line. */ int lines_per_screen; /* max appearing lines on the screen. */ scroll_buf_t *sb_arr; /* array of lines to render. */ scroll_buf_t *sb_list; /* list " " " " */ double vel = 16.; /* velocity: speed of text. */ int stop = 0; /* stop the intro. */ unsigned int tcur, tlast; /* timers. */ double delta; /* time diff from last render to this one. */ int line_index = 0; /* index into the big list of intro lines. */ intro_img_t side_image; /* image to go along with the text. */ intro_img_t transition; /* image for transitioning. */ /* Load the introduction. */ if (intro_load(text) < 0) return -1; /* Change music to intro music. */ if (mus != NULL) music_choose(mus); /* We need to clear key repeat to avoid infinite loops. */ toolkit_clearKey(); /* Enable keyrepeat just for the intro. */ #if !SDL_VERSION_ATLEAST(2,0,0) SDL_EnableKeyRepeat( conf.repeat_delay, conf.repeat_freq ); #endif /* !SDL_VERSION_ATLEAST(2,0,0) */ /* Do a few calculations to figure out how many lines can be present on the screen at any given time. */ line_height = (double)intro_font.h * 1.3; lines_per_screen = (int)(SCREEN_H / line_height + 1.5); /* round up + 1 */ sb_arr = (scroll_buf_t*)malloc( sizeof(scroll_buf_t) * lines_per_screen ); /* Force the first line to be loaded immediately. */ offset = line_height; /* Create a cycle of lines. */ sb_list = arrange_scroll_buf( sb_arr, lines_per_screen ); /* Unset the side image. */ initialize_image( &side_image ); initialize_image( &transition ); tlast = SDL_GetTicks(); while (!stop) { tcur = SDL_GetTicks(); delta = (double)(tcur - tlast) / 1000.; tlast = tcur; /* Increment position. */ offset += vel * delta; while (! (offset < line_height)) { /* One line has scrolled off, and another one on. */ if (line_index < intro_nlines) { switch (intro_lines[line_index][0]) { case 't': /* plain ol' text. */ sb_list->text = &intro_lines[line_index][1]; offset -= line_height; sb_list = sb_list->next; break; case 'i': /* fade in image. */ intro_fade_image_in( &side_image, &transition, &intro_lines[line_index][1] ); break; case 'o': /* fade out image. */ if (NULL == side_image.tex) { WARN(_("Tried to fade out without an image.") ); break; } side_image.fade_rate = -0.1; side_image.c.a = 0.99; break; default: /* unknown. */ break; } ++line_index; } else { sb_list->text = NULL; offset -= line_height; sb_list = sb_list->next; } } /* while (offset > line_height) */ /* Fade the side image. */ if (side_image.tex != NULL && side_image.c.a < 1.0) { side_image.c.a += delta * vel * side_image.fade_rate; if (transition.tex != NULL && transition.fade_rate > 0.0) transition.c.a += delta * vel * transition.fade_rate; if (side_image.c.a > 1.0) { /* Faded in... */ side_image.c.a = 1.0; side_image.fade_rate = 0.0; } else if (side_image.c.a < 0.0) { /* Faded out... */ gl_freeTexture( side_image.tex ); if (transition.tex != NULL) { side_image.tex = transition.tex; side_image.c.a = transition.c.a; side_image.y = transition.y; side_image.fade_rate = 0.1; transition.tex = NULL; transition.c.a = 1.0; } else { side_image.c.a = 1.0; side_image.tex = NULL; side_image.fade_rate = 0.0; } } } /* Clear stuff. */ glClear(GL_COLOR_BUFFER_BIT); /* Only thing we actually care about updating is music. */ music_update( 0. ); /* Draw text. */ stop = intro_draw_text( sb_list, offset, line_height ); if (NULL != side_image.tex) /* Draw the image next to the text. */ gl_blitScale( side_image.tex, side_image.x, side_image.y, side_image.tex->w, side_image.tex->h, &side_image.c ); if (NULL != transition.tex && transition.c.a > 0.0) /* Draw the image in transition. */ gl_blitScale( transition.tex, transition.x, transition.y, transition.tex->w, transition.tex->h, &transition.c ); /* Display stuff. */ #if SDL_VERSION_ATLEAST(2,0,0) SDL_GL_SwapWindow( gl_screen.window ); #else /* SDL_VERSION_ATLEAST(2,0,0) */ SDL_GL_SwapBuffers(); #endif /* SDL_VERSION_ATLEAST(2,0,0) */ SDL_Delay(10); /* No need to burn CPU. */ /* Handle user events. */ intro_event_handler( &stop, &offset, &vel ); } /* while (!stop) */ /* free malloc'd memory. */ free( sb_arr ); if (NULL != side_image.tex) gl_freeTexture( side_image.tex ); if (NULL != transition.tex) gl_freeTexture( transition.tex ); /* Disable intro's key repeat. */ #if !SDL_VERSION_ATLEAST(2,0,0) SDL_EnableKeyRepeat( 0, 0 ); #endif /* !SDL_VERSION_ATLEAST(2,0,0) */ /* Stop music, normal music will start shortly after. */ music_stop(); /* Clean up after the introduction. */ intro_cleanup(); return 0; }
int main(int argc, char **argv) { Uint8 *RawMooseData; SDL_RWops *handle; SDL_Surface *screen; SDL_Surface *MooseFrame[MOOSEFRAMES_COUNT]; SDL_Overlay *overlay; SDL_Rect overlayrect; SDL_Event event; Uint32 lastftick; int paused = 0; int resized = 0; int i; int fps = 12; int fpsdelay; int overlay_format = SDL_YUY2_OVERLAY; int scale = 5; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); return 3; } while (argc > 1) { if (strcmp(argv[1], "-fps") == 0) { if (argv[2]) { fps = atoi(argv[2]); if (fps == 0) { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } if ((fps < 0) || (fps > 1000)) { fprintf(stderr, "The -fps option must be in range from 1 to 1000, default is 12.\n"); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } } else if (strcmp(argv[1], "-format") == 0) { if (argv[2]) { if (!strcmp(argv[2], "YV12")) overlay_format = SDL_YV12_OVERLAY; else if (!strcmp(argv[2], "IYUV")) overlay_format = SDL_IYUV_OVERLAY; else if (!strcmp(argv[2], "YUY2")) overlay_format = SDL_YUY2_OVERLAY; else if (!strcmp(argv[2], "UYVY")) overlay_format = SDL_UYVY_OVERLAY; else if (!strcmp(argv[2], "YVYU")) overlay_format = SDL_YVYU_OVERLAY; else { fprintf(stderr, "The -format option %s is not recognized, see help for info.\n", argv[2]); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -format option requires an argument, default is YUY2.\n"); quit(10); } } else if (strcmp(argv[1], "-scale") == 0) { if (argv[2]) { scale = atoi(argv[2]); if (scale == 0) { fprintf(stderr, "The -scale option requires an argument [from 1 to 50], default is 5.\n"); quit(10); } if ((scale < 0) || (scale > 50)) { fprintf(stderr, "The -scale option must be in range from 1 to 50, default is 5.\n"); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } } else if ((strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "-h") == 0)) { PrintUsage(argv[0]); quit(0); } else { fprintf(stderr, "Unrecognized option: %s.\n", argv[1]); quit(10); } break; } RawMooseData = (Uint8 *) malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT); if (RawMooseData == NULL) { fprintf(stderr, "Can't allocate memory for movie !\n"); free(RawMooseData); quit(1); } /* load the trojan moose images */ handle = SDL_RWFromFile("moose.dat", "rb"); if (handle == NULL) { fprintf(stderr, "Can't find the file moose.dat !\n"); free(RawMooseData); quit(2); } SDL_RWread(handle, RawMooseData, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT); SDL_RWclose(handle); /* Set video mode */ if ((screen = SDL_SetVideoMode(MOOSEPIC_W * scale, MOOSEPIC_H * scale, 0, SDL_RESIZABLE | SDL_SWSURFACE)) == NULL) { fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); free(RawMooseData); quit(4); } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL test overlay: running moose", "testoverlay2"); for (i = 0; i < MOOSEFRAMES_COUNT; i++) { MooseFrame[i] = SDL_CreateRGBSurfaceFrom(RawMooseData + i * MOOSEFRAME_SIZE, MOOSEPIC_W, MOOSEPIC_H, 8, MOOSEPIC_W, 0, 0, 0, 0); if (MooseFrame[i] == NULL) { fprintf(stderr, "Couldn't create SDL_Surfaces:%s\n", SDL_GetError()); free(RawMooseData); quit(5); } SDL_SetColors(MooseFrame[i], MooseColors, 0, 84); { SDL_Surface *newsurf; SDL_PixelFormat format; format.palette = NULL; format.BitsPerPixel = 32; format.BytesPerPixel = 4; #if SDL_BYTEORDER == SDL_LIL_ENDIAN format.Rshift = 0; format.Gshift = 8; format.Bshift = 16; #else format.Rshift = 24; format.Gshift = 16; format.Bshift = 8; #endif format.Ashift = 0; format.Rmask = 0xff << format.Rshift; format.Gmask = 0xff << format.Gshift; format.Bmask = 0xff << format.Bshift; format.Amask = 0; format.Rloss = 0; format.Gloss = 0; format.Bloss = 0; format.Aloss = 8; newsurf = SDL_ConvertSurface(MooseFrame[i], &format, SDL_SWSURFACE); if (!newsurf) { fprintf(stderr, "Couldn't convert picture to 32bits RGB: %s\n", SDL_GetError()); quit(6); } SDL_FreeSurface(MooseFrame[i]); MooseFrame[i] = newsurf; } } free(RawMooseData); overlay = SDL_CreateYUVOverlay(MOOSEPIC_W, MOOSEPIC_H, overlay_format, screen); if (!overlay) { fprintf(stderr, "Couldn't create overlay: %s\n", SDL_GetError()); quit(7); } printf("Created %dx%dx%d %s %s overlay\n", overlay->w, overlay->h, overlay->planes, overlay->hw_overlay ? "hardware" : "software", overlay->format == SDL_YV12_OVERLAY ? "YV12" : overlay->format == SDL_IYUV_OVERLAY ? "IYUV" : overlay->format == SDL_YUY2_OVERLAY ? "YUY2" : overlay->format == SDL_UYVY_OVERLAY ? "UYVY" : overlay->format == SDL_YVYU_OVERLAY ? "YVYU" : "Unknown"); for (i = 0; i < overlay->planes; i++) { printf(" plane %d: pitch=%d\n", i, overlay->pitches[i]); } overlayrect.x = 0; overlayrect.y = 0; overlayrect.w = MOOSEPIC_W * scale; overlayrect.h = MOOSEPIC_H * scale; /* set the start frame */ i = 0; fpsdelay = 1000 / fps; /* Ignore key up events, they don't even get filtered */ SDL_EventState(SDL_KEYUP, SDL_IGNORE); lastftick = SDL_GetTicks(); /* Loop, waiting for QUIT or RESIZE */ while (1) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_RESIZABLE | SDL_SWSURFACE); overlayrect.w = event.resize.w; overlayrect.h = event.resize.h; if (paused) { resized = 1; } break; case SDL_MOUSEBUTTONDOWN: overlayrect.x = event.button.x - overlayrect.w / 2; overlayrect.y = event.button.y - overlayrect.h / 2; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_SPACE) { paused = !paused; break; } if (event.key.keysym.sym != SDLK_ESCAPE) { break; } case SDL_QUIT: SDL_FreeYUVOverlay(overlay); for (i = 0; i < MOOSEFRAMES_COUNT; i++) { SDL_FreeSurface(MooseFrame[i]); } quit(0); } } if ((!paused) || (resized)) { if (((SDL_GetTicks() - lastftick) > fpsdelay) || (resized)) { lastftick = SDL_GetTicks(); switch (overlay_format) { case SDL_YUY2_OVERLAY: ConvertRGBtoYUY2(MooseFrame[i], overlay, 0, 100); break; case SDL_YV12_OVERLAY: ConvertRGBtoYV12(MooseFrame[i], overlay, 0, 100); break; case SDL_UYVY_OVERLAY: ConvertRGBtoUYVY(MooseFrame[i], overlay, 0, 100); break; case SDL_YVYU_OVERLAY: ConvertRGBtoYVYU(MooseFrame[i], overlay, 0, 100); break; case SDL_IYUV_OVERLAY: ConvertRGBtoIYUV(MooseFrame[i], overlay, 0, 100); break; } SDL_DisplayYUVOverlay(overlay, &overlayrect); if (!resized) { i++; if (i == 10) { i = 0; } } else { resized = 0; } } } /* kind of timeslice to OS */ SDL_Delay(1); } SDL_Quit(); return 0; }
bool CGame::Start() { // Esta variable nos ayudara a controlar la salida del juego... int salirJuego = false; while (salirJuego == false){ openGlImplement.DrawStart(); keys = (Uint8*)SDL_GetKeyboardState(NULL); //Maquina de estados switch (estadoJuego){ case ESTADO_INICIANDO: IniciandoVideo(); openGlImplement.InitGL(); openGlImplement.InitShaders(); CargandoObjetos(); InicializandoStage(); estadoJuego = ESTADO_MENU; break; case ESTADO_MENU: MenuActualizar(); MenuPintar(); break; case ESTADO_PRE_JUGANDO: nivelActual = CERO; vida = UNO; enemigosEliminados = CERO; estadoJuego = ESTADO_JUGANDO; juegoGanado = false; IniciarEnemigo(); IniciarNave(); break; case ESTADO_JUGANDO: JugandoActualizar(); JugandoPintar(); break; case ESTADO_FINALIZANDO: salirJuego = true; break; case ESTADO_TERMINANDO: TerminadoPintar(); TerminadoActualizar(); break; }; openGlImplement.DrawEnd(); while (SDL_PollEvent(&event))//Aqui sdl creara una lista de eventos ocurridos { if (event.type == SDL_QUIT) { salirJuego = true; } //si se detecta una salida del sdl o..... if (event.type == SDL_KEYDOWN) {} } //Calculando fps tiempoFrameFinal = SDL_GetTicks(); while (tiempoFrameFinal < (tiempoFrameInicial + FPS_DELAY)) { tiempoFrameFinal = SDL_GetTicks(); SDL_Delay(1); } tiempoFrameInicial = tiempoFrameFinal; tick++; } return true; }
/** * @brief The entry point of Naev. * * @param[in] argc Number of arguments. * @param[in] argv Array of argc arguments. * @return EXIT_SUCCESS on success. */ int main( int argc, char** argv ) { char buf[PATH_MAX]; /* Save the binary path. */ binary_path = strdup(argv[0]); /* Print the version */ LOG( " "APPNAME" v%s", naev_version(0) ); #ifdef GIT_COMMIT DEBUG( " git HEAD at " GIT_COMMIT ); #endif /* GIT_COMMIT */ /* Initializes SDL for possible warnings. */ SDL_Init(0); /* Initialize the threadpool */ threadpool_init(); /* Set up debug signal handlers. */ debug_sigInit(); /* Create the home directory if needed. */ if (nfile_dirMakeExist("%s", nfile_configPath())) WARN("Unable to create config directory '%s'", nfile_configPath()); /* Must be initialized before input_init is called. */ if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { WARN("Unable to initialize SDL Video: %s", SDL_GetError()); return -1; } /* Get desktop dimensions. */ #if SDL_VERSION_ATLEAST(1,2,10) const SDL_VideoInfo *vidinfo = SDL_GetVideoInfo(); gl_screen.desktop_w = vidinfo->current_w; gl_screen.desktop_h = vidinfo->current_h; #else /* #elif SDL_VERSION_ATLEAST(1,2,10) */ gl_screen.desktop_w = 0; gl_screen.desktop_h = 0; #endif /* #elif SDL_VERSION_ATLEAST(1,2,10) */ /* We'll be parsing XML. */ LIBXML_TEST_VERSION xmlInitParser(); /* Input must be initialized for config to work. */ input_init(); /* Set the configuration. */ nsnprintf(buf, PATH_MAX, "%s"CONF_FILE, nfile_configPath()); #if HAS_UNIX /* TODO get rid of this cruft ASAP. */ int oldconfig = 0; if (!nfile_fileExists( buf )) { char *home, buf2[PATH_MAX]; home = SDL_getenv( "HOME" ); if (home != NULL) { nsnprintf( buf2, PATH_MAX, "%s/.naev/"CONF_FILE, home ); if (nfile_fileExists( buf2 )) oldconfig = 1; } } #endif /* HAS_UNIX */ conf_setDefaults(); /* set the default config values */ conf_loadConfig(buf); /* Lua to parse the configuration file */ conf_parseCLI( argc, argv ); /* parse CLI arguments */ /* Enable FPU exceptions. */ #if defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING) if (conf.fpu_except) feenableexcept( FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW ); #endif /* defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING) */ /* Open data. */ if (ndata_open() != 0) ERR("Failed to open ndata."); /* Load the start info. */ if (start_load()) ERR("Failed to load module start data."); /* Load the data basics. */ LOG(" %s", ndata_name()); DEBUG(); /* Display the SDL Version. */ print_SDLversion(); DEBUG(); /* random numbers */ rng_init(); /* * OpenGL */ if (gl_init()) { /* initializes video output */ ERR("Initializing video output failed, exiting..."); SDL_Quit(); exit(EXIT_FAILURE); } window_caption(); gl_fontInit( NULL, NULL, FONT_SIZE ); /* initializes default font to size */ gl_fontInit( &gl_smallFont, NULL, FONT_SIZE_SMALL ); /* small font */ /* Display the load screen. */ loadscreen_load(); loadscreen_render( 0., "Initializing subsystems..." ); time_ms = SDL_GetTicks(); /* * Input */ if ((conf.joystick_ind >= 0) || (conf.joystick_nam != NULL)) { if (joystick_init()) WARN("Error initializing joystick input"); if (conf.joystick_nam != NULL) { /* use the joystick name to find a joystick */ if (joystick_use(joystick_get(conf.joystick_nam))) { WARN("Failure to open any joystick, falling back to default keybinds"); input_setDefault(); } free(conf.joystick_nam); } else if (conf.joystick_ind >= 0) /* use a joystick id instead */ if (joystick_use(conf.joystick_ind)) { WARN("Failure to open any joystick, falling back to default keybinds"); input_setDefault(); } } /* * OpenAL - Sound */ if (conf.nosound) { LOG("Sound is disabled!"); sound_disabled = 1; music_disabled = 1; } if (sound_init()) WARN("Problem setting up sound!"); music_choose("load"); /* FPS stuff. */ fps_setPos( 15., (double)(gl_screen.h-15-gl_defFont.h) ); /* Misc graphics init */ if (nebu_init() != 0) { /* Initializes the nebula */ /* An error has happened */ ERR("Unable to initialize the Nebula subsystem!"); /* Weirdness will occur... */ } gui_init(); /* initializes the GUI graphics */ toolkit_init(); /* initializes the toolkit */ map_init(); /* initializes the map. */ cond_init(); /* Initialize conditional subsystem. */ cli_init(); /* Initialize console. */ /* Data loading */ load_all(); /* Generate the CVS. */ if (conf.devcsv) dev_csv(); /* Unload load screen. */ loadscreen_unload(); /* Start menu. */ menu_main(); /* Force a minimum delay with loading screen */ if ((SDL_GetTicks() - time_ms) < NAEV_INIT_DELAY) SDL_Delay( NAEV_INIT_DELAY - (SDL_GetTicks() - time_ms) ); fps_init(); /* initializes the time_ms */ #if HAS_UNIX /* Tell the player to migrate their configuration files out of ~/.naev */ /* TODO get rid of this cruft ASAP. */ if (oldconfig) { char path[PATH_MAX], *script, *home; uint32_t scriptsize; int ret; nsnprintf( path, PATH_MAX, "%s/naev-confupdate.sh", ndata_getDirname() ); home = SDL_getenv("HOME"); ret = dialogue_YesNo( "Warning", "Your configuration files are in a deprecated location and must be migrated:\n" " \er%s/.naev/\e0\n\n" "The update script can likely be found in your Naev data directory:\n" " \er%s\e0\n\n" "Would you like to run it automatically?", home, path ); /* Try to run the script. */ if (ret) { ret = -1; /* Running from ndata. */ if (ndata_getPath() != NULL) { script = ndata_read( "naev-confupdate.sh", &scriptsize ); if (script != NULL) ret = system(script); } /* Running from laid-out files or ndata_read failed. */ if ((nfile_fileExists(path)) && (ret == -1)) { script = nfile_readFile( (int*)&scriptsize, path ); if (script != NULL) ret = system(script); } /* We couldn't find the script. */ if (ret == -1) { dialogue_alert( "The update script was not found at:\n\er%s\e0\n\n" "Please locate and run it manually.", path ); } /* Restart, as the script succeeded. */ else if (!ret) { dialogue_msg( "Update Completed", "Configuration files were successfully migrated. Naev will now restart." ); execv(argv[0], argv); } else { /* I sincerely hope this else is never hit. */ dialogue_alert( "The update script encountered an error. Please exit Naev and move your config and save files manually:\n\n" "\er%s/%s\e0 =>\n \eD%s\e0\n\n" "\er%s/%s\e0 =>\n \eD%s\e0\n\n" "\er%s/%s\e0 =>\n \eD%snebula/\e0\n\n", home, ".naev/conf.lua", nfile_configPath(), home, ".naev/{saves,screenshots}/", nfile_dataPath(), home, ".naev/gen/*.png", nfile_cachePath() ); } } else { dialogue_alert( "To manually migrate your configuration files " "please exit Naev and run the update script, " "likely found in your Naev data directory:\n" " \er%s/naev-confupdate.sh\e0", home, path ); } }
void profile_start(std::string profile) { #ifdef LS_PERFORMANCE_PROFILE profile_start_msec = SDL_GetTicks(); profile_name = profile; #endif }
void Manager::play() { SDL_Event event; SDLSound sound; bool done = false; bool keyCatch = false; int rnd ; //Fuel bar; unsigned prevTicks = 0; unsigned currTicks = SDL_GetTicks(); unsigned ticks = 0; clock.unpause(); while ( not done ) { if ( ( myPlayer->X() > ( Gamedata::getInstance().getXmlInt("worldWidth") - 200) ) || (livesRemaining<0) ) { io.printMessageAt("Game Over !!!", 800, 400); gameOver = true; clock.pause(); SDL_Flip(screen); SDL_Delay(1250); done = true; break; } //if(cacheEnemies.size()<=5) //{ if(level == 1) { rnd = rand()%200; } else if(level == 2) { rnd = rand()%100; } else { rnd = rand()%50; } if(rnd == 5) { //Enemy *newenemy = new Enemy("enemy"); Enemy *newenemy = new Enemy("enemy", *cachePlayer); newenemy->setPosition(Vector2f(cachePlayer->X() + (3*Gamedata::getInstance().getXmlInt("viewWidth")/4) , rand()%(2*Gamedata::getInstance().getXmlInt("worldHeight")/3)+60 ) ); cacheEnemies.push_back(newenemy); //insert into cache enemies.push_back(newenemy); //insert into enemies currently drawn enemyBlasts.push_back(new MultiSprite("blast")); //insert corresponding blast sprite enemyExploded.push_back(false); //on creation explosion is false } //} for(unsigned i=0; i<enemies.size(); ++i) { if(enemyExploded[i]) { //if ( static_cast<MultiSprite*>(enemies[i])->getCurrentFrame() == 0 ) //sound[1]; if ( static_cast<MultiSprite*>(enemies[i])->getCurrentFrame() == 6 ) { /* //enemyExploded[i] = false; cacheEnemies[i].erase; enemies[i].erase; enemyBlasts[i].erase; enemyExploded[i].erase; //enemies[i] = cacheEnemies[i] ; */ unsigned ctr =0; std::vector<Enemy*>::iterator ptr = cacheEnemies.begin(); while ( ctr < i ) { ctr++; ptr++; } cacheEnemies.erase(ptr); ctr =0; std::vector<MultiSprite*>::iterator ptr1 = enemyBlasts.begin(); while ( ctr < i ) { ctr++; ptr1++; } enemyBlasts.erase(ptr1); ctr =0; std::vector<Drawable*>::iterator ptr2 = enemies.begin(); while ( ctr < i ) { ctr++; ptr2++; } enemies.erase(ptr2); ctr =0; std::vector<bool>::iterator ptr3 = enemyExploded.begin(); while ( ctr < i ) { ctr++; ptr3++; } enemyExploded.erase(ptr3); } } } if(explosion) { if ( static_cast<MultiSprite*>(myPlayer)->getCurrentFrame() == 0 ) { sound[1]; } if ( static_cast<MultiSprite*>(myPlayer)->getCurrentFrame() == 6 ) { timeSinceLastExplosion = 0; explosion = false; myPlayer = cachePlayer ; } } SDL_PollEvent(&event); Uint8 *keystate = SDL_GetKeyState(NULL); if (event.type == SDL_QUIT) { done = true; break; } if(event.type == SDL_KEYUP) { //std::cout<<"******************8KEY_UP*****"; keyCatch = false; if (!keystate[SDLK_RIGHT] && !keystate[SDLK_LEFT]) static_cast<Player*>(myPlayer)->stopX(); if (!keystate[SDLK_UP] && !keystate[SDLK_DOWN]) static_cast<Player*>(myPlayer)->stopY(); if (keystate[SDLK_LEFT] && !keyCatch && !showHelp ) { if(bar.getcurrentLength()) { static_cast<Player*>(myPlayer)->goLeft(); //keyCatch = false; } else { static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_RIGHT] && !showHelp) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { // std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goRight(); } else { //std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_UP] && !showHelp && !explosion) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { // std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goUp(); } else { //std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_DOWN] && !showHelp && !explosion ) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { // std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goDown(); } else { // std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } } if(event.type == SDL_KEYDOWN) { if (keystate[SDLK_ESCAPE] || keystate[SDLK_q]) { clock.pause(); done = true; break; } if (keystate[SDLK_SPACE] && !keyCatch) { keyCatch = true; //io.clearString(); sound.toggleMusic(); break; } if (keystate[SDLK_r] && !keyCatch && !explosion) { keyCatch = true; sound[0]; bullets.shoot( Vector2f(myPlayer->X(),myPlayer->Y() +40) , Vector2f(Gamedata::getInstance().getXmlInt("bulletSpeedX"),Gamedata::getInstance().getXmlInt("bulletSpeedY")) ); } if (keystate[SDLK_p] && !keyCatch && parachutes.size()<100) { keyCatch = true; Sprite *newparachute; int rnd = rand()%3; if(rnd==0) { newparachute= new Sprite("parachuteBig") ; //newparachute->setPosition( Vector2f(sprites[0]->X() + rand()%(Gamedata::getInstance().getXmlInt("viewWidth")/2) , rand()%100) ); newparachute->setVelocity( Vector2f(-100 , 100 )); } else if(rnd==1) { newparachute= new Sprite("parachuteMed") ; //newparachute->setPosition( Vector2f(sprites[0]->X() + rand()%(Gamedata::getInstance().getXmlInt("viewWidth")/2) , rand()%100) ); newparachute->setVelocity( Vector2f(-50 , 50 )); } else { newparachute= new Sprite("parachuteSmall") ; //newparachute->setPosition( Vector2f(sprites[0]->X() + rand()%(Gamedata::getInstance().getXmlInt("viewWidth")/2) , rand()%100) ); newparachute->setVelocity( Vector2f(-25 , 25 )); } newparachute->setPosition( Vector2f(sprites[0]->X() + rand()%(Gamedata::getInstance().getXmlInt("viewWidth")/2) , rand()%100) ); parachutes.push_back(newparachute); std::sort(parachutes.begin(), parachutes.end(), ParachuteCompare()); } /* if (keystate[SDLK_t] && !keyCatch) { keyCatch = true; // currentSprite = (currentSprite+1) % sprites.size(); currentSprite = (currentSprite+1) % 2; viewport.setObjectToTrack(sprites[currentSprite]); }*//* if (keystate[SDLK_F1] && !keyCatch) { keyCatch = true; if(showHelp==true) { showHelp=false; //viewport.setObjectToTrack(sprites[currentSprite]); viewport.setObjectToTrack(myPlayer); } else { //viewport.setObjectToTrack(sprites[2]); viewport.setObjectToTrack(sprites[1]); showHelp=true; } }*/ if (keystate[SDLK_h]&& !keyCatch) { keyCatch = true; if(showHUD==true) { showHUD=false; //viewport.setObjectToTrack(sprites[currentSprite]); } else { //viewport.setObjectToTrack(sprites[2]); showHUD=true; } } /* if (keystate[SDLK_s] && !keyCatch) { keyCatch = true; clock.toggleSloMo(); }*/ if (keystate[SDLK_LEFT] && !showHelp && !explosion ) { if(bar.getcurrentLength()) { static_cast<Player*>(myPlayer)->goLeft(); //keyCatch = false; } else { static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_RIGHT] && !showHelp && !explosion ) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { //std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goRight(); } else { //std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_UP] && !showHelp && !explosion) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { //std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goUp(); } else { // std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_DOWN] && !showHelp && !explosion ) { //std::cout<<bar.getcurrentLength(); if(bar.getcurrentLength()>0) { // std::cout<<"Condition checked"; static_cast<Player*>(myPlayer)->goDown(); } else { //std::cout<<"Condition FALSE"; static_cast<Player*>(myPlayer)->stopX(); static_cast<Player*>(myPlayer)->stopY(); } } if (keystate[SDLK_f]&& !keyCatch ) { keyCatch = true; // std::cout<<" R PRESSED "; //keyCatch = false; //keystate[SDLK_RIGHT] = 1; bar.reset(); } if (keystate[SDLK_e]&& !keyCatch && explosion==false ) { sound[1]; //std::cout<<"E pressed"; keyCatch = true; explosion = true; blast->resetCurrentFrame(); blast->setPosition(Vector2f(myPlayer->X(),myPlayer->Y())); blast->setVelocity(Vector2f(0,0)); myPlayer = blast ; } /* if (keystate[SDLK_k]&& !keyCatch) { sound[1]; //std::cout<<"E pressed"; keyCatch = true; for(unsigned i=0; i<enemies.size(); i++) { enemyExploded[i] = true; enemyBlasts[i]->resetCurrentFrame(); enemyBlasts[i]->setPosition(Vector2f(enemies[i]->X(),enemies[i]->Y())); enemyBlasts[i]->setVelocity(Vector2f(0,0)); enemies[i] = enemyBlasts[i] ; } }*/ } //std::sort(parachutes.begin(), parachutes.end(), ParachuteCompare()); draw(); // **************** Draw Health Meter ******************** //io.printMessageCenteredAt("Press r to reset health meter", 10); currTicks = SDL_GetTicks(); // currTicks = clock.getElapsedTicks(); ticks = currTicks-prevTicks; prevTicks = currTicks; if(showHUD) { bar.draw(); io.printMessageValueAt("FPS: ", clock.getAvgFps(), 10, 20); //string message = "Tracking: "+ sprites[currentSprite]->getName(); //io.printMessageAt(message, 80, 20); //io.printMessageAt("F1: Help", 230, 20); io.printMessageAt("Fuel : ", 1290, 20); io.printMessageValueAt("Level: ", level, 250, 20); io.printMessageValueAt("Score: ", score, 600, 20); //io.printMessageValueAt("timeSinceLastExplosion: ", timeSinceLastExplosion, 500, 20); io.printMessageValueAt("Lives Remaining: ", livesRemaining, 900, 20); if(rand()%10<9 && bar.getcurrentLength()<150) io.printMessageAt("Re-Fuel!!", 1200, 20); } if(!showHelp) bar.update(ticks); SDL_Flip(screen); update(); } }
void profile_stop() { #ifdef LS_PERFORMANCE_PROFILE debugLog("%s took %d ms\n", profile_name.c_str(), SDL_GetTicks() - profile_start_msec); #endif }
int main(int argc, char *argv[]) { SDL_Joystick *joy = NULL; int t1, t0; if (!fs_init(argv[0])) { fprintf(stderr, "Failure to initialize virtual file system: %s\n", fs_error()); return 1; } lang_init("neverball"); opt_parse(argc, argv); config_paths(opt_data); make_dirs_and_migrate(); /* Initialize SDL. */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == -1) { fprintf(stderr, "%s\n", SDL_GetError()); return 1; } /* Intitialize configuration. */ config_init(); config_load(); /* Initialize joystick. */ if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0) { joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE)); if (joy) SDL_JoystickEventState(SDL_ENABLE); } /* Initialize audio. */ audio_init(); tilt_init(); /* Initialize video. */ if (!video_init(TITLE, ICON)) return 1; init_state(&st_null); /* Initialize demo playback or load the level. */ if (opt_replay && fs_add_path(dir_name(opt_replay)) && progress_replay(base_name(opt_replay))) { demo_play_goto(1); goto_state(&st_demo_play); } else if (opt_level) { const char *path = fs_resolve(opt_level); int loaded = 0; if (path) { /* HACK: must be around for the duration of the game. */ static struct level level; if (level_load(path, &level)) { progress_init(MODE_STANDALONE); if (progress_play(&level)) { goto_state(&st_level); loaded = 1; } } } else fprintf(stderr, "%s: file is not in game path\n", opt_level); if (!loaded) goto_state(&st_title); } else goto_state(&st_title); /* Run the main game loop. */ t0 = SDL_GetTicks(); while (loop()) { if ((t1 = SDL_GetTicks()) > t0) { /* Step the game state. */ st_timer(0.001f * (t1 - t0)); t0 = t1; /* Render. */ st_paint(0.001f * t0); shot_take(); video_swap(); if (config_get_d(CONFIG_NICE)) SDL_Delay(1); } } config_save(); if (joy) SDL_JoystickClose(joy); tilt_free(); SDL_Quit(); return 0; }
void OEMFMain :: run(void) { unsigned int menuIndex = 0; unsigned int frames = 0; unsigned int timepassed; if (musicPlayer->isPlayingSong()) musicPlayer->stopSong(); string songfile = PREPATH "boiling.mp3"; musicPlayer->playSongAtPath(songfile.c_str()); drawIntro(); SDL_Event event; int done = 0; while ( !done) { timepassed = SDL_GetTicks(); OEMF_LOCKSCREEN; clearWithColor(0xFF000000, false); OEMF_UNLOCKSCREEN; blitImage(images[IMG_INTRO], 0, 0); for (unsigned int i = 0; i < m_menuCount; i++) fonts[FNT_MENU]->blitText(this, m_menuOptions[i].c_str(), 160, 240 + i * 32, 480, false); blitImage(images[IMG_OEMFOE], 128, (unsigned int) (240 + menuIndex * 32 + sin(frames / 2.0) * 8)); SDL_UpdateRect(m_screen, 128, 232, 512, 248); /* Check for events */ while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEMOTION: break; case SDL_MOUSEBUTTONDOWN: break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { done = 1; } else if (event.key.keysym.sym == SDLK_UP) { menuIndex = (menuIndex - 1 + m_menuCount) % m_menuCount; musicPlayer->playSound(sounds[SND_TOK]); } else if (event.key.keysym.sym == SDLK_DOWN) { menuIndex = (menuIndex + 1) % m_menuCount; musicPlayer->playSound(sounds[SND_TOK]); } else if (event.key.keysym.sym == SDLK_p) { SDL_SaveBMP(m_screen, "screenshot.bmp"); } else if (event.key.keysym.sym == SDLK_RETURN) { musicPlayer->playSound(sounds[SND_TIK]); if (menuIndex == 4) { fadeOut(); done = 1; } else if (menuIndex == 0) // new game { fadeOut(); OEMFGame * game = new OEMFGame(m_screen, m_execPath, m_screenWidth, m_screenHeight, m_screenBpp); game->run(); delete game; drawIntro(); } else if (menuIndex == 3) // level editor { fadeOut(); OEMFLevelEdit * leveledit = new OEMFLevelEdit(m_screen, m_execPath, m_screenWidth, m_screenHeight, m_screenBpp); leveledit->run(); delete leveledit; drawIntro(); } else if (menuIndex == 2) // options { unsigned int choice = 0; string * options = new string[2]; while (choice != 2) // not exit { if (musicEnabled) options[0] = "Turn Music Off"; else options[0] = "Turn Music On"; options[1] = "Toggle Fullscreen"; drawIntro(); choice = chooseList(2 /* exit */, "Options", options, 2); if (choice == 0) { musicEnabled = !musicEnabled; if (!musicEnabled) { if (musicPlayer->isPlayingSong()) musicPlayer->stopSong(); } else { musicPlayer->playSongAtPath(songfile.c_str()); } } else if (choice == 1) { if (fullscreenMode) { m_screen = SDL_SetVideoMode(m_screenWidth, m_screenHeight, m_screenBpp, SDL_SWSURFACE); m_fb = (Uint32 *) m_screen->pixels; m_pitch = (Uint32) m_screen->pitch / 4; fullscreenMode = false; } else { m_screen = SDL_SetVideoMode(m_screenWidth, m_screenHeight, m_screenBpp, SDL_SWSURFACE | SDL_FULLSCREEN); m_fb = (Uint32 *) m_screen->pixels; m_pitch = (Uint32) m_screen->pitch / 4; fullscreenMode = true; } choice = 2; } } drawIntro(); } else { fadeOut(); fonts[FNT_MENU]->blitCenterText(this, "NOT AVAILABLE YET", 240, m_screenWidth); SDL_UpdateRect(m_screen, 0, 0, m_screenWidth, m_screenHeight); SDL_Delay(2000); string test = fonts[FNT_MENU]->inputText(this, "default", 32, 32, 10); drawIntro(); } } break; case SDL_QUIT: done = 1; break; default: break; } } frames++; // 30 FPS timepassed = SDL_GetTicks() - timepassed; if (timepassed <= 33) SDL_Delay(33 - timepassed); } }
int main(int argc, char *argv[]) { SDL_Window *window; /* main window */ Uint32 startFrame; /* time frame began to process */ Uint32 endFrame; /* time frame ended processing */ Uint32 delay; /* time to pause waiting to draw next frame */ int done; /* should we clean up and exit? */ /* initialize SDL */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { fatalError("Could not initialize SDL"); } /* seed the random number generator */ srand(time(NULL)); /* request some OpenGL parameters that may speed drawing */ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); /* create main window and renderer */ window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); SDL_CreateRenderer(window, 0, 0); /* load the particle texture */ initializeTexture(); /* check if GL_POINT_SIZE_ARRAY_OES is supported this is used to give each particle its own size */ pointSizeExtensionSupported = SDL_GL_ExtensionSupported("GL_OES_point_size_array"); /* set up some OpenGL state */ glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, 1); if (pointSizeExtensionSupported) { /* we use this to set the sizes of all the particles */ glEnableClientState(GL_POINT_SIZE_ARRAY_OES); } else { /* if extension not available then all particles have size 10 */ glPointSize(10); } done = 0; /* enter main loop */ while (!done) { startFrame = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { done = 1; } if (event.type == SDL_MOUSEBUTTONDOWN) { int x, y; SDL_GetMouseState(&x, &y); spawnEmitterParticle(x, y); } } stepParticles(); drawParticles(); endFrame = SDL_GetTicks(); /* figure out how much time we have left, and then sleep */ delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame); if (delay > MILLESECONDS_PER_FRAME) { delay = MILLESECONDS_PER_FRAME; } if (delay > 0) { SDL_Delay(delay); } } /* delete textures */ glDeleteTextures(1, &particleTextureID); /* shutdown SDL */ SDL_Quit(); return 0; }
void Timer::start() { startTime = SDL_GetTicks(); paused = false; }
void setTimer(Timer *timer) { timer->currentTime = SDL_GetTicks(); timer->ellapsedTime = timer->currentTime - timer->lastTime; timer->lastTime = timer->currentTime; }
void Watch::start() { stoped = false; lastRun = SDL_GetTicks(); }
/** * Works with any update function. */ static void run_main_loop( void (*update_fn)( LoopData*, bool ), LoopData* data, float ups ) { assert( data->running && ups > 0 ); // maximum number of frame skips before we force a render static const int MAX_SKIPS = 3; // the maximum possible lag time, lag is capped here static const int MAX_LAG_TIME = 100; // frequency at which to print frame rate info static const int FRAME_RATE_PRINT_TIME = 600; int period = static_cast< int >( 1000.0 / ups ); // frame period in milliseconds // how far we are behind the target framerate int lag_time = 0; // the number of updates since the last render int num_skips = 0; // time since last frame counter start int frame_rate_counter_start = SDL_GetTicks(); // frame rate counter int frame_rate_counter = 0; int total_frame_time = 0; while ( *data->running ) { int start_time = SDL_GetTicks(); // update, only if we are not too far behind, or if we've skipped too many frames if ( lag_time < period || num_skips >= MAX_SKIPS ) { // update update_fn( data, false ); num_skips = 0; frame_rate_counter++; } else { update_fn( data, true ); num_skips++; } // if ( frame_rate_counter == FRAME_RATE_PRINT_TIME ) { // int curr_time = SDL_GetTicks(); // printf( "main loop frame rate: %f, avg frame time: %f\n", // FRAME_RATE_PRINT_TIME * 1000 / float(curr_time - frame_rate_counter_start), // float(total_frame_time) / FRAME_RATE_PRINT_TIME // ); // frame_rate_counter_start = curr_time; // frame_rate_counter = 0; // total_frame_time = 0; // } // compute sleep time until end of period, may be negative int end_time = SDL_GetTicks(); int time_diff = end_time - start_time; int sleep_time = period - time_diff - lag_time; total_frame_time += time_diff; // always yield at least once to keep system responsive SDL_Delay( 1 ); if ( sleep_time > 0 ) { // sleep until end of period while ( int(SDL_GetTicks()) < end_time + sleep_time ) { SDL_Delay( sleep_time - 1 ); } // if we oversleep, add to lag. note this must be nonnegative // because of the while loop above lag_time = (int)(SDL_GetTicks()) - (end_time + sleep_time); } else { // otherwise mark how much we're falling behind // sleep time is negative here, so it's like adding the time we went over lag_time = -sleep_time; } // cap the lag time to avoid lots of skips if ( lag_time > MAX_LAG_TIME ) { lag_time = MAX_LAG_TIME; } } }
bool Visualization::update() { if (!m_initialized) { printf("Visualization has not been yet initialized."); return false; } // Compute the time since last update (in seconds). Uint32 time = SDL_GetTicks(); float dt = (time - m_lastTickCount) / 1000.0f; m_lastTickCount = time; bool singleSimulationStep = false; bool scrollForward = false; bool scrollBackward = false; int mscroll = 0; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: // Handle any key presses here. if (event.key.keysym.sym == SDLK_ESCAPE) //Escape. { m_stopRequested = true; } else if (event.key.keysym.sym == SDLK_SPACE) { m_paused = !m_paused; } else if (event.key.keysym.sym == SDLK_TAB) { singleSimulationStep = true; } else if (event.key.keysym.sym == SDLK_r) { float pos[3] = {-15, 0, 15}; m_crowd->pushAgentPosition(0, pos); } else if (event.key.keysym.sym == SDLK_KP7) { float pos[3] = {-19, 0, -19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP9) { float pos[] = {19, 0, -19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP3) { float pos[3] = {19, 0, 19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP1) { float pos[3] = {-19, 0, 19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP5) { float pos[3] = {0, 0, 0}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_RIGHT) { // Rotate view m_rotating = true; m_initialMousePosition[0] = m_mousePosition[0]; m_initialMousePosition[1] = m_mousePosition[1]; m_intialCameraOrientation[0] = m_cameraOrientation[0]; m_intialCameraOrientation[1] = m_cameraOrientation[1]; m_intialCameraOrientation[2] = m_cameraOrientation[2]; } else if (event.button.button == SDL_BUTTON_WHEELUP) { scrollForward = true; } else if (event.button.button == SDL_BUTTON_WHEELDOWN) { scrollBackward = true; } break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_RIGHT) { m_rotating = false; } else if (event.button.button == SDL_BUTTON_LEFT) { float pickedPosition[3]; int index = 0; pick(pickedPosition, &index); } break; case SDL_MOUSEMOTION: m_mousePosition[0] = event.motion.x; m_mousePosition[1] = m_winHeight-1 - event.motion.y; if (m_rotating) { int dx = m_mousePosition[0] - m_initialMousePosition[0]; int dy = m_mousePosition[1] - m_initialMousePosition[1]; m_cameraOrientation[0] = m_intialCameraOrientation[0] - dy*0.25f; m_cameraOrientation[1] = m_intialCameraOrientation[1] + dx*0.25f; } break; case SDL_QUIT: m_stopRequested = true; break; default: break; } } unsigned char mbut = 0; if (SDL_GetMouseState(0,0) & SDL_BUTTON_LMASK) mbut |= IMGUI_MBUT_LEFT; if (SDL_GetMouseState(0,0) & SDL_BUTTON_RMASK) mbut |= IMGUI_MBUT_RIGHT; // Update the camera velocity from keyboard state. Uint8* keystate = SDL_GetKeyState(NULL); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4800) #endif updateCameraVelocity( dt, keystate[SDLK_w] || keystate[SDLK_UP] || scrollForward, keystate[SDLK_s] || keystate[SDLK_DOWN] || scrollBackward, keystate[SDLK_a] || keystate[SDLK_LEFT], keystate[SDLK_d] || keystate[SDLK_RIGHT], SDL_GetModState() & KMOD_SHIFT); #ifdef _MSC_VER #pragma warning(pop) #endif //Update the camera position updateCameraPosition(dt); //Update the crowd if (m_crowd) { if (singleSimulationStep) { m_paused = true; m_debugInfo->startUpdate(); m_crowd->update(m_crowdDt); m_debugInfo->endUpdate(m_crowdDt); m_crowdAvailableDt = 0.f; } else if (!m_paused) { m_crowdAvailableDt += dt; while(m_crowdAvailableDt > m_crowdDt) { m_debugInfo->startUpdate(); m_crowd->update(m_crowdDt); m_debugInfo->endUpdate(m_crowdDt); m_crowdAvailableDt -= m_crowdDt; } } else { m_crowdAvailableDt = 0.f; } } // Set rendering context glViewport(0, 0, m_winWidth, m_winHeight); glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); // Render 3D glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(50.0f, (float)m_winWidth/(float)m_winHeight, m_zNear, m_zFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(m_cameraOrientation[0],1,0,0); glRotatef(m_cameraOrientation[1],0,1,0); glRotatef(m_cameraOrientation[2],0,0,1); glTranslatef(-m_cameraPosition[0], -m_cameraPosition[1], -m_cameraPosition[2]); // Extract OpenGL view properties glGetDoublev(GL_PROJECTION_MATRIX, m_projection); glGetDoublev(GL_MODELVIEW_MATRIX, m_modelView); glGetIntegerv(GL_VIEWPORT, m_viewport); renderScene(); renderCrowd(); // Render 2D Overlay glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, m_winWidth, 0, m_winHeight); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); imguiBeginFrame(m_mousePosition[0], m_mousePosition[1], mbut,mscroll); renderDebugInfoOverlay(); imguiEndFrame(); imguiRenderGLDraw(); glEnable(GL_DEPTH_TEST); SDL_GL_SwapBuffers(); return true; }