Files
isaac-port/src/platform.cpp
T
shweetandClaude Opus 5.5 28e2e48842 Curation round 2, wave B: ItemConfig, EntityConfig, mods, Manager and the KAGE platform on SDL3; boots to LuaEngine::Init
- item_config, entity_config and mod_manager take over their families as idiomatic classes (std containers,
  unique_ptr, bitset tear flags). Every big loader reads the imported JSON: entities2.xml gives 1349 entities.
- manager.h/.cpp take over Manager (g_manager) and IsaacStartup. Members are the curated subsystems by value.
- kage_graphics, kage_input and kage_sound take over KAGE's graphics (shaders, render targets, batches, PNG through
  stb_image), input (SDL3 keyboard, mouse, gamepads) and sound (SDL3 audio, wav and stb_vorbis ogg, pitch and volume).
- source_tree.py: classes inside a namespace block in src/ headers count as taken over, and a still-generated class's
  vtable slot keeps its stub unless src/ defines that exact method.
build/isaac opens the window, sets up GL 4.6, framebuffers and PulseAudio, logs the version, and stops at
LuaEngine::Init. 522 functions taken over, boot path 156/615.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:03:39 -05:00

578 lines
23 KiB
C++

#include "platform.h"
#include "data.h"
#include "gl.h"
#include "kage_graphics.h"
#include "kage_input.h"
#include "kage_sound.h"
#include "options_config.h"
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_filesystem.h>
#include <SDL3/SDL_hints.h>
#include <SDL3/SDL_init.h>
#include <SDL3/SDL_messagebox.h>
#include <SDL3/SDL_mouse.h>
#include <SDL3/SDL_timer.h>
#include <SDL3/SDL_video.h>
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <mutex>
#include <span>
#include <utility>
constexpr const char* SAVE_FOLDER = "Binding of Isaac Repentance+";
constexpr const char* SAVE_FOLDER_ERROR = "Failed to obtain writable save data directory!";
constexpr const char* SAVE_PATHS_NOTICE =
"This file is purely informational. Changing it will have no effect on saving or loading data.\n\n";
constexpr const char* WINDOW_TITLE = "Binding of Isaac: Repentance+ v1.9.7.17";
constexpr int WINDOW_HEIGHT = 540;
constexpr int WINDOW_WIDTH = 960;
constexpr SDL_WindowFlags WINDOW_FLAGS = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE;
// The context versions GLFW was asked for, the second only when the first fails.
constexpr int GL_MAJOR_VERSIONS[] = {2, 1};
constexpr int DEPTH_BITS = 24;
constexpr int STENCIL_BITS = 8;
constexpr double CLEAR_DEPTH = -1000;
constexpr int RENDERBUFFER_MIN_SIZE = 8;
constexpr int ACTION_COUNT = 32;
constexpr int CONTROLLER_COUNT = 4;
constexpr ActionBinding EMPTY_BINDING = {-1, -1, -1, -1};
// A frame shorter than this share of FRAME_TIME is short, and this many in a row switch the pacing over.
constexpr double SHORT_FRAME_RATIO = 1.1;
constexpr int PACING_SWITCH_FRAMES = 30;
constexpr int MESSAGE_LENGTH = 1024;
constexpr int MS_PER_SECOND = 1000;
constexpr int TARGET_HZ = 60;
constexpr float REFRESH_TOLERANCE = 0.04f;
// One default binding: an input action and its button or key.
struct DefaultBinding
{
int action;
int input;
};
// The engine's own controller defaults, in its standard button numbers.
constexpr DefaultBinding CONTROLLER_DEFAULTS[] = {
{0, 0}, {0, 43947}, {1, 1}, {1, 43948}, {2, 2}, {2, 43949}, {3, 3}, {3, 43950}, {4, 4},
{4, 43951}, {5, 5}, {5, 43952}, {6, 6}, {6, 43953}, {7, 7}, {7, 43954}, {8, 8}, {9, 9},
{10, 11}, {11, 12}, {12, 15}, {13, 14}, {14, 17}, {15, 18}, {19, 15}, {20, 0}, {20, 43947},
{21, 1}, {21, 43948}, {22, 2}, {22, 43949}, {23, 3}, {23, 43950}, {24, 8}, {25, 11}, {26, 9},
{27, 12}, {28, 6}, {29, 4}, {30, 13}, {31, 10},
};
// The engine's keyboard defaults, in GLFW key numbers.
constexpr DefaultBinding KEYBOARD_DEFAULTS[] = {
{0, 65}, {1, 68}, {2, 87}, {3, 83}, {4, 263}, {5, 262}, {6, 265}, {7, 264}, {8, 69},
{9, 32}, {10, 81}, {11, 341}, {12, 80}, {13, 258}, {14, 32}, {14, 257}, {15, 256}, {19, 257},
{20, 263}, {21, 262}, {22, 265}, {23, 264}, {24, 81}, {25, 69}, {26, 88}, {27, 67}, {28, 258},
{29, 341}, {30, 342}, {31, 340}, {18, 82}, {16, 70}, {17, 77},
};
// The standard buttons whose GLFW gamepad number differs.
constexpr DefaultBinding PLATFORM_BUTTONS[] = {{17, 7}, {18, 5}};
Platform platform;
// The log file, which levels reach it, and whether the next message starts a line.
static std::mutex logMutex;
static FILE* logFile = nullptr;
static unsigned int logMask = 0;
static bool isLogLineStart = true;
// 00a5f3a0 Opens the log file, replacing any open one, with every level written to it.
void log_open(const std::string& path)
{
if (logFile) std::fclose(logFile);
logFile = std::fopen(path.c_str(), "wb");
logMask = UINT8_MAX;
}
// What a level's lines start with.
static const char* log_prefix(unsigned int flags)
{
switch (flags)
{
case LOG_INFO: return "[INFO] - ";
case LOG_NET: return "[NET] - ";
case LOG_WARN: return "[WARN] - ";
case LOG_ERROR: return "[ERROR] - ";
case LOG_ASSERT: return "[ASSERT] - ";
default: return "";
}
}
// Prints a message to stdout, and to the log file when its level is in the mask, the level's prefix at a line start.
void log_printf(LogLevel level, const char* format, ...)
{
std::lock_guard lock(logMutex);
bool isFileLogged = logFile && (logMask & level);
if ((level & UINT8_MAX) == 0 && !isFileLogged) return;
va_list args;
va_start(args, format);
va_list sizing;
va_copy(sizing, args);
std::string text = isLogLineStart ? log_prefix(level) : "";
size_t start = text.size();
text.resize(start + std::vsnprintf(nullptr, 0, format, sizing));
va_end(sizing);
std::vsnprintf(text.data() + start, text.size() - start + 1, format, args);
va_end(args);
if (level & UINT8_MAX)
{
std::fputs(text.c_str(), stdout);
std::fflush(stdout);
}
if (isFileLogged)
{
std::fputs(text.c_str(), logFile);
std::fflush(logFile);
}
if (!text.empty()) isLogLineStart = text.back() == '\n';
}
// 00a112c0 Logs finished text at a level. The game's prototype has no format arguments, so callers format first.
void KAGE_LogMessage(uint32_t flags, uint8_t* format)
{
log_printf((LogLevel)flags, "%s", (const char*)format);
}
// 00a68490 The monotonic clock in nanoseconds.
uint64_t GetTimeNs()
{
return (uint64_t)((double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency() * SDL_NS_PER_SECOND);
}
// Creates a folder, showing the game's error box when it is not there afterwards.
static void folder_create(const std::string& path, const char* error)
{
std::error_code result;
char message[MESSAGE_LENGTH];
std::filesystem::create_directory(path, result);
if (std::filesystem::is_directory(path, result)) return;
std::snprintf(message, sizeof(message), error, path.c_str());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message, nullptr);
}
// 009a9510 Finds the save folder (SDL's per-user folder for the game) and the mods and mod data folders, removes the
// mods folder older versions kept with the saves, moves loose online logs into online_logs/desyncs/ and notes the
// folders in savedatapath.txt.
// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here. Mod data goes with saves.
void Platform::directories_load()
{
char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER);
userDataDirectory = prefPath ? prefPath : "";
SDL_free(prefPath);
if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr);
modsDirectory = dataDirectory + "mods/";
modsSaveDirectory = userDataDirectory + "data/";
folder_create(modsDirectory, "Modding data path %s is not a writable directory!");
folder_create(modsSaveDirectory, "Modding save data path %s is not a writable directory!");
std::error_code result;
std::filesystem::remove_all(userDataDirectory + "mods/", result);
std::string onlineLogs = userDataDirectory + "online_logs/";
std::string desyncs = onlineLogs + "desyncs/";
if (!std::filesystem::exists(desyncs, result))
{
std::filesystem::create_directory(desyncs, result);
for (const auto& entry : std::filesystem::directory_iterator(onlineLogs, result))
std::filesystem::rename(entry.path(), std::filesystem::path(desyncs) / entry.path().filename(), result);
}
FILE* info = std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w");
if (!info) return;
std::fputs(SAVE_PATHS_NOTICE, info);
std::fprintf(info, "Save Data Path: %s\n", userDataDirectory.c_str());
std::fprintf(info, "Modding Data Path: %s\n", modsDirectory.c_str());
std::fclose(info);
}
// The bindings a table of defaults gives each action, in table order, up to BINDING_SLOTS each.
static std::vector<ActionBinding> bindings_build(std::span<const DefaultBinding> defaults)
{
std::vector<ActionBinding> bindings(ACTION_COUNT, EMPTY_BINDING);
for (DefaultBinding binding : defaults)
{
int* slot = std::ranges::find(bindings[binding.action], -1);
if (slot == bindings[binding.action].end()) log_printf(LOG_ASSERT, "Mapping slot overflow\n");
else *slot = binding.input;
}
return bindings;
}
// 004307c0 Sets the engine's default input bindings, the controller's in GLFW's button numbers, before KAGE starts.
// Its window parameters are this file's constants. Its Epic Online Services keys and options.ini's EnableEpicOverlay
// are online, and its heap size has no heap to size, so they are left out.
void Platform::bindings_load()
{
if (isEngineInitialized)
return log_printf(LOG_ASSERT, "SetEngineParameters must be called before calling KAGE::Initialize\n");
std::vector<DefaultBinding> controller(std::begin(CONTROLLER_DEFAULTS), std::end(CONTROLLER_DEFAULTS));
for (DefaultBinding& binding : controller)
for (DefaultBinding button : PLATFORM_BUTTONS)
if (binding.input == button.action) binding.input = button.input;
bindings = {bindings_build(controller), bindings_build(KEYBOARD_DEFAULTS), CONTROLLER_COUNT};
}
// 00a5f0e0 Seeds rand from the clock in milliseconds, then starts KAGE: graphics, sound, input and video in turn,
// stopping at the first that fails (the game carries on either way).
// 00a710a0 (merged) Steam, EOS, the custom heap, the packed archives' mount points (resources/ is read directly), the
// multiplayer threads and the Windows timer and power settings are left out: SDL keeps the display awake itself.
// The OpenAL Soft device hooks after the sound manager have no place on SDL audio.
// 00a8c430 The services manager that came last is left out: theoraplayer (no cutscene video yet), the Steam checks,
// the default profile icon and the user profile lock are all for video or online play.
void Platform::engine_init()
{
std::srand((unsigned int)(GetTimeNs() / SDL_NS_PER_MS));
if (isEngineInitialized) log_printf(LOG_ASSERT, "KAGE has already been initialized\n");
if (!KAGE::Graphics::manager.Init()) return;
KAGE::Sound::manager.Init();
if (!KAGE::Input::manager.Init()) return;
isEngineInitialized = true;
}
// 00a71770 Shuts KAGE down: input, sound and graphics, then the framebuffer and the window.
// Its EOS release, log closing, compressor, multiplayer threads, video manager and heaps have nothing here to free.
void Platform::engine_shutdown()
{
KAGE::Input::manager.Shutdown();
KAGE::Sound::manager.Shutdown();
KAGE::Graphics::manager.Shutdown();
gl.BindFramebuffer(GL_FRAMEBUFFER, 0);
gl.DeleteFramebuffers(1, &framebuffer);
gl.DeleteRenderbuffers(1, &depthRenderbuffer);
SDL_GL_DestroyContext(context);
SDL_DestroyWindow(window);
context = nullptr;
window = nullptr;
isEngineInitialized = false;
}
// Opens the window at its default size with its GL context and shows it, as Graphics::Manager::Init began.
bool Platform::window_open()
{
if (!SDL_Init(SDL_INIT_VIDEO)) log_printf(LOG_ASSERT, "SDL failed to initialize: %s\n", SDL_GetError());
window_size_set({WINDOW_WIDTH, WINDOW_HEIGHT});
viewportSize = windowSize;
if (!window_create()) return false;
SDL_ShowWindow(window);
SDL_RaiseWindow(window);
return true;
}
// Shows the finished frame, as glfwSwapBuffers.
void Platform::window_swap()
{
SDL_GL_SwapWindow(window);
}
// 00a19df0 Creates the window hidden, with an OpenGL 2.0 compatibility context (1.0 if that fails), and the
// framebuffer the renderer draws the game into.
// The Win32 icon and the maximize box it removes have no SDL counterpart.
bool Platform::window_create()
{
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, DEPTH_BITS);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, STENCIL_BITS);
window = SDL_CreateWindow(WINDOW_TITLE, windowSize.width, windowSize.height, WINDOW_FLAGS);
for (int major : GL_MAJOR_VERSIONS)
{
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
if (window && (context = SDL_GL_CreateContext(window))) break;
}
// The original carries on without a context and crashes in its first GL call. This stops instead.
if (!context)
{
log_printf(LOG_ASSERT, "Failed to create OpenGL window / context: %s\n", SDL_GetError());
return false;
}
gl_load();
log_printf(LOG_INFO, "OpenGL version %s\n", (const char*)gl.GetString(GL_VERSION));
log_printf(LOG_INFO, "GLSL version %s\n", (const char*)gl.GetString(GL_SHADING_LANGUAGE_VERSION));
if (!gl.GenFramebuffers)
{
log_printf(LOG_ERROR, "glGenFramebuffers is NULL!\n");
return false;
}
gl.GenFramebuffers(1, &framebuffer);
log_printf(LOG_INFO, "Framebuffer ID: %d\n", framebuffer);
gl.BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
depth_renderbuffer_update(RENDERBUFFER_REBUILD);
gl.BindFramebuffer(GL_FRAMEBUFFER, 0);
SDL_GetWindowPosition(window, &windowPosition.x, &windowPosition.y);
state_reset();
return true;
}
// 00a19b60 (00a184e0) Puts back the GL state the renderer expects: the vsync setting, blending, depth testing toward
// the viewer from a cleared depth of -1000, and back faces culled.
void Platform::state_reset()
{
vsync_apply();
gl.Enable(GL_BLEND);
gl.Enable(GL_DEPTH_TEST);
gl.Enable(GL_CULL_FACE);
gl.ClearDepth(CLEAR_DEPTH);
gl.DepthFunc(GL_GREATER);
gl.CullFace(GL_BACK);
}
// 00a1a470 Swaps on the display's refresh when vsync is on.
void Platform::vsync_apply()
{
SDL_GL_SetSwapInterval(isVsync ? 1 : 0);
}
// (00a19340, 00a193c0) The window's drawable size in pixels.
Size Platform::framebuffer_size_get()
{
Size size;
SDL_GetWindowSizeInPixels(window, &size.width, &size.height);
return size;
}
// 00a18750 Gives the framebuffer a depth renderbuffer at the powers of two at or above the drawing size, 8 at least,
// keeping the one it has while that is big enough.
// The drawing size falls back to the bound render target's, then the window's.
void Platform::depth_renderbuffer_update(RenderbufferMode mode)
{
int width = drawingSize.width > 0 ? drawingSize.width : KAGE::Graphics::manager.target_width_get();
int height = drawingSize.height > 0 ? drawingSize.height : KAGE::Graphics::manager.target_height_get();
if (mode == RENDERBUFFER_KEEP && depthRenderbuffer != 0)
{
int currentHeight = 0;
int currentWidth = 0;
gl.BindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
gl.GetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &currentWidth);
gl.GetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &currentHeight);
if (width <= currentWidth && height <= currentHeight) return;
}
if (depthRenderbuffer != 0) gl.DeleteRenderbuffers(1, &depthRenderbuffer);
width = (int)std::bit_ceil((unsigned int)std::max(width, RENDERBUFFER_MIN_SIZE));
height = (int)std::bit_ceil((unsigned int)std::max(height, RENDERBUFFER_MIN_SIZE));
int previous = 0;
gl.GetIntegerv(GL_FRAMEBUFFER_BINDING, &previous);
gl.BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
gl.GenRenderbuffers(1, &depthRenderbuffer);
log_printf(LOG_INFO, "Renderbuffer ID: %d size %dx%d\n", depthRenderbuffer, width, height);
gl.BindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
gl.RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
gl.FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
gl.BindFramebuffer(GL_FRAMEBUFFER, previous);
}
// (00a19bc0, 00a186f0) Sets the GL viewport to the game's viewport, at its offset when it has one.
void Platform::viewport_reset()
{
SDL_FPoint offset = isViewportOffset ? viewportOffset : SDL_FPoint{};
gl.Viewport((int)offset.x, (int)offset.y, viewportSize.width, viewportSize.height);
}
// 00a19450 Resizes the window unless it has that size already. In fullscreen it keeps the size for later and warns.
void Platform::window_size_set(Size size)
{
if (size == windowSize) return;
windowSize = size;
if (isFullscreen) log_printf(LOG_WARN, "Setting size of window while in fullscreen, is this intended?\n");
else if (window) SDL_SetWindowSize(window, size.width, size.height);
}
// Moves the window, as GLFW's glfwSetWindowPos.
void Platform::window_position_set(SDL_Point position)
{
SDL_SetWindowPosition(window, position.x, position.y);
}
// 00a196b0 Switches between the window and fullscreen, at the display's own mode when exclusive, then tells the size
// listeners and resets the viewport, projection and depth buffer. The cursor hides in fullscreen.
// The original fakes borderless fullscreen with a topmost window a pixel wider than the display. SDL's desktop
// fullscreen does that job.
void Platform::fullscreen_set(FullscreenMode mode)
{
bool isWanted = mode != FULLSCREEN_OFF;
if (isWanted == isFullscreen) return;
const SDL_DisplayMode* displayMode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(window));
isFullscreen = isWanted;
SDL_SetWindowFullscreenMode(window, mode == FULLSCREEN_EXCLUSIVE ? displayMode : nullptr);
SDL_SetWindowFullscreen(window, isFullscreen);
if (!isFullscreen)
{
SDL_SetWindowSize(window, viewportSize.width, viewportSize.height);
window_position_set(windowPosition);
}
SDL_ShowWindow(window);
SDL_RaiseWindow(window);
SDL_SyncWindow(window);
Size size;
SDL_GetWindowSize(window, &size.width, &size.height);
for (auto& listener : sizeListeners) listener(size);
viewport_reset();
KAGE::Graphics::manager.update_projection();
depth_renderbuffer_update(RENDERBUFFER_KEEP);
isFullscreen ? SDL_HideCursor() : SDL_ShowCursor();
}
// Takes the window's events as GLFW's callbacks did: closing asks the game to quit, a new size (00a19bf0), position
// (00a19ca0) or focus (00a19d40) goes to its listeners and resets what depends on it, keys and gamepads go to input.
// Win32's topmost-while-focused fullscreen window has no SDL counterpart.
void Platform::events_poll()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_EVENT_QUIT:
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
isQuitRequested = true;
break;
case SDL_EVENT_WINDOW_RESIZED:
if (event.window.data1 == 0 || event.window.data2 == 0) break;
windowSize = {event.window.data1, event.window.data2};
for (auto& listener : sizeListeners) listener(windowSize);
viewport_reset();
depth_renderbuffer_update(RENDERBUFFER_KEEP);
KAGE::Graphics::manager.update_projection();
break;
case SDL_EVENT_WINDOW_MOVED:
for (auto& listener : positionListeners) listener({event.window.data1, event.window.data2});
if (isFullscreen) break;
windowPosition = {event.window.data1, event.window.data2};
viewport_reset();
break;
case SDL_EVENT_WINDOW_FOCUS_GAINED:
case SDL_EVENT_WINDOW_FOCUS_LOST:
for (auto& listener : focusListeners) listener(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED);
break;
case SDL_EVENT_KEY_DOWN:
case SDL_EVENT_KEY_UP:
KAGE::Input::manager.key_set(event.key.scancode, event.key.down);
break;
case SDL_EVENT_GAMEPAD_ADDED:
KAGE::Input::manager.gamepad_add(event.gdevice.which);
break;
case SDL_EVENT_GAMEPAD_REMOVED:
KAGE::Input::manager.gamepad_remove(event.gdevice.which);
break;
}
}
}
// 00a266a0 Seconds since the platform started, as glfwGetTime.
double Platform::time_get()
{
return (double)SDL_GetTicksNS() / SDL_NS_PER_SECOND;
}
// Starts a frame and returns the frame rate the time since the last one makes, rounded. A long run of short frames
// (vsync on a faster display) forces the 60 Hz pacing on.
int Platform::frame_begin()
{
double now = time_get();
double frameTime = now - frameStart;
frameStart = now;
if (FRAME_TIME / frameTime <= SHORT_FRAME_RATIO) shortFrameCount = 0;
else if (++shortFrameCount > PACING_SWITCH_FRAMES)
{
isPacingForced = true;
fullFrameCount = 0;
}
return (int)std::floor(1 / frameTime + 0.5);
}
// Holds the frame to 60 Hz unless vsync paces it: sleeps the whole milliseconds left but one, then spins. A long run
// of frames with nothing left to sleep turns the forced pacing back off.
// The original spins without sleeping while a cutscene video is behind (0095dee0). No video plays yet.
void Platform::frame_wait()
{
if (!isPacingForced && isVsync) return;
int sleepMs = std::max((int)((FRAME_TIME - (time_get() - frameStart)) * MS_PER_SECOND) - 1, 0);
if (sleepMs > 0)
{
fullFrameCount = 0;
SDL_DelayNS(sleepMs * SDL_NS_PER_MS);
}
else if (++fullFrameCount > PACING_SWITCH_FRAMES)
{
isPacingForced = false;
shortFrameCount = 0;
}
while (time_get() - frameStart < FRAME_TIME) {}
}
// Applies one window option, as the OptionsConfig setters did: windowed again, the window takes back its saved size,
// position and cursor. Vsync stays off for the session on a display not running at a multiple of 60 Hz.
void window_apply(OptionsConfig& options, WindowSetting setting)
{
switch (setting)
{
case WINDOW_CURSOR:
options.isMouseControlEnabled ? SDL_HideCursor() : SDL_ShowCursor();
break;
case WINDOW_FULLSCREEN:
if (!options.isFullscreen) platform.fullscreen_set(FULLSCREEN_OFF);
else platform.fullscreen_set(options.isExclusiveFullscreen ? FULLSCREEN_EXCLUSIVE : FULLSCREEN_BORDERLESS);
if (options.isFullscreen) break;
platform.window_size_set({options.windowWidth, options.windowHeight});
platform.window_position_set({options.windowPosX, options.windowPosY});
window_apply(options, WINDOW_CURSOR);
break;
case WINDOW_POSITION:
platform.window_position_set({options.windowPosX, options.windowPosY});
break;
case WINDOW_VSYNC:
{
const SDL_DisplayMode* display = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(platform.window));
int hz = display ? (int)display->refresh_rate : 0;
float cycles = 0;
float fraction = std::modf((float)hz / TARGET_HZ, &cycles);
bool isVsync = options.isVsyncEnabled;
if (isVsync && std::min(fraction, 1 - fraction) > REFRESH_TOLERANCE)
{
log_printf(LOG_INFO, "Display Hz: %d, Target: 60.. disabling vsync for this session.\n", hz);
isVsync = false;
}
if (isVsync == platform.isVsync) break;
platform.isVsync = isVsync;
platform.vsync_apply();
break;
}
}
}
// The window's current size, which reset options take as theirs.
void window_size_load(OptionsConfig& options)
{
SDL_GetWindowSize(platform.window, &options.windowWidth, &options.windowHeight);
}