int main(int argc, char *argv[]) { TankGame game; float tick_duration = 1000.0f / SDL_GetPerformanceFrequency(); float frame_ticks = SDL_GetPerformanceFrequency() * 1.0f / 60.0f; auto timer = SDL_GetPerformanceCounter(); if (game.initialize(false)) { game.loadLevel01(); for (int i = 0; i < 500; ++i) { if (game.getPlayerTank()) { game.getPlayerTank()->turnTurret(0.02); if (i % 4 == 0) game.getPlayerTank()->fireBullet(5.0f); } game.updateLogic(1.0f/60.0); game.render(); auto now = SDL_GetPerformanceCounter(); float delay = frame_ticks - (float)(now - timer); if (delay > 0) { SDL_Delay(delay * tick_duration); } timer = SDL_GetPerformanceCounter(); } } }
void Clock::Initialize() { DEBUGPRINTF( "Initializing Clock\n" ); ShutDown(); #if BUILD_WINDOWS_NO_SDL LARGE_INTEGER Frequency; LARGE_INTEGER Counter; QueryPerformanceFrequency( &Frequency ); QueryPerformanceCounter( &Counter ); m_Resolution = 1.0 / (double)Frequency.QuadPart; m_PhysicalBaseTime = Counter.QuadPart; #endif #if BUILD_SDL Uint64 Frequency = SDL_GetPerformanceFrequency(); Uint64 Counter = SDL_GetPerformanceCounter(); m_Resolution = 1.0 / static_cast<double>( Frequency ); m_PhysicalBaseTime = Counter; #endif m_PhysicalDeltaTime = 0; m_MachineDeltaTime = 0.0f; m_GameDeltaTime = 0.0f; m_PhysicalCurrentTime = 0; m_MachineCurrentTime = 0.0f; m_GameCurrentTime = 0.0f; m_TickCount = 0; }
void app::perf::dump(bool log) { // Sample the timer. Uint64 current = SDL_GetPerformanceCounter(); Uint64 persec = SDL_GetPerformanceFrequency(); // Calculate the timings. double d1 = double(current - local_start) / double(persec); double dn = double(current - total_start) / double(persec); double m1 = 1000.0 * d1 / local_frames; double mn = 1000.0 * dn / total_frames; int fps = int(ceil(local_frames / d1)); local_start = current; // Report to a string. Set the window title and log. std::ostringstream str; str << std::fixed << std::setprecision(1) << m1 << "ms " << "(" << mn << "ms) " << fps << "fps"; SDL_SetWindowTitle(window, str.str().c_str()); if (log) std::cout << str.str() << std::endl; }
void Core::run() { uint64_t frequency = SDL_GetPerformanceFrequency(); uint64_t fixedStep = frequency / static_cast<uint64_t>(kStepRate); uint64_t maxTotalDelta = fixedStep * 6; uint64_t stepTime = SDL_GetPerformanceCounter(); while(!done_) { uint64_t loopTime = SDL_GetPerformanceCounter(); if(loopTime > stepTime + maxTotalDelta) { stepTime = loopTime - maxTotalDelta; } while(loopTime >= stepTime + fixedStep) { handleEvents(); sessionManager_->handleBlobs(); step(fp_t(1.0) / kStepRate); stepTime += fixedStep; } #ifndef HEADLESS fp_t interp = static_cast<fp_t>(loopTime - stepTime) / static_cast<fp_t>(frequency); renderer_->render(interp); #else // simulate ~83 without game logic SDL_Delay(12); #endif } }
void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplSDL2_UpdateGamepads(); }
void OpenGlCamera::UpdateCamera(const Uint8 *keyboard_state, int *x, int *y) { double render_time = (SDL_GetPerformanceCounter() - last_call_time_) / (double)SDL_GetPerformanceFrequency(); last_call_time_ = SDL_GetPerformanceCounter(); // the mouse movement doesn't depend on the render_time (fps) this->camera_data_->AddRot((-*y) * 0.001f * this->camera_data_->camera_sensitivity, (-*x) * 0.001f * this->camera_data_->camera_sensitivity, 0.0f); /*if (keyboard_state[SDL_SCANCODE_Q]) this->camera_data->AddRot(0.0f, 0.0f, +render_time * this->camera_data_->speed * 0.1f); if (keyboard_state[SDL_SCANCODE_E]) this->camera_data->AddRot(0.0f, 0.0f, -render_time * this->camera_data_->speed * 0.1f);*/ // Movement if (keyboard_state[SDL_SCANCODE_Q]) this->camera_data_->AddPos(0.0f, 0.0f, -render_time * this->camera_data_->camera_speed); if (keyboard_state[SDL_SCANCODE_E]) this->camera_data_->AddPos(0.0f, 0.0f, +render_time * this->camera_data_->camera_speed); if (keyboard_state[SDL_SCANCODE_W] || keyboard_state[SDL_SCANCODE_UP]) this->camera_data_->AddPos(+render_time * this->camera_data_->camera_speed, 0.0f, 0.0f); if (keyboard_state[SDL_SCANCODE_A] || keyboard_state[SDL_SCANCODE_LEFT]) this->camera_data_->AddPos(0.0f, +render_time * this->camera_data_->camera_speed, 0.0f); if (keyboard_state[SDL_SCANCODE_S] || keyboard_state[SDL_SCANCODE_DOWN]) this->camera_data_->AddPos(-render_time * this->camera_data_->camera_speed, 0.0f, 0.0f); if (keyboard_state[SDL_SCANCODE_D] || keyboard_state[SDL_SCANCODE_RIGHT]) this->camera_data_->AddPos(0.0f, -render_time * this->camera_data_->camera_speed, 0.0f); }
bool Engine::Initialize() { // We will initialize all SDL subsystems one by one SDL_Init( 0 ); // Profiler needs the timer subsystem if ( SDL_InitSubSystem( SDL_INIT_TIMER ) != 0 ) { Logger::Log( "Failed to initialize SDL timer subsystem", "SDL", LogSeverity::ERROR_MSG ); assert( false ); } g_Profiler.SetFrequency( SDL_GetPerformanceFrequency() ); // Several systems need the event system if ( SDL_InitSubSystem( SDL_INIT_EVENTS ) != 0 ) { Logger::Log( "Failed to initialize SDL event subsystem", "SDL", LogSeverity::ERROR_MSG ); assert( false ); } g_SubsystemBank.Initialize(); InitializeComponentSystem(); g_InputState.Initialize(); g_Input.Initialize(); g_TextInput.Initialize(); m_SubsystemCollection.InitializeGameMode( ( 1 << g_SubsystemBank.GetNrOfSubsystems() ) - 1 ); return true; }
/* ================ Sys_DoubleTime ================ */ double Sys_DoubleTime( void ) { static longtime_t g_PerformanceFrequency; static longtime_t g_ClockStart; longtime_t CurrentTime; #ifdef XASH_SDL if( !g_PerformanceFrequency ) { g_PerformanceFrequency = SDL_GetPerformanceFrequency(); g_ClockStart = SDL_GetPerformanceCounter(); } CurrentTime = SDL_GetPerformanceCounter(); return (double)( CurrentTime - g_ClockStart ) / (double)( g_PerformanceFrequency ); #elif _WIN32 if( !g_PerformanceFrequency ) { g_PerformanceFrequency = GetPerformanceFrequency(); g_ClockStart = GetPerformanceCounter(); } CurrentTime = GetPerformanceCounter(); return (double)( CurrentTime - g_ClockStart ) / (double)( g_PerformanceFrequency ); #else struct timespec ts; if( !g_PerformanceFrequency ) { struct timespec res; if( !clock_getres(CLOCK_MONOTONIC, &res) ) g_PerformanceFrequency = 1000000000LL/res.tv_nsec; } clock_gettime(CLOCK_MONOTONIC, &ts); return (double) ts.tv_sec + (double) ts.tv_nsec/1000000000.0; #endif }
void executeStack(StateStack& stack, SDL_Window& window, bool* pTerminator) { std::vector<const SDL_Event> events; SDL_Event e; bool localRunning = true; bool& running = pTerminator ? *pTerminator : localRunning; Uint64 t0 = SDL_GetPerformanceCounter(); while (!stack.empty() && running == true) { while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } events.push_back(e); } Uint64 now = SDL_GetPerformanceCounter(); float dt = (float)(now - t0) / SDL_GetPerformanceFrequency(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); tickStack(stack, events, dt); events.clear(); SDL_GL_SwapWindow(&window); t0 = now; } }
// ------------------------------------------------------------------------------------------------ // Timer Class // ------------------------------------------------------------------------------------------------ cTimer::cTimer(const cTimer::timerState_t tState) { state = tState; dt = 0.0; now = SDL_GetPerformanceCounter(); prev = now; cpuFreq = SDL_GetPerformanceFrequency(); }
void SimKit::FPSTimeline::log_frame_end() { this->frame_end = SDL_GetPerformanceCounter(); this->frame_recorded = true; this->past_frames[this->past_frames_ctr % SimKit::FPSTimeline::NUM_PAST_FRAMES] = ((float)(this->frame_end - this->frame_begin) / (float)SDL_GetPerformanceFrequency()) * MICROSECONDS_PER_SECOND; this->past_frames_ctr++; };
void GameTimer::Start( ) { m_Started = true; m_Paused = false; m_StartTicks = SDL_GetPerformanceCounter( ); m_LastCheckedTicks = SDL_GetPerformanceCounter( ); m_TicksPerSec = SDL_GetPerformanceFrequency( ); }
CPUTimer(int iter) : iter(iter), acc(0), counter(0), ticks(0) { perfFreq = SDL_GetPerformanceFrequency(); }
float FrameCounter::GetAverageFPS() const { uint64_t total = 0; for ( unsigned int i = 0; i < m_nrOfFrames; ++i ) { total += m_frameTimes[i]; } return SDL_GetPerformanceFrequency() * m_nrOfFrames / ( total * 1.0f ); }
float FrameCounter::GetAverageMS() const { uint64_t total = 0; for ( unsigned int i = 0; i < m_nrOfFrames; ++i ) { total += m_frameTimes[i]; } return total / ( SDL_GetPerformanceFrequency() * 0.001f * m_nrOfFrames ); }
uint32_t TimeCounterGetMsec() { uint64_t perfCounter = SDL_GetPerformanceCounter(); uint64_t perfFreq = SDL_GetPerformanceFrequency(); uint32_t msec = ( uint32_t )( 1000000 * perfCounter / perfFreq ); return msec; }
internal b32 SetupSDLWindow(GameState * CurrentGameState) { if(CurrentGameState->ScreenWidth == 0) { CurrentGameState->ScreenWidth = DEFAULT_SCREEN_WIDTH; } if(CurrentGameState->ScreenHeight == 0) { CurrentGameState->ScreenHeight = DEFAULT_SCREEN_HEIGHT; } SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 0 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); CurrentGameState->MainSDLWindow = SDL_CreateWindow("TA_SDL: SOMETHING HERE!!!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,CurrentGameState->ScreenWidth, CurrentGameState->ScreenHeight, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL); if (!CurrentGameState->MainSDLWindow) { LogError("SDL_CreateWindow Error: %s", SDL_GetError()); return 0; } CurrentGameState->PerformanceCounterFrequency = SDL_GetPerformanceFrequency(); Assert(CurrentGameState->PerformanceCounterFrequency); GLint GLMajorVer, GLMinorVer; CurrentGameState->glContext = SDL_GL_CreateContext( CurrentGameState->MainSDLWindow); SDL_GL_MakeCurrent (CurrentGameState->MainSDLWindow,CurrentGameState->glContext); if( SDL_GL_SetSwapInterval( 1 ) < 0 ) { LogWarning("Warning: Unable to set VSync! SDL Error: %s",SDL_GetError()); } glGetIntegerv(GL_MAJOR_VERSION, &GLMajorVer); glGetIntegerv(GL_MINOR_VERSION, &GLMinorVer); GLenum ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed before glewInit : %s",gluErrorString(ErrorValue)); } //as we need to use glewExperimental - known issue (it segfaults otherwise!) - we encounter //another known issue, which is that while glewInit suceeds, it leaves opengl in an error state ErrorValue = glGetError(); return 1; }
bool TimeKeeper::initialize() { m_freq = SDL_GetPerformanceFrequency(); m_init_time = SDL_GetPerformanceCounter(); m_current_time = m_previous_time = getCurrentTime(); return true; }
void timer_init() { if ( !Timer_inited ) { Timer_perf_counter_freq = SDL_GetPerformanceFrequency(); Timer_inited = 1; atexit(timer_close); } }
/** * @brief Call to SDL_GetPerformanceFrequency */ int timer_getPerformanceFrequency(void *arg) { Uint64 result; result = SDL_GetPerformanceFrequency(); SDLTest_AssertPass("Call to SDL_GetPerformanceFrequency()"); SDLTest_AssertCheck(result > 0, "Check result value, expected: >0, got: %lu", result); return TEST_COMPLETED; }
void time_init(void) { use_hires = env_get("TAISEI_HIRES_TIMER", 1); if(use_hires) { log_info("Using the system high resolution timer"); prev_hires_time = SDL_GetPerformanceCounter(); set_freq(SDL_GetPerformanceFrequency()); } else { log_info("Not using the system high resolution timer: disabled by environment"); return; } }
FPSLimiter(uint16_t desiredFPS) : lastTickCount(SDL_GetPerformanceCounter()), tickFreq(SDL_GetPerformanceFrequency()), tickFreqMS(tickFreq / 1000), tickFreqNS((double) tickFreq / NS_PER_S), disabled(false) { setDesiredFPS(desiredFPS); adj.last = SDL_GetPerformanceCounter(); adj.idealDiff = 0; adj.resetFlag = false; }
//----------------------------------------------------------------------------- void AdScreen::Present(void) { int pitch; void* pixels; SDL_LockTexture(s_pTexture, NULL, &pixels, &pitch); SDL_ConvertPixels( s_pScreen->w, s_pScreen->h, s_pScreen->format->format, s_pScreen->pixels, s_pScreen->pitch, SDL_PIXELFORMAT_RGBA8888, pixels, pitch ); SDL_UnlockTexture(s_pTexture); SDL_RenderCopy(GetRenderer(), s_pTexture, NULL, NULL); SDL_RenderPresent(GetRenderer()); s_iFrames++; s_uiCurrentCount = SDL_GetPerformanceCounter(); s_uiDiffCount = (s_uiCurrentCount-s_uiLastCount); s_uiCountFreq = SDL_GetPerformanceFrequency(); s_fElapsedTime = ((float) s_uiDiffCount/(float) s_uiCountFreq); if((1.0f/60.0f)-s_fElapsedTime > 0) { // NOTE: without this there seems to be a more consistent framerate // but on older computers sometimes the vsync doesn't work right //SDL_Delay((uint32_t) (1000.0f*((1.0f/60.0f)-s_fElapsedTime))); s_fTotTime += 1.0f/60.0f; } else { s_fTotTime += s_fElapsedTime; } s_uiLastCount = s_uiCurrentCount; if(s_fTotTime >= 1.0f) { char strTitle[0x20] = ""; sprintf(strTitle, "%s, FPS: %d", WINDOW_TITLE, s_iFrames); SDL_SetWindowTitle(GetWindow(), strTitle); s_fTotTime = 0; s_iFrames = 0; } }
double updateDeltaTime() { Uint64 curTime; double deltaTime; if (prevTime == 0) { prevTime = SDL_GetPerformanceCounter(); } curTime = SDL_GetPerformanceCounter(); deltaTime = (double) (curTime - prevTime) / (double) SDL_GetPerformanceFrequency(); prevTime = curTime; return deltaTime; }
int main(int _argc, char *_argv[]) { try { bool quit = false; SDLState sdl; DispatchStack &dispatch = DispatchStack::get(); Game game; Update update; glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); update.ticksLast = SDL_GetPerformanceCounter(); update.tickFrequency = SDL_GetPerformanceFrequency(); // Should really refresh this. while(!quit) { SDL_Event event; while(SDL_PollEvent(&event)) { if(!dispatch.handleEvent(event) && (event.type == SDL_QUIT)) quit = true; } update.ticksNow = SDL_GetPerformanceCounter(); update.dt = float((update.ticksNow - update.ticksLast) / double(update.tickFrequency)); dispatch.update(update); update.ticksLast = update.ticksNow; dispatch.handleIdle(); SDL_Delay(0); } } catch(std::exception tExc) { std::cerr << "An exception occurred: " << tExc.what() << std::endl; return -1; } catch(...) { std::cerr << "An unknown exception occurred." << std::endl; return -2; } }
static int get_elapsed_time ( Uint64 t_old, Uint64 *t_new, time_t *store_unix_time ) { #ifdef XEMU_OLD_TIMING #define __TIMING_METHOD_DESC "gettimeofday" struct timeval tv; gettimeofday(&tv, NULL); if (store_unix_time) *store_unix_time = tv.tv_sec; *t_new = tv.tv_sec * 1000000UL + tv.tv_usec; return *t_new - t_old; #else #define __TIMING_METHOD_DESC "SDL_GetPerformanceCounter" if (store_unix_time) *store_unix_time = time(NULL); *t_new = SDL_GetPerformanceCounter(); return 1000000 * (*t_new - t_old) / SDL_GetPerformanceFrequency(); #endif }
int main() { double *fs = malloc(SIZE * sizeof (double)); int i; Uint64 c, acc; srand(SEED); acc = 0; for (i = 0; i < SIZE; i++) { fs[i] = rand()/(double)RAND_MAX; fs[i] *= 2.0; fs[i] -= 1.0; c = SDL_GetPerformanceCounter(); fs[i] = fclamp0(fs[i], D_MAX); acc += SDL_GetPerformanceCounter() - c; } free(fs); printf("%f secs\n", acc/(double) SDL_GetPerformanceFrequency()); return 0; }
//Apply forces, resolve collisions, etc. void Scene::Update(NUI_SKELETON_FRAME* frame) { //Update kinect data skeletonFrame = frame; //Timekeeping stuff previousTime = currentTime; currentTime = SDL_GetPerformanceCounter(); deltaTime = float(double(currentTime - previousTime) / double(SDL_GetPerformanceFrequency())); //Step through particles and update them for (int i = 0; i < particles.Size(); ++i) { particles[i].Update(deltaTime); } //Process Player input (this->*dataCollection)(); //Add new particles that are created by emitters for (Emitter* e : emitters) { e->Update(deltaTime); e->AddParticle(particles); } //Delete particles that have exceeded their lifespan particles.RemoveElements([](const Particle& p)->bool {return p.IsAlive(); }); //Step through targets for (Target* target : targets) { //Check particle collisions with target for (int i = 0; i < particles.Size(); ++i) { target->Collide(&particles[i]); } //Update target's location target->Update(deltaTime); } }
void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt()); // Font atlas needs to be built, call renderer _NewFrame() function e.g. ImGui_ImplOpenGL3_NewFrame() // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); }
void Scheduler::run_tasks_loop_with_task_id(TaskId root_id) { const auto num_additional_threads = num_nodes() - 1; std::vector<std::thread> threads; threads.reserve(num_additional_threads); for (NodeId i_node = 0; i_node < num_nodes_; ++i_node) { node(i_node).attach(*this, i_node); } for (NodeId i_thread = 0; i_thread < num_additional_threads; ++i_thread) { threads.emplace_back([this, i_thread]{ node(i_thread + 1).run_tasks_loop(); }); } auto x = SDL_GetPerformanceCounter(); node(0).generic_tasks_.unique_push(root_id); node(0).run_tasks_loop(); LOG(INFO) << ((SDL_GetPerformanceCounter() - x) / double(SDL_GetPerformanceFrequency())); for (auto& thread : threads) thread.join(); }