From f5704b6d841a30962f1c79b5eaed3a53452288c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20H=C3=B6rdt?= <6329417-neop_@users.noreply.gitlab.com> Date: Sun, 4 Aug 2024 02:07:41 +0200 Subject: [PATCH] automatically adjust batchsize to walk as fast as possible --- main.cpp | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/main.cpp b/main.cpp index a39e826..1835dce 100644 --- a/main.cpp +++ b/main.cpp @@ -35,8 +35,10 @@ auto operator==(const SDL_Point& a, const SDL_Point& b) { return a.x == b.x && a.y == b.y; } -constexpr int width = 1000; -constexpr int height = 1000; +// constexpr int width = 1000; +// constexpr int height = 1000; +constexpr int width = 3440; +constexpr int height = 1300; template struct [[nodiscard("give this a name so SDL_Quit is called at the end" @@ -97,14 +99,34 @@ int main() { std::mt19937_64 rne(std::random_device{}()); std::uniform_int_distribution dist(0, 3); // aarrggbb?? - constexpr Uint32 walk_color = 0xff00ff00; + constexpr Uint32 bg_color = 0xffdbd7c0; + constexpr Uint32 walk_color = 0xff0d0f14; + + SDL_LockSurface(window_surface); + for (int i = 0; i < window_surface->w * window_surface->h; ++i) { + static_cast(window_surface->pixels)[i] = bg_color; + } + SDL_UnlockSurface(window_surface); + + auto batchsize = 100.0; + constexpr auto frametime_target = std::chrono::milliseconds{10}; const auto start_time = clock::now(); auto next_poll_events_time = start_time; + auto frame_start = start_time - frametime_target; + clock::duration frame_time = frametime_target; for (bool continu = true; continu;) { + { + // measure frame_time + auto now = clock::now(); + frame_time = now - frame_start; + frame_start = now; + } + + batchsize = batchsize * (0.9 + 0.1 * frametime_target / frame_time); SDL_LockSurface(window_surface); - for (auto batch = 0z; batch < 1000; ++batch) { + for (auto step = 0z; step < int(batchsize); ++step) { SDL_Point newpoint; do { newpoint = pos + directions[dist(rne)]; @@ -112,15 +134,19 @@ int main() { newpoint.y >= height); pos = newpoint; static_cast(window_surface->pixels - )[pos.x + pos.y * window_surface->h] = walk_color; + )[pos.x + pos.y * window_surface->w] = walk_color; } SDL_UnlockSurface(window_surface); + SDL_UpdateWindowSurface(window); const auto now = clock::now(); if (now >= next_poll_events_time) { - next_poll_events_time = now + std::chrono::milliseconds{100}; + next_poll_events_time = now + std::chrono::milliseconds{200}; poll_events(continu); + std::println( + "last frame_time={} batchsize={}", frame_time, batchsize + ); } }