Files
fs2open.github.com/code/osapi/osapi.cpp
T
b26b9cf743 Add Vulkan rendering backend, with HDR10 output and raytraced shadows (#7554)
* Shadow overhaul round 2: PCSS, dynamic cascades, cockpit/instanced shadows

Squashed snapshot of lafiel/shadow_overhaul_2's continuation work
(d3922aa87..010f9d2d9), which has no separate upstream PR of its own.

* Add Vulkan rendering backend

Squashed snapshot of the Vulkan backend as vendored into this branch
(ce2d1e85f..6ce539463, authored by Mara van der Laan with build/CI
fixes by Taylor Richards). This work has its own upstream PR #7553
(notimaginative:vulkan-pr-new) and is not otherwise original to true-hdr.

* Add true HDR output, RT shadows, and PCSS shadows for Vulkan

Squashed snapshot of true-hdr's own integration work: true HDR
framebuffer output, wiring the shadow overhaul into the Vulkan
backend (raytraced + cascaded shadow maps), logging refactors, log
filter UI, and CI/build fixes.

* refactor: update Vulkan logging calls to use `nprintf` for scoped logging

* fix: correct shadow cascade count in Vulkan logging calls

* fix: fall back to PATH-resolved ccache when CCACHE_PATH is stale

CI hardcodes /usr/local/bin/ccache, but macOS runners on Apple Silicon
hosts install Homebrew (and ccache) under /opt/homebrew instead,
causing all four Mac configs to fail with "No such file or directory".

* Fix vulkan texture readback to correctly handle transparent pipelines

* Put the pixel swizzles into a util file

* OOB safety check

* Fix fog handling

* Fix MSAA in Vulkan

* fix: enable SMAA for vulkan

* adapt the post-processing AA shaders to hdr

* fix clang-tidy warnings: concatenate nested namespaces, static methods

pixel_swizzle.{h,cpp}: collapse `namespace graphics { namespace util {`
into `namespace graphics::util {` (modernize-concat-nested-namespaces).

VulkanState.h/VulkanDraw.h: getClearColor()/setClearColor() only touch
gr_screen and other globals, no instance state, so make them static
(readability-convert-member-functions-to-static) and drop the
top-level const on getClearColor()'s return type
(readability-const-return-type).

* fix clang-tidy warning

* Extend raytraced shadows to all directional lights

RT shadows previously only shadowed the first directional light in the
scene, even though multi-sun missions push more than one directional
light into the engine. The TLAS raytraced shadows query against is
already light-agnostic, so this extends both the deferred lighting
pass and the forward MODEL shader to shadow every directional light
(capped by a new Max Raytraced Shadow Lights option, configurable via
the in-game Options menu or the Lab's Scene rendering options).

Cascaded shadow maps are untouched: they're built for a single light
only, so the deferred pass still limits itself to one shadowed
directional light whenever CSM (not raytracing) is the active method.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016DA6JHJ3twz2oHGQcZ1Udc

* refactor: improve shader flag handling and render target finalization in Vulkan backend

- Consolidate shader flag setup logic in VulkanPostProcessingLighting to simplify configuration.
- Fix dead field usage in VulkanDraw by ensuring correct image view selection for environment maps.
- Add mip chain regeneration in VulkanRenderer::endRenderTarget to ensure correct mip levels for cubemaps.

* fix: ensure correct mip chain initialization in cubemap rendering

- Add mip chain generation to VulkanDraw for cubemaps with multiple mip levels.
- Fix potential issue with uninitialized mip levels above level 0 in deferred-f.sdr sampling paths.

* fix: don't crash on startup when environment locale is unavailable

std::locale("") pulls in the process's environment locale categories
(LC_CTYPE, LC_MONETARY, LC_PAPER, etc.), and throws std::runtime_error
if any of them names a locale not installed on the host (e.g.
mismatched regional-format overrides). Since SCP_default_locale is
constructed during static initialization, before main() and before any
of our own exception handling exists, an uncaught throw here aborted
the whole process before the game even started. Fall back to the
classic "C" locale instead, which is sufficient since this locale is
only ever used for ASCII case-folding (SCP_toupper/tolower/isdigit).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* `feat: add raytraced shadows for local lights and optimize TLAS management`

* Make the Commandline authoritative for -res and -vulkan / -opengl

* address BMagnu's comments on the original PR

* update prebuilt version hash to 62c89ef6

* refactor: standardize graphics API handling and document Vulkan limitations in qtFRED

- Updated `AboutDialogModel.cpp` to use `GraphicsAPI` enum for better clarity.
- Ensured qtFRED falls back to OpenGL when Vulkan is requested.
- Added detailed documentation in `qtfred/README.md` regarding Vulkan backend limitations and requirements.

* chore: include cmdline library in main and mission management modules

* docs: add known issue for blank render viewport under Wayland in README.md

* fix CI issues

* chore: add `GR_DEBUG_SCOPE` markers across Vulkan post-processing and rendering paths for improved debugging

* feat: improve Vulkan HDR pipeline with separate encode paths for SDR and HDR10

- Added an HDR10-specific output encode pass in `VulkanRenderer` and `VulkanPostProcessor` that applies PQ/BT.2020 transfer.
- Introduced an optimized SDR fallback path with direct blit support for devices that can skip shader draws.
- Updated `m_sceneLdrCompressed` to provide [0,1]-clamped proxies for HDR edge detection.
- Refactored `copyImageToImage` and added `blitImageToImage` to allow format conversions and optimized transfers.
- Replaced `hdr_mode` with explicit HDR10 flags and data structures for clearer state handling.

* refactor: encapsulate SMAA processing and refactor VulkanPostProcessor

- Moved SMAA-specific logic into `VulkanSMAA` class for better separation of concerns.
- Simplified `initSMAA`, `shutdownSMAA`, and `executeSMAA` logic by leveraging `VulkanLDR` and `PostProcessContext` abstractions.
- Improved initialization and cleanup code with clearer resource lifecycle management.
- Updated debug markers and messages to reference `VulkanSMAA`.
- Enhanced flexibility of fullscreen triangle rendering API with additional parameters (`sampleCount`, `bindGlobalSet`).

* Update Vulkan porting credits in AboutDialogModel

* fix CI issues again

* fix: correct Y-flip in viewport setup for Vulkan light volumes

- Adjusted viewport height to negative value to account for G-buffer render pass's negative Y-axis convention.
- Ensured proper alignment of point and tube light volumes with actual light positions.

* feat: add user-adjustable gamma correction to SDR and HDR10 output paths

- Added gamma correction to HDR10 path, applying user settings before PQ/BT.2020 encode.
- Replaced the SDR blit-only path with an encode pass that applies gamma correction, ensuring consistent behavior across devices.
- Refactored VulkanPostProcessor and associated shaders to support gamma slider adjustments for both SDR and HDR output.

* fix: ensure proper uniform and cull mode setup for Vulkan sphere rendering

- Added uniform buffer setup and default material uniforms in `vulkan_draw_sphere`.
- Disabled face culling in material definition for sphere rendering to align behavior with OpenGL.

* Ensure memory flushes after UBO updates and add explicit pipeline barrier for MoltenVK compatibility.

* fix: add clear pass for SMAA edge detection to prevent persistent artifacts

* feat: add Vulkan debug-utils messenger, opt-in sync validation, frame diagnostics

Groundwork for the renderer-review fix series (.agents/plans/
vulkan-renderer-review-fixes.md, Phase 0):

- Register a VK_EXT_debug_utils messenger (preferred) instead of only the
  deprecated VK_EXT_debug_report callback, which is kept as a fallback for
  loaders without debug-utils. The messenger config is also chained into
  instance creation so vkCreateInstance-time messages are captured.
  Validation errors/warnings now go to the main log via mprintf.
- New -gr_sync_validation cmdline flag (implies -gr_debug): chains
  VkValidationFeaturesEXT with synchronization validation into instance
  creation when VK_LAYER_KHRONOS_validation is available. This is the
  regression net for the synchronization fixes in the following commits.
- Frame stats now report descriptor sets/writes allocated per frame and the
  total pipeline count (descriptor-manager counters; DescriptorWriter::flush
  moved out-of-line to report into the manager).

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: unify Vulkan render-pass begins, clamp in-pass clears, add per-frame UBO ring

Phase 1 of the renderer-review fix series: shared helpers that the
correctness fixes build on.

- New VulkanRenderer::beginTrackedRenderPass(PassBeginDesc): every render-pass
  begin on the frame command buffer now records vkCmdBeginRenderPass and
  updates the state tracker (pass, color attachment count, sample count,
  render area, viewport) in one place. Converted: setupFrame,
  beginSceneRendering (both branches), resumeSceneRendering,
  endSceneRendering, beginRenderTarget (viewport kept for gr_set_viewport),
  resumeSwapChainPass, plus new resumeScenePassAfterCopy() shared by
  copyEffectTexture/copySceneDepthForParticles and
  rebeginSwapChainPassAfterReadback() shared by both readbackFramebuffer
  exits (~200 lines of duplicated begin/clear/viewport blocks removed).
- The state tracker records the active render area; all four
  vkCmdClearAttachments sites clamp their rects against it and skip empty
  results. Previously gr_screen-sized clear rects could exceed a smaller
  off-screen render target's render area, which is invalid API usage.
- New PerFrameUboRing utility (VulkanPerFrameUbo.h/.cpp): a persistently
  mapped uniform buffer with one slot region per frame in flight and a
  self-flushing alloc(). Used by the next commit to fix the cross-frame
  UBO races.

Deliberate behavior deltas (all safe-direction): the helper always sets
colorAttachmentCount/sampleCount (some sites previously inherited stale
values), and resumeSwapChainPass/resumeSceneRendering now also reset the
standard flipped viewport instead of leaving the previous one.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: eliminate Vulkan cross-frame UBO/buffer races, make gr_sync honest

Phase 2 of the renderer-review fix series: with two frames in flight, several
host-visible resources were rewritten by the CPU while the previous frame's
GPU work could still be reading them.

- The post-processing scratch UBO is now a PerFrameUboRing (per-frame-in-
  flight slot regions, persistently mapped, self-flushing alloc). All the
  per-pass map/unmap/cursor bookkeeping in bloom/LDR/fog/SMAA is deleted;
  the cursor resets exactly once per frame via the new
  VulkanPostProcessor::beginFrame() hook in setupFrame.
  This also fixes two latent bugs: (a) fog consumed scratch slots mid-scene
  and bloom's later same-frame cursor reset overwrote them before submission
  whenever fog+bloom were both active; (b) volumetric_fog_data (288 bytes)
  overflowed the 256-byte slots - the memcpy spilled into the neighboring
  slot and the shader's bound range ended before the aspect/fov/noise
  fields. Slots are now 512 bytes (static_assert at the fog call site) and
  the per-frame budget is 32 slots.
- The dedicated tonemap, output-encode, and MSAA-resolve UBOs (each a single
  instance rewritten per frame, i.e. racy; the MSAA one also never flushed)
  are deleted entirely - those passes build their structs on the stack and
  allocate from the scratch ring.
- Static-buffer rewrites orphan instead of racing: getVkBuffer() stamps a
  last-used frame number, and a full-content updateBufferData() on a Static
  buffer used within the last MAX_FRAMES_IN_FLIGHT frames defers the old
  VkBuffer to the deletion queue and writes a fresh one. Offset writes
  (GPU-heap appends to fresh regions) and PersistentMapping buffers (the
  engine holds their mapped pointer and syncs via gr_sync) are exempt.
- gr_sync_wait now honors its contract: VulkanRenderFrame::waitForFinish
  takes a timeout and reports expiry without consuming the fence;
  VulkanRenderer::waitForFrame returns false for fences taken during the
  still-recording frame (previously it waited on a stale or idle slot and
  reported success) and resolves the frame->slot mapping correctly. This
  makes UniformBufferManager's segment-fence throttling actually protective
  on Vulkan for the first time.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Refactor framebuffer and target lifecycle: centralized creation/resizing logic, improved resource management across Vulkan post-processing subsystems.

* Improve Vulkan cross-frame sync with explicit access masks and validation updates

- Unified Vulkan validation flag handling in setup, separating engine debug output from synchronization validation.
- Specified access masks and stage flags to address cross-frame WRITE_AFTER_WRITE vulnerabilities, notably in G-buffer, post-processing, and MSAA resolve paths.
- Adjusted subpass dependencies and image layout transitions to prevent read-after-write and write-after-write hazards, detected using `-gr_sync_validation`.
- Fixed uniform buffer and barrier transitions to ensure proper ordering in render passes across frames.

* Refactor Vulkan render-pass dependencies and sync stages for clarity and future testing

- Clarified dependency logic for cross-pass and cross-frame synchronization, ensuring explicit stage and access flag comments match observed behavior.
- Adjusted subpass dependencies to decouple render-pass compatibility definitions from dependency assumptions.
- Highlighted MoltenVK-specific issues and retained workarounds with notes for re-testing on macOS hardware.
- Updated synchronization barriers and validation notes to address historical inconsistencies across platforms.

* Remove transfer queue support; consolidate all operations into the graphics queue

- Removed transfer queue handling, simplifying buffer and queue logic to use the graphics queue for all transfer operations.
- Updated buffer sharing modes and removed related code paths and parameters for transfer queue families.
- Introduced exclusive buffer access, noting async transfer and queue ownership transfers are future work.
- Limited enabled device features to only those actively used by the renderer, reducing unnecessary feature requests (e.g., robustBufferAccess).

* Refactor frame advancement and descriptor management in VulkanRenderer

- Removed `endFrame()` from `VulkanDescriptorManager`, replacing it with `setCurrentFrame(frameIndex)` for explicit frame synchronization.
- Centralized frame index advancement within `VulkanRenderer` to ensure consistency across components.
- Invalidated cached descriptor set bindings at render-pass boundaries to handle raw recorder staleness correctly.
- Optimized pipeline descriptor rebind logic by removing redundant clears during pipeline changes.

* Refactor `PipelineConfig::hash` and Global descriptor set management for improved hashing and memoization efficiency

- Replaced inefficient shift-based hashing in `PipelineConfig::hash` with a robust `hashCombine` strategy to minimize bucket collisions.
- Introduced `maskBits` helper to streamline bitmask creation for boolean fields.
- Implemented memoization for Global (Set 0) descriptor sets, reducing redundant rebuilds across frames and improving performance.
- Added dirty state tracking (`m_globalSetDirty`) and invalidation logic for Global set updates following relevant input changes (e.g., TLAS or UBO modifications).

* Refactor Vulkan post-processing output logic: extracted shared `encodeToSwapChainPass` method to streamline HDR and SDR output paths.

* Optimize Vulkan descriptor set management with per-frame memoization

- Added memoization for Material (Set 1) and PerDraw (Set 2) descriptor sets to reuse cached sets across frames if inputs remain unchanged.
- Implemented precise input tracking for Material and PerDraw descriptor sets to detect and rebuild only when necessary.
- Reduced redundant Vulkan descriptor allocations and writes, improving performance on repeated or batched draw calls.

* Fix Vulkan access masks for G-buffer and scene pass transitions

- Added `eColorAttachmentRead` to access masks in multiple barriers to ensure proper synchronization for load operations (e.g., `loadOp=eLoad`) across render passes.
- Prevented `READ_AFTER_WRITE` synchronization validation issues in deferred and multi-pass rendering scenarios.
- Updated comments to clarify the reasoning behind the access mask changes and load dependencies.

* Refactor Vulkan resource management and indexed draw logic

- Consolidated destruction queue methods in `VulkanDeletionQueue` using a shared `queueHandle` template to reduce redundancy.
- Introduced `ModelDrawParams` structure and `computeModelDrawParams` function to unify indexed draw parameters for models and shadows.
- Simplified draw logic by eliminating repeated calculation of indexed draw parameters and improving code reuse.

* Add `releaseAnimationSlotRef` for ref-count handling of shared animation texture arrays

- Introduced `releaseAnimationSlotRef` to manage reference counting for shared animation texture-array slots, preventing premature destruction of shared resources.
- Updated `flushTextures` and related methods to integrate `releaseAnimationSlotRef` for shared slot cleanup.
- Refactored staging buffer creation into `createStagingBuffer` for 3D texture uploads and shared path consistency.
- Enhanced texture upload logic with improved tracking and logging for re-upload cases, aiding preloading gap analysis.
- Added instrumentation for on-demand mid-frame texture uploads in `FrameStats`.

* Refactor Vulkan resource and texture management, extend debug logging

- Updated smart pointer usage for consistency across Vulkan resource managers (`std::make_unique`).
- Removed redundant `cubeImageView` member and related cleanup logic; unified sampling view management.
- Added per-instance debug log counters (avoiding static state) for Vulkan texture uploads and bindings, improving visibility during initialization and run-time.
- Optimized `VulkanRenderer` property/feature getters by caching physical device properties and features during device creation.
- Improved memory region flushing logic for out-of-date offsets, aligning with Vulkan Memory Allocator behavior.
- Refactored render pass state tracking to reapply dynamic state reliably after mid-frame render passes.
- Enhanced validation and error handling for mismatched update texture formats.

* fix CI build warning

* Fix on-demand YUV texture locking and set alpha uniform for movie rendering in Vulkan

- Corrected bitmap lock type from `BMP_TEX_OTHER` to `BMP_AABITMAP` for YUV textures during on-demand loading.
- Updated movie rendering to bind alpha from the `MovieData` UBO (set 2, binding 4) for Vulkan, aligning behavior with OpenGL implementation.

* revert inadvertent changes introduced by a squash commit

* address ci issues

* remove wip stuff from code comments that make no sense to people who aren't me

* Remove unused LD_LIBRARY_PATH export and fix shader shadow map sampling.

* Refactor batched rendering uniform setup in Vulkan

- Removed unused fields from `genericData` uniform block, simplifying shader definitions.
- Updated Vulkan material uniform handling to align with OpenGL's batched rendering logic.
- Introduced `batched_data` struct for streamlined UBO updates, improving maintainability and clarity.

* Add `-hdr` command-line option for HDR nits configuration

- Introduced `-hdr` parameter to set paper white and peak luminance in nits, overriding in-game HDR settings.
- Added input validation with error feedback for incorrect format.

* Remove unused `MODEL_SDR_FLAG_SHADOW_MAP` macro from shader flags

* clean up unrelated changes

* Invalidate Vulkan state tracker bindings after external command buffer modifications

- Added `invalidateExternalBindings()` to `VulkanStateTracker` to handle stale pipelines, descriptors, and dynamic states caused by external Vulkan commands (e.g., ImGui renders mid-pass).
- Updated ImGui rendering flow to call `invalidateExternalBindings()` post-draw, ensuring consistent pipeline state for subsequent engine renders.
- Adjusted image usage flags to account for `eTransferSrc` in texture readbacks.
- Fixed barrier `dstAccessMask` and pipeline stage flags to ensure proper synchronization for image transitions.

* Add a few more generically useful lines to the log

* Simplify Qt deployment logic and improve handling for system-installed Qt on Linux

* add cmdline headers to make qtFred compile

* use VK_KHR_synchronization2 for sync and barrier purposes

* Simplify and clean up Qt deployment logic in CMake for qtfred

* update get_bitmap_from_texture to match the new API

* Enhance `-hdr` command-line option to force HDR output and support optional nits configuration with improved input validation and overrides.

* Improve Vulkan robustness, add device feature checks, and refine memory/logging.

- Added depth clamping support gated by device feature checks, with fallback where unsupported.
- Improved deferred lighting UBO overflow handling with user-accessible warnings and buffer size adjustments.
- Enhanced Vulkan logging for validation, allocation, and debugging:
  - Automatic logging for descriptor pool exhaustion/fragmentation.
  - Vertex format and resource destruction checks.
  - Notifications for generic layout transitions and volumetric texture uploads.
- Consolidated shader logic to ensure Vulkan and OpenGL parity.

* Remove HDR10 encode shader and consolidate gamma correction logic for SDR and HDR10. Replace `Verify` assertions with `Assert`

* Add braces to conditional in object lighting logic for clarity

* Refine Vulkan memory allocation checks with `Verification` for improved error handling and messaging.

* Refine VulkanBuffer resize logic to preserve contents with CPU-side copy and add safeguards for non-coherent memory scenarios.

* Add detailed comments explaining descriptor array capacity constants in VulkanDescriptorManager

* Gate shadow support on depth clamp feature availability and clarify its necessity with improved comments.

---------

Co-authored-by: BMagnu <[email protected]>
Co-authored-by: Mara van der Laan <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-07-21 16:58:21 +00:00

843 lines
23 KiB
C++

/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "freespace.h"
#include "cmdline/cmdline.h"
#include "gamesequence/gamesequence.h"
#include "globalincs/pstypes.h"
#include "parse/parselo.h"
#include "graphics/openxr.h"
#include "io/joy_ff.h"
#include <fcntl.h>
#include <utf8.h>
#include "imgui.h"
#include "backends/imgui_impl_sdl.h"
#ifdef SCP_UNIX
#include <sys/stat.h>
#elif defined(WIN32)
#include <sys/stat.h>
#include <sys/types.h>
#endif
namespace
{
const char* ORGANIZATION_NAME = "HardLightProductions";
const char* APPLICATION_NAME = "FreeSpaceOpen";
SCP_string preferencesPath;
bool checkedLegacyMode = false;
bool legacyMode = false;
SCP_vector<std::unique_ptr<os::Viewport>> viewports;
os::Viewport* mainViewPort = nullptr;
SDL_Window* mainSDLWindow = nullptr;
SCP_string getPreferencesPath()
{
// Lazily initialize the preferences path
if (preferencesPath.empty()) {
//Check for a custom path set by env variable
auto envPreferencesPath = getenv("FSO_PREFERENCES_PATH");
if (envPreferencesPath != nullptr && strlen(envPreferencesPath) > 0) {
preferencesPath = SCP_string(envPreferencesPath);
}
else {
char* sdlPreferencesPath = SDL_GetPrefPath(ORGANIZATION_NAME, APPLICATION_NAME);
if (sdlPreferencesPath != nullptr) {
preferencesPath = SCP_string(sdlPreferencesPath);
SDL_free(sdlPreferencesPath);
sdlPreferencesPath = nullptr;
}
else {
// this section will at least tell the user if something is seriously wrong instead of just crashing without a message or debug log.
// It may crash later, especially when trying to load sound. But let's let it *try* to run in the current directory at least.
static bool sdl_is_borked_warning = false;
if (!sdl_is_borked_warning) {
ReleaseWarning(LOCATION, "%s\n\nSDL and Windows are unable to get the preferred path for the reason above. "
"Installing FSO, its executables and DLLs in another non-protected folder may fix the issue.\n\n"
"You may experience issues if you continue playing, and FSO may crash. Please report this error if it persists.\n\n"
"Report at www.hard-light.net or the hard-light discord.", SDL_GetError());
sdl_is_borked_warning = true;
}
}
}
// No preferences path, try current directory.
if (preferencesPath.empty()) {
Cmdline_portable_mode = true;
return "." DIR_SEPARATOR_STR;
}
// Ensure path ends with a path separator (slash)
if (!preferencesPath.empty() && (preferencesPath.back() != DIR_SEPARATOR_CHAR)) {
preferencesPath += DIR_SEPARATOR_CHAR;
}
#ifdef WIN32
try {
auto current = preferencesPath.begin();
const auto prefPathEnd = preferencesPath.end();
while (current != prefPathEnd) {
const auto cp = utf8::next(current, prefPathEnd);
if (cp > 127) {
// On Windows, we currently do not support Unicode paths so force portable mode let the user
// know
const auto invalid_end = current;
static bool force_portable_warning = false;
if (!force_portable_warning) {
utf8::prior(current, preferencesPath.begin());
ReleaseWarning(LOCATION,
"Determined the preferences path as \"%s\". That path is not supported since it "
"contains a Unicode character (%s). Using portable mode. Set -portable_mode in "
"the commandline to avoid this message in the future.",
preferencesPath.c_str(), std::string(current, invalid_end).c_str());
force_portable_warning = true;
}
Cmdline_portable_mode = true;
return "." DIR_SEPARATOR_STR;
}
}
} catch (const std::exception& e) {
Error(LOCATION, "UTF-8 error while checking the preferences path \"%s\": %s", preferencesPath.c_str(),
e.what());
}
#endif
}
if (!preferencesPath.empty()) {
return preferencesPath;
}
else {
// No preferences path, try current directory
return "." DIR_SEPARATOR_STR;
}
}
bool fAppActive = false;
bool window_event_handler(const SDL_Event& e)
{
Assertion(mainSDLWindow != nullptr, "This function may only be called with a valid SDL Window.");
if (os::events::isWindowEvent(e, mainSDLWindow)) {
switch (e.window.event) {
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_FOCUS_LOST:
{
if (fAppActive) {
game_pause();
joy_unacquire_ff();
fAppActive = false;
}
break;
}
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED:
case SDL_WINDOWEVENT_FOCUS_GAINED:
{
if (!fAppActive) {
joy_reacquire_ff();
game_unpause();
fAppActive = true;
}
break;
}
case SDL_WINDOWEVENT_CLOSE:
gameseq_post_event(GS_EVENT_QUIT_GAME);
break;
}
gr_activate(fAppActive);
return true;
}
return false;
}
bool quit_handler(const SDL_Event& /*e*/) {
mprintf(("Received quit signal\n"));
gameseq_post_event(GS_EVENT_QUIT_GAME);
return true;
}
const char* mapCategory(int category) {
switch (category) {
case SDL_LOG_CATEGORY_APPLICATION:
return "APPLICATION";
case SDL_LOG_CATEGORY_ERROR:
return "ERROR";
case SDL_LOG_CATEGORY_ASSERT:
return "ASSERT";
case SDL_LOG_CATEGORY_SYSTEM:
return "SYSTEM";
case SDL_LOG_CATEGORY_AUDIO:
return "AUDIO";
case SDL_LOG_CATEGORY_VIDEO:
return "VIDEO";
case SDL_LOG_CATEGORY_RENDER:
return "RENDER";
case SDL_LOG_CATEGORY_INPUT:
return "INPUT";
case SDL_LOG_CATEGORY_TEST:
return "TEST";
default:
return "UNKNOWN";
}
}
const char* mapPriority(SDL_LogPriority prio)
{
switch (prio) {
case SDL_LOG_PRIORITY_VERBOSE:
return "VRB";
case SDL_LOG_PRIORITY_DEBUG:
return "DBG";
case SDL_LOG_PRIORITY_INFO:
return "INF";
case SDL_LOG_PRIORITY_WARN:
return "WRN";
case SDL_LOG_PRIORITY_ERROR:
return "ERR";
case SDL_LOG_PRIORITY_CRITICAL:
return "CRI";
default:
return "UNK";
}
}
void SDLCALL logHandler(void*, int category, SDL_LogPriority priority, const char* message) {
if (priority >= SDL_LOG_PRIORITY_INFO) {
mprintf(("SDL [%s][%s]: %s\n", mapPriority(priority), mapCategory(category), message));
} else {
nprintf(("SDL", "SDL [%s][%s]: %s\n", mapPriority(priority), mapCategory(category), message));
}
}
}
// ----------------------------------------------------------------------------------------------------
// PLATFORM SPECIFIC FUNCTION FOLLOWING
//
#ifdef WIN32
// Windows specific includes
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <backends/imgui_impl_sdl.h>
// go through all windows and try and find the one that matches the search string
BOOL __stdcall os_enum_windows( HWND hwnd, LPARAM param )
{
const char* search_string = reinterpret_cast<const char*>(param);
char tmp[128];
int len;
len = GetWindowText( hwnd, tmp, 127 );
if ( len ) {
if ( strstr( tmp, search_string )) {
Os_debugger_running = 1; // found the search string!
return FALSE; // stop enumerating windows
}
}
return TRUE; // continue enumeration
}
// Fills in the Os_debugger_running with non-zero if debugger detected.
void os_check_debugger()
{
HMODULE hMod;
char search_string[256];
char myname[128];
int namelen;
char * p;
Os_debugger_running = 0; // Assume its not
// Find my EXE file name
hMod = GetModuleHandle(NULL);
if ( !hMod ) return;
namelen = GetModuleFileName( hMod, myname, 127 );
if ( namelen < 1 ) return;
// Strip off the .EXE
p = strstr( myname, ".exe" );
if (!p) return;
*p = '\0';
// Move p to point to first letter of EXE filename
while( (*p!='\\') && (*p!='/') && (*p!=':') )
p--;
p++;
if ( strlen(p) < 1 ) return;
// Build what the debugger's window title would be if the debugger is running...
sprintf( search_string, "[run] - %s -", p );
// ... and then search for it.
EnumWindows(os_enum_windows, reinterpret_cast<LPARAM>(&search_string));
}
void os_set_process_affinity()
{
HANDLE pHandle = GetCurrentProcess();
DWORD_PTR pMaskProcess = 0, pMaskSystem = 0;
if ( GetProcessAffinityMask(pHandle, &pMaskProcess, &pMaskSystem) ) {
// only do this if we have at least 2 procs
if (pMaskProcess >= 3) {
// prefer running on the second processor by default
pMaskProcess = os_config_read_uint(NULL, "ProcessorAffinity", 2);
if (pMaskProcess > 0) {
SetProcessAffinityMask(pHandle, pMaskProcess);
}
}
}
}
#endif // WIN32
// ----------------------------------------------------------------------------------------------------
// OSAPI DEFINES/VARS
//
// os-wide globals
static char szWinTitle[128];
static char szWinClass[128];
static int Os_inited = 0;
static SCP_vector<SDL_Event> deferred_events;
int Os_debugger_running = 0;
#ifdef SCP_UNIX
const char* os_get_legacy_user_dir()
{
static bool user_dir_initialized = false;
static SCP_string Os_user_dir_legacy;
if (user_dir_initialized) {
return Os_user_dir_legacy.c_str();
}
extern const char* Osreg_user_dir_legacy;
sprintf(Os_user_dir_legacy, "%s/%s", getenv("HOME"), Osreg_user_dir_legacy);
user_dir_initialized = true;
return Os_user_dir_legacy.c_str();
}
#endif
// ----------------------------------------------------------------------------------------------------
// OSAPI FORWARD DECLARATIONS
//
void os_deinit();
// ----------------------------------------------------------------------------------------------------
// OSAPI FUNCTIONS
//
// initialization/shutdown functions -----------------------------------------------
// If app_name is NULL or ommited, then TITLE is used
// for the app name, which is where registry keys are stored.
void os_init(const char * wclass, const char * title, const char * app_name)
{
if (app_name == nullptr || !app_name[0])
{
os_init_registry_stuff(Osreg_company_name, title);
}
else
{
os_init_registry_stuff(Osreg_company_name, app_name);
}
strcpy_s( szWinTitle, title );
strcpy_s( szWinClass, wclass );
SDL_version compiled;
SDL_version linked;
SDL_VERSION(&compiled);
SDL_GetVersion(&linked);
mprintf((" Initializing SDL %d.%d.%d (compiled with %d.%d.%d)...\n", linked.major, linked.minor, linked.patch,
compiled.major, compiled.minor, compiled.patch));
if (LoggingEnabled) {
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
SDL_LogSetOutputFunction(&logHandler, nullptr);
}
if (SDL_Init(SDL_INIT_EVENTS) < 0)
{
fprintf(stderr, "Couldn't init SDL: %s", SDL_GetError());
mprintf(("Couldn't init SDL: %s\n", SDL_GetError()));
exit(1);
return;
}
#ifdef FS2_VOICER
SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); // We currently only need this for voice recognition
#endif
// initialized
Os_inited = 1;
#ifdef WIN32
// check to see if we're running under msdev
os_check_debugger();
if (Cmdline_set_cpu_affinity)
{
// deal with processor affinity
os_set_process_affinity();
}
#endif // WIN32
os::events::addEventListener(SDL_WINDOWEVENT, os::events::DEFAULT_LISTENER_WEIGHT, window_event_handler);
os::events::addEventListener(SDL_QUIT, os::events::DEFAULT_LISTENER_WEIGHT, quit_handler);
}
// set the main window title
void os_set_title( const char * title )
{
Assertion(mainSDLWindow != nullptr, "This function may only be called with a valid SDL Window.");
strcpy_s( szWinTitle, title );
SDL_SetWindowTitle(mainSDLWindow, szWinTitle);
}
// call at program end
void os_cleanup()
{
os_deinit_registry_stuff();
if (LoggingEnabled) {
outwnd_close();
}
os_deinit();
}
// window management -----------------------------------------------------------------
// Returns 1 if app is not the foreground app.
bool os_foreground()
{
return fAppActive;
}
// process management -----------------------------------------------------------------
// Sleeps for n milliseconds or until app becomes active.
void os_sleep(uint ms)
{
SDL_Delay(ms);
}
static bool file_exists(const SCP_string& path) {
std::ofstream str(path, std::ios::in);
return str.good();
}
static time_t get_file_modification_time(const SCP_string& path) {
#ifdef SCP_UNIX
struct stat file_stats{};
if(stat(path.c_str(), &file_stats) < 0) {
return 0;
}
return file_stats.st_mtime;
#elif defined(WIN32)
struct _stat buf{};
if (_stat(path.c_str(), &buf) != 0) {
return 0;
}
return buf.st_mtime;
#else
#error Unsupported platform!
#endif
}
const char* Osapi_legacy_mode_reason = nullptr;
bool os_is_legacy_mode()
{
// Make this check a little faster by caching the result
if (checkedLegacyMode)
{
return legacyMode;
}
if (Cmdline_portable_mode) {
// When the portable mode option is given, non-legacy is implied
legacyMode = false;
checkedLegacyMode = true;
Osapi_legacy_mode_reason = "Legacy mode disabled since portable mode was enabled.";
}
else {
SCP_stringstream path_stream;
path_stream << getPreferencesPath() << Osreg_config_file_name;
auto new_config_exists = file_exists(path_stream.str());
time_t new_config_time = 0;
if (new_config_exists) {
new_config_time = get_file_modification_time(path_stream.str());
}
// Also check the modification times of the command line files in case the launcher did not change the settings
// file
path_stream.str("");
path_stream << getPreferencesPath() << "data" << DIR_SEPARATOR_CHAR << "cmdline_fso.cfg";
new_config_time = std::max(new_config_time, get_file_modification_time(path_stream.str()));
#ifdef SCP_UNIX
path_stream.str("");
path_stream << os_get_legacy_user_dir() << DIR_SEPARATOR_CHAR << Osreg_config_file_name;
auto old_config_exists = file_exists(path_stream.str());
time_t old_config_time = 0;
if (old_config_exists) {
old_config_time = get_file_modification_time(path_stream.str());
}
path_stream.str("");
path_stream << os_get_legacy_user_dir() << DIR_SEPARATOR_CHAR << "data" << DIR_SEPARATOR_CHAR
<< "cmdline_fso.cfg";
old_config_time = std::max(old_config_time, get_file_modification_time(path_stream.str()));
#else
std::optional<time_t> optional_old_config_time = os_registry_get_last_modification_time();
time_t old_config_time = 0;
//Check if the registry key exists
auto old_config_exists = optional_old_config_time.has_value();
if (old_config_exists) {
old_config_time = optional_old_config_time.value();
// On Windows the cmdline_fso file was stored in the game root directory which should be in the current directory
// Only get this if the old config exists
path_stream.str("");
path_stream << "." << DIR_SEPARATOR_CHAR << "data" << DIR_SEPARATOR_CHAR << "cmdline_fso.cfg";
old_config_time = std::max(old_config_time, get_file_modification_time(path_stream.str()));
}
#endif
if (new_config_exists && old_config_exists) {
// Both config files exists so we need to decide which to use based on their last modification times
// if the old config was modified more recently than the new config then we use the legacy mode since the
// user probably used an outdated launcher after using a more recent one
legacyMode = old_config_time > new_config_time;
if (legacyMode) {
Osapi_legacy_mode_reason = "Legacy mode enabled since the old config location was used more recently than the new location.";
} else {
Osapi_legacy_mode_reason = "Legacy mode disabled since the new config location was used more recently than the old location.";
}
} else if (new_config_exists) {
// If the new config exists and the old one doesn't then we can safely disable the legacy mode
legacyMode = false;
Osapi_legacy_mode_reason = "Legacy mode disabled since the old config does not exist while the new config exists.";
} else if (old_config_exists) {
// Old config exists but new doesn't -> use legacy mode
legacyMode = true;
Osapi_legacy_mode_reason = "Legacy mode enabled since the old config exists while the new config does not exist.";
} else {
// Neither old nor new config exists -> this is a new install
legacyMode = false;
Osapi_legacy_mode_reason = "Legacy mode disabled since no existing config was detected.";
}
}
if (legacyMode) {
// Print a message for the people running it from the terminal
fprintf(stdout, "FSO is running in legacy config mode. Please either update your launcher or"
" copy the configuration and pilot files to '%s' for better future compatibility.\n", getPreferencesPath().c_str());
}
checkedLegacyMode = true;
return legacyMode;
}
// ----------------------------------------------------------------------------------------------------
// OSAPI FORWARD DECLARATIONS
//
// called at shutdown. Makes sure all thread processing terminates.
void os_deinit()
{
// Free the view ports
os::closeAllViewports();
SDL_Quit();
}
void debug_int3(const char *file, int line)
{
mprintf(("Int3(): From %s at line %d\n", file, line));
gr_activate(0);
mprintf(("%s\n", dump_stacktrace().c_str()));
#ifndef NDEBUG
SDL_TriggerBreakpoint();
#endif
gr_activate(1);
}
namespace os
{
Viewport* addViewport(std::unique_ptr<Viewport>&& viewport) {
auto port = viewport.get();
viewports.push_back(std::move(viewport));
return port;
}
void setMainViewPort(Viewport* mainView) {
mainViewPort = mainView;
mainSDLWindow = mainView->toSDLWindow();
}
SDL_Window* getSDLMainWindow() {
return mainSDLWindow;
}
Viewport* getMainViewport() {
return mainViewPort;
}
void closeAllViewports() {
viewports.clear();
}
namespace events
{
namespace
{
ListenerIdentifier nextListenerIdentifier;
struct EventListenerData
{
ListenerIdentifier identifier;
Listener listener;
uint32_t type;
int weight;
bool operator<(const EventListenerData& other) const
{
if (type < other.type)
{
return true;
}
if (type > other.type)
{
return false;
}
// Type is the same
return weight < other.weight;
}
};
bool compare_type(const EventListenerData& left, const EventListenerData& right)
{
return left.type < right.type;
}
SCP_vector<EventListenerData> eventListeners;
}
ListenerIdentifier addEventListener(SDL_EventType type, int weight, const Listener& listener)
{
Assertion(listener, "Invalid event handler passed!");
EventListenerData data;
data.identifier = ++nextListenerIdentifier;
data.listener = listener;
data.weight = weight;
data.type = static_cast<uint32_t>(type);
eventListeners.push_back(data);
// This is suboptimal for runtime but we will iterate that vector often so cache hits are more important
std::sort(eventListeners.begin(), eventListeners.end());
return data.identifier;
}
bool removeEventListener(ListenerIdentifier identifier)
{
auto endIter = end(eventListeners);
for (auto iter = begin(eventListeners); iter != endIter; ++iter)
{
if (iter->identifier == identifier)
{
eventListeners.erase(iter);
return true; // Identifiers are unique
}
}
return false;
}
bool isWindowEvent(const SDL_Event& e, SDL_Window* window)
{
auto mainId = SDL_GetWindowID(window);
switch(e.type)
{
case SDL_WINDOWEVENT:
return mainId == e.window.windowID;
case SDL_KEYDOWN:
case SDL_KEYUP:
return mainId == e.key.windowID;
case SDL_TEXTEDITING:
return mainId == e.edit.windowID;
case SDL_TEXTINPUT:
return mainId == e.text.windowID;
case SDL_MOUSEMOTION:
return mainId == e.motion.windowID;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
return mainId == e.button.windowID;
case SDL_MOUSEWHEEL:
return mainId == e.wheel.windowID;
default:
// Event doesn't have a window ID
return true;
}
}
}
}
void os_defer_events_on_load_screen() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
// Add event to be handled later
deferred_events.push_back(event);
}
}
static void handle_sdl_event(const SDL_Event& event) {
using namespace os::events;
bool imgui_processed_this = false;
if ((gameseq_get_state() == GS_STATE_LAB) || (gameseq_get_state() == GS_STATE_INGAME_OPTIONS)) {
//In these states, we always need to forward inputs to ImGUI, and depending on the ImGUI state and the input type, we must consume it here instead of passing it to FSO.
ImGui_ImplSDL2_ProcessEvent(&event);
imgui_processed_this = (ImGui::GetIO().WantCaptureKeyboard &&
(event.type == SDL_EventType::SDL_KEYUP ||
event.type == SDL_EventType::SDL_KEYDOWN)) ||
(ImGui::GetIO().WantCaptureMouse &&
(event.type == SDL_EventType::SDL_MOUSEBUTTONUP ||
event.type == SDL_EventType::SDL_MOUSEBUTTONDOWN||
event.type == SDL_EventType::SDL_MOUSEMOTION));
}
if (!imgui_processed_this) {
EventListenerData data;
data.type = event.type;
auto iter = std::lower_bound(eventListeners.begin(), eventListeners.end(), data, compare_type);
if (iter != eventListeners.end()) {
// The vector contains all event listeners, the listeners are sorted for type and weight
// -> iterating through all listeners will yield them in increasing weight order
// but we can only do this until we have reached the end of the vector or the type has changed
for (; iter != eventListeners.end() && iter->type == event.type; ++iter) {
if (iter->listener(event)) {
// Listener has handled the event
break;
}
}
}
}
}
void os_remove_deferred_cutscene_key_events() {
deferred_events.erase(
std::remove_if(deferred_events.begin(), deferred_events.end(), [](const SDL_Event &event)
{
return (event.type == SDL_KEYUP) && (
event.key.keysym.sym == SDLK_KP_ENTER ||
event.key.keysym.sym == SDLK_RETURN ||
event.key.keysym.sym == SDLK_SPACE
);
}),
deferred_events.end()
);
}
void os_poll()
{
// Replay the deferred events
auto end = deferred_events.end();
for (auto it = deferred_events.begin(); it != end; ++it) {
handle_sdl_event(*it);
}
deferred_events.clear();
SDL_Event event;
while (SDL_PollEvent(&event)) {
handle_sdl_event(event);
}
openxr_poll();
}
SCP_string os_get_config_path(const SCP_string& subpath)
{
// Make path platform compatible
SCP_string compatiblePath(subpath);
std::replace(compatiblePath.begin(), compatiblePath.end(), '/', DIR_SEPARATOR_CHAR);
SCP_stringstream ss;
if (Cmdline_portable_mode) {
// Use the current directory
ss << "." << DIR_SEPARATOR_CHAR << compatiblePath;
return ss.str();
}
// Avoid infinite recursion when checking legacy mode
if (os_is_legacy_mode()) {
#ifdef WIN32
// Use the current directory
ss << ".";
#else
extern const char* Osreg_user_dir_legacy;
// Use the home directory
ss << getenv("HOME") << DIR_SEPARATOR_CHAR << Osreg_user_dir_legacy;
#endif
ss << DIR_SEPARATOR_CHAR << compatiblePath;
return ss.str();
}
ss << getPreferencesPath() << compatiblePath;
return ss.str();
}