| 1 |
/* |
| 2 |
* This file is part of the DXX-Rebirth project <https://www.dxx-rebirth.com/>. |
| 3 |
* It is copyright by its individual contributors, as recorded in the |
| 4 |
* project's Git history. See COPYING.txt at the top level for license |
| 5 |
* terms and a link to the Git history. |
| 6 |
*/ |
| 7 |
/* |
| 8 |
* |
| 9 |
* SDL library timer functions |
| 10 |
* |
| 11 |
*/ |
| 12 |
|
| 13 |
#include <SDL.h> |
| 14 |
|
| 15 |
#include "fwd-game.h" |
| 16 |
#include "maths.h" |
| 17 |
#include "timer.h" |
| 18 |
#include "config.h" |
| 19 |
#include "multi.h" |
| 20 |
|
| 21 |
namespace dcx { |
| 22 |
|
| 23 |
static fix64 F64_RunTime = 0; |
| 24 |
|
| 25 |
fix64 timer_update() |
| 26 |
{ |
| 27 |
static bool already_initialized; |
| 28 |
static fix64 last_tv; |
| 29 |
const fix64 cur_tv = static_cast<fix64>(SDL_GetTicks()) * F1_0 / 1000; |
| 30 |
const fix64 prev_tv = last_tv; |
| 31 |
fix64 runtime = F64_RunTime; |
| 32 |
last_tv = cur_tv; |
| 33 |
if (unlikely(!already_initialized)) |
| 34 |
{ |
| 35 |
already_initialized = true; |
| 36 |
} |
| 37 |
else if (likely(prev_tv < cur_tv)) // in case SDL_GetTicks wraps, don't update and have a little hickup |
| 38 |
F64_RunTime = (runtime += (cur_tv - prev_tv)); // increment! this value will overflow long after we are all dead... so why bother checking? |
| 39 |
return runtime; |
| 40 |
} |
| 41 |
|
| 42 |
fix64 timer_query(void) |
| 43 |
{ |
| 44 |
return (F64_RunTime); |
| 45 |
} |
| 46 |
|
| 47 |
void timer_delay_ms(unsigned milliseconds) |
| 48 |
{ |
| 49 |
SDL_Delay(milliseconds); |
| 50 |
} |
| 51 |
|
| 52 |
// Replacement for timer_delay which considers calc time the program needs between frames (not reentrant) |
| 53 |
void timer_delay_bound(const unsigned caller_bound) |
| 54 |
{ |
| 55 |
static uint32_t FrameStart; |
| 56 |
|
| 57 |
uint32_t start = FrameStart; |
| 58 |
const auto multiplayer{Game_mode & GM_MULTI}; |
| 59 |
const auto vsync{CGameCfg.VSync}; |
| 60 |
const auto bound = vsync ? 1000u / MAXIMUM_FPS : caller_bound; |
| 61 |
for (;;) |
| 62 |
{ |
| 63 |
const uint32_t tv_now = SDL_GetTicks(); |
| 64 |
if (multiplayer) |
| 65 |
multi_do_frame(); // during long wait, keep packets flowing |
| 66 |
if (!vsync) |
| 67 |
SDL_Delay(1); |
| 68 |
if (unlikely(start > tv_now)) |
| 69 |
start = tv_now; |
| 70 |
if (unlikely(tv_now - start >= bound)) |
| 71 |
{ |
| 72 |
FrameStart = tv_now; |
| 73 |
break; |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
} |