Linux + Vulkan Port — Step-by-Step Rebuild Plan
A commit-by-commit replay of everything done in the first port session (2026-11-04), so it can
be re-implemented by hand. Each step lists what to change, the exact code, how to verify it,
and what was learned. The why and the full roadmap (Phases 6–7: the Vulkan backend) live in
LinuxVulkanPort.md; this file is the how.
- Baseline:
050a7b6("DevLog 01 …"), the last upstream commit before the port. - Already committed: steps A1–A4 match your commit
5d512e7("Add Linux CMake build support"). If you start over from the baseline, redo them; otherwise begin at B1. - End state: the working tree at the end of the session (Phases 0–5 done, Windows not yet compiled).
- Diffs are generated from the real files. Intermediate versions are reconstructed for files that change in more than one step, so each diff shows only that step's change.
- You commit manually; suggested commit messages are given per step.
Contents
- 0 — Setup (packages, IDE, build commands)
- L — Lessons learned (read first)
- A — Foundation: license, C++ standard, CMake (= commit
5d512e7) - B — Phase 2: core portability → entity test runs
- C — Phase 3: shared platform API → window test runs
- D — Phase 4: content loader, game executable, paths
- E — Phase 5: shader compiler, HLSL → SPIR-V
- V — Verification helpers (scratch programs)
- N — What's next
0. Setup
Packages (CachyOS/Arch):
sudo pacman -S cmake ninja vulkan-headers vulkan-validation-layers directx-shader-compiler sdl3
# optional: vulkan-memory-allocator renderdoc
# already present on the dev machine: clang 23, gcc 16, glslc, spirv-val/spirv-dis, vulkaninfo
ninjain the zsh profile is an alias (ninja -j24); the binary must still be installed.- IDE: Rider can't load C++
.vcxprojprojects on Linux (Windows/MSVC only). Use CLion: open the repo root folder, enable the Linux Debug (clang) CMake profile, disable the default Debug profile, and turn on Emulate terminal in output console for EngineTest (the entity test reads stdin). Keep Rider/Visual Studio +Primal.slnxfor Windows. - Build / run:
cmake --preset linux-debug # configure (Ninja + clang)
cmake --preset linux-debug -DPRIMAL_ENGINE_TEST=WINDOW # pick a test: ENTITY_COMPONENTS | WINDOW | RENDERER
cmake --build --preset linux-debug
./x64/Debug/EngineTest # output goes to x64/<Config>/ like on Windows
# sanitizer build in a separate folder (ASan + LSan + UBSan)
cmake -S . -B build/asan -G Ninja -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Debug -DPRIMAL_ENABLE_SANITIZERS=ON
cmake --build build/asan
SDL_VIDEO_DRIVER=x11 ./x64/Debug/EngineTest # force X11 (default on KDE is Wayland)
- Windows checkpoints: after each part (A–E), build
Primal.slnxon Windows. None of the Windows-side edits from parts B–E were compiled during the session.
L. Lessons learned
Build & tooling
- clang only on Linux for now. GCC 16 rejects two things MSVC/clang accept: a member named like its type (
camera_id camera_id;,-Wchanges-meaning, ill-formed NDR) inRenderer.h,GraphicsPlatformInterface.h,Input.h; and members with constructors in an anonymous struct inside a union (Transform.cpp, MSVC extension). Fixing the first needs public API renames — a separate decision. - C++23, not C++26. Linux enforces it strictly (
CMAKE_CXX_STANDARD 23, no extensions). The.vcxprojfiles usestdcpp23(=/std:c++23preview, confirmed 2026-11-09; earlierstdcpplatest). - Static library
main:libengine.acontainsCore/MainLinux.cppwithmain(). Executables that define their ownmain(EngineTest) don't pull it in — the linker only takes archive members that resolve undefined symbols (same asWinMaininengine.libon Windows). - Linux paths are case-sensitive (
"enginetest"had to become"EngineTest") and need/. Forward slashes work on Windows too, so use them everywhere. - Debugging:
ptrace_scope=1blocks attaching gdb to a running process. Launch under the tool instead (gdb ./EngineTest,strace -f -o log ./EngineTest).timeoutexits with 124 even if the program shut down cleanly; usetimeout --preserve-status. - zsh doesn't word-split
$VARinto arguments (unlike bash). Use arrays or a bash script when passing a list of flags through a variable.
Engine bugs found (they affect Windows too)
utl::vectorbyte-copies items (realloc,memmove,memcpy). That's only valid for types that survive a byte copy. libstdc++'sstd::string/std::wstring(short-string buffer pointer) andstd::unordered_map(single-bucket pointer) point into themselves; MSVC's happen not to. Symptom: DXC got garbage arguments ("Internal Compiler error",munmap_chunk(): invalid pointer). Fix (B4): move-construct those types; keep byte copies for trivially copyable types, non-movable types andvector<T, false>(free_list).free_listmust stay bitwise — dead slots hold the free-list link, so they can't be move-constructed from. Items in afree_listmust therefore be byte-relocatable:noexcept_mapnow holds itsstd::unordered_mapthrough aunique_ptr. Its copy constructor / copy assignment must then be= delete(they were= default, which clang flags as implicitly deleted; fixed after367babd).memcpywith overlapping ranges inutl::vector::erase(UB, caught by ASan) →memmove.std::chrono::high_resolution_clockissteady_clockon MSVC butsystem_clockon libstdc++.time_itmixed the two; usesteady_clock.load_game()read u32 fields as one byte (const u32 n{ *at }whereatisconst u8*). The editor writes 4-byteints. Values > 255 (e.g. > 255 entities) were misread →read_u32().engine_shutdown()removed a window that was never created whenengine_initialize()failed (missinggame.bin) → checkis_valid().- COM refcount leak: constructing a
ComPtr/CComPtrfromother.Detach()adds a reference; useAttach(). Every compiled shader blob was leaked. - Narrowing: clang rejects
u32 x{ sizeof(...) * n }(size_t → u32 in braces); MSVC only warns.
Platform layer
- Wayland doesn't show a window that has never presented a buffer. Until a graphics surface exists, the Linux layer fills windows with the Win32 class brush colour (RGB 26, 48, 76) via SDL's window surface. The Vulkan backend must call
SDL_DestroyWindowSurfacebefore creating its swapchain (Phase 6). - Wayland ignores window positions. Test window positions were also changed from far-negative (an old multi-monitor setup) to on-screen.
- Event callbacks may remove windows (Esc, F11 restart). Both platform layers collect the event, finish their own bookkeeping, and call the callback last; they never touch the window afterwards.
- Closing hides, it doesn't destroy. On both platforms
closedhides the window so the native handle (and the swapchain built on it) stays valid untilremove_window(). - SDL lifetime: set
SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSEto0(the app decides, like Win32). Subsystems are refcounted: checkSDL_WasInitbeforeSDL_InitSubSystem. DeferSDL_QuitSubSystem(VIDEO)whilepump_events()runs, or an F11 restart (remove all + recreate inside a callback) tears SDL down mid-loop. SDL turns SIGINT/SIGTERM intoSDL_EVENT_QUIT. native_window_handlepoints into the window list; copy it if needed after the nextcreate_window/remove_window.- The editor needs
WM_MOUSEHOVER/WM_MOUSELEAVEfrom the engine's child window (RenderSurfaceControl.cs). TheTrackMouseEventcode moved from EngineDLL'sWinProcintoPlatformWin32.cpp. - Keys: Linux maps SDL scancodes (physical positions); Win32 maps layout-dependent virtual keys, so letters differ on non-QWERTY layouts. Wheel delta scaled to 120 per notch like Win32.
- Sanitizer noise: on Wayland LSan reports a 256-byte leak inside a library SDL
dlcloses (no engine frames). X11 is clean. Late in the session XWayland stopped answering (all X11 runs, including old binaries, hung inpoll()at startup) — an environment issue (locked screen / compositor), not code.
Shaders (DXC on Linux)
- Linux DXC =
libdxcompiler.so+<dxc/dxcapi.h>withWinAdapter.h(COM shim). ItsCComPtrhas no.Get()→ smallcom_ptr<T>wrapper.WinAdapter.halso mapsOutputDebugStringAtofputs(stderr). - ADL trap: a local
get_engine_shaders_path(platform)was ambiguous withgraphics::get_engine_shaders_path(graphics_platform)because the argument type lives inprimal::graphics. Give helpers distinct names. static_assert(std::size(ptr->array))through a runtime pointer isn't a constant expression; usesizeof(Type::array).- DXC only hashes DXIL (
DXC_OUT_SHADER_HASH) and only disassembles DXIL ("Invalid bitcode signature" on SPIR-V). SPIR-V gets a 128-bit FNV-1a hash; disassembly is skipped (usespirv-dis). - Use the dxc CLI +
spirv-val --target-env vulkan1.3 --scalar-block-layoutto iterate on flags before touching C++. The flags/binding table is in step E2. - Vulkan device requirements created by the flags:
scalarBlockLayout(-fvk-use-dx-layout),shaderFloat16/shaderInt16+ 16-bit storage (-enable-16bit-types),VK_EXT_mutable_descriptor_type(resource heap with aliased typed views).
Vulkan backend (Phase 6)
- SDL's window surface is GPU-backed by default.
SDL_GetWindowSurfaceuses anSDL_Renderer(OpenGL), which on X11 recreates the window with another visual: the XID we handed out innative_window_handlebecame a destroyed window (BadWindow, "graphics queue can't present to this window").SDL_HINT_FRAMEBUFFER_ACCELERATION=0keeps SDL's software framebuffer (XShm / wl_shm), which leaves the window alone.get_window_handle()asserts the XID is unchanged. Wayland happened to work either way. - The background painting must stop before the swapchain exists:
window::set_has_graphics_surface(true)(callsSDL_DestroyWindowSurfaceon Linux, no-op on Win32), called by the Vulkan surface. - Frame fences don't cover presents. Destroying/recreating a swapchain (or its per-image present semaphores) after
waiting on the timeline semaphore still triggers
VUID-vkDestroySwapchainKHR-swapchain-01282/VUID-vkDestroySemaphore-semaphore-05149. WithoutVK_EXT_swapchain_maintenance1present fences,flush()must alsovkQueueWaitIdle. - Present semaphores are per swapchain image, acquire semaphores per frame in flight (an acquire semaphore is reusable once its frame's fence value is reached; a present semaphore only when its image is acquired again).
- Mesa (26.2) leaks debug names of surfaces and swapchains (
vk_common_set_object_name_locked, a per-device hash table it never frees). Don't nameVkSurfaceKHR/VkSwapchainKHR. - LSan and unloaded libraries: leaks inside the ICD/layers show as
<unknown module>because the loaderdlcloses them.LD_PRELOADa shim whosedlclose()returns 0 to get symbolized stacks. A bare instance + device create/destroy already reports 256 B in RADV without the shim (none with it). - X11 Xlib.h defines macros (
None,Bool,Status,Always, ...).VulkanSurface.cppdeclares the four typesvulkan_xlib.hneeds (Display,XID,Window,VisualID) instead of including it; nothing links libX11.
Process
- Copyright: new files get
// Copyright (c) 2026 Charles Smith; Arash's files keep his header even when heavily modified.LICENSElists both. - File renames: plain
mvwas used, so stage them yourself (git add -Aorgit mvbefore editing to keep rename detection obvious). - Keep
Docs/LinuxVulkanPort.md(plan + status) updated as you go.
A. Foundation (matches commit 5d512e7)
A1 — License and copyright convention
Edit LICENSE
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,7 @@
MIT License
Copyright (c) Arash Khatami
+Copyright (c) 2026 Charles Smith
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Rule from here on: new files start with
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
Commit: Add Charles Smith copyright line to LICENSE
A2 — C++ standard in the Visual Studio projects
In all four .vcxproj files (ContentTools, Engine ×4 configurations, EngineDLL, EngineTest) change every
<LanguageStandard>stdcpp20</LanguageStandard> to stdcpp23 (/std:c++23preview with the v145 toolset; the port
originally used stdcpplatest until this value was confirmed on 2026-11-09).
- <LanguageStandard>stdcpp20</LanguageStandard>
+ <LanguageStandard>stdcpp23</LanguageStandard>
Commit: Move Visual Studio projects to the latest C++ standard
A3 — CMake build alongside the .vcxproj files
Linux-only CMake build for Engine (static, PIC) and EngineTest. Windows keeps Primal.slnx.
New file CMakeLists.txt
# Copyright (c) 2026 Charles Smith
# Distributed under the MIT license. See the LICENSE file in the project root for more information.
#
# CMake build for Linux (Engine + EngineTest). On Windows, keep using Primal.slnx / the .vcxproj files.
cmake_minimum_required(VERSION 3.25)
project(Primal LANGUAGES CXX)
if(WIN32)
message(FATAL_ERROR "On Windows, build with Primal.slnx (Visual Studio / Rider). CMake is used for the Linux build.")
endif()
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug CACHE STRING "Build type" FORCE)
endif()
set(PRIMAL_ENGINE_TEST "ENTITY_COMPONENTS" CACHE STRING "Which EngineTest test to build (ENTITY_COMPONENTS, WINDOW, RENDERER)")
set_property(CACHE PRIMAL_ENGINE_TEST PROPERTY STRINGS ENTITY_COMPONENTS WINDOW RENDERER)
option(PRIMAL_ENABLE_SANITIZERS "Build with AddressSanitizer + UndefinedBehaviorSanitizer" OFF)
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
include(PrimalDependencies)
include(PrimalBuildSettings)
add_subdirectory(Engine)
add_subdirectory(EngineTest)
New file CMakePresets.json
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
"configurePresets": [
{
"name": "linux-base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"cacheVariables": {
"CMAKE_CXX_COMPILER": "clang++",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
},
"condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Linux" }
},
{
"name": "linux-debug",
"displayName": "Linux Debug (clang)",
"inherits": "linux-base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }
},
{
"name": "linux-release",
"displayName": "Linux Release (clang)",
"inherits": "linux-base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Release" }
}
],
"buildPresets": [
{ "name": "linux-debug", "configurePreset": "linux-debug" },
{ "name": "linux-release", "configurePreset": "linux-release" }
]
}
New file cmake/PrimalBuildSettings.cmake
# Copyright (c) 2026 Charles Smith
# Distributed under the MIT license. See the LICENSE file in the project root for more information.
#
# Compiler settings shared by all Primal targets. Mirrors the intent of the .vcxproj settings:
# - /arch:AVX2 -> -mavx2 -mfma -mf16c (+ SSE4.2 for _mm_crc32_u64)
# - /fp:fast -> -ffp-contract=fast -fno-math-errno (NOT -ffast-math, which breaks NaN/Inf handling)
# - _DEBUG / NDEBUG -> per configuration
add_library(primal_build_settings INTERFACE)
add_library(primal::build_settings ALIAS primal_build_settings)
target_compile_features(primal_build_settings INTERFACE cxx_std_23)
target_compile_options(primal_build_settings INTERFACE
-msse4.2 -mavx2 -mfma -mf16c
-ffp-contract=fast -fno-math-errno
-Wall
-Wno-unknown-pragmas # MSVC-only pragmas (#pragma warning, #pragma comment, ...)
)
target_compile_definitions(primal_build_settings INTERFACE
$<$<CONFIG:Debug>:_DEBUG>
)
if(PRIMAL_ENABLE_SANITIZERS)
target_compile_options(primal_build_settings INTERFACE -fsanitize=address,undefined -fno-omit-frame-pointer)
target_link_options(primal_build_settings INTERFACE -fsanitize=address,undefined)
endif()
New file cmake/PrimalDependencies.cmake
# Copyright (c) 2026 Charles Smith
# Distributed under the MIT license. See the LICENSE file in the project root for more information.
#
# Third-party dependencies for the Linux build.
include(FetchContent)
# DirectXMath (header-only, portable). Uses a system install if one is found, otherwise fetches a pinned release.
set(BUILD_TESTING OFF CACHE BOOL "" FORCE)
FetchContent_Declare(DirectXMath
URL https://github.com/microsoft/DirectXMath/archive/refs/tags/jun2026.tar.gz
URL_HASH SHA256=cb46002679b16a25fd11d0a2a13f6a7c7bf9c51bf04258fb5485e5b839da8474
FIND_PACKAGE_ARGS CONFIG NAMES directxmath DirectXMath
)
FetchContent_MakeAvailable(DirectXMath)
if(NOT TARGET Microsoft::DirectXMath)
add_library(Microsoft::DirectXMath ALIAS DirectXMath)
endif()
# DirectXMath includes <sal.h>, which only exists on Windows. Provide a minimal stub elsewhere.
add_library(primal_sal_stub INTERFACE)
add_library(primal::sal ALIAS primal_sal_stub)
target_include_directories(primal_sal_stub SYSTEM INTERFACE "${PROJECT_SOURCE_DIR}/Engine/ThirdParty/sal")
New file Engine/CMakeLists.txt
# Copyright (c) 2026 Charles Smith
# Distributed under the MIT license. See the LICENSE file in the project root for more information.
add_library(Engine STATIC)
# Platform-neutral sources.
target_sources(Engine PRIVATE
Components/Entity.cpp
Components/Geometry.cpp
Components/Script.cpp
Components/Transform.cpp
Content/ContentToEngine.cpp
Graphics/Renderer.cpp
Input/Input.cpp
)
# NOTE: Windows-only sources (Win32 platform layer, D3D12 backend) are not part of the Linux build.
target_include_directories(Engine PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/Common
)
target_link_libraries(Engine PUBLIC
primal::build_settings
primal::sal
Microsoft::DirectXMath
)
# PIC so the engine can later be linked into a shared EngineDLL (libEngineDLL.so) for the editor.
set_target_properties(Engine PROPERTIES
POSITION_INDEPENDENT_CODE ON
OUTPUT_NAME engine
)
New file EngineTest/CMakeLists.txt
# Copyright (c) 2026 Charles Smith
# Distributed under the MIT license. See the LICENSE file in the project root for more information.
set(_primal_tests ENTITY_COMPONENTS WINDOW RENDERER)
if(NOT PRIMAL_ENGINE_TEST IN_LIST _primal_tests)
message(FATAL_ERROR "PRIMAL_ENGINE_TEST must be one of: ${_primal_tests} (got '${PRIMAL_ENGINE_TEST}')")
endif()
add_executable(EngineTest Main.cpp)
# Lights.cpp and Scripts.cpp are only used by the renderer test.
if(PRIMAL_ENGINE_TEST STREQUAL "RENDERER")
target_sources(EngineTest PRIVATE
TestRenderer.cpp
RenderItem.cpp
Lights.cpp
Scripts.cpp
)
endif()
foreach(_test IN LISTS _primal_tests)
if(_test STREQUAL PRIMAL_ENGINE_TEST)
target_compile_definitions(EngineTest PRIVATE TEST_${_test}=1)
else()
target_compile_definitions(EngineTest PRIVATE TEST_${_test}=0)
endif()
endforeach()
target_link_libraries(EngineTest PRIVATE Engine)
# Same layout as the Windows build (x64/<Config>/) so the relative paths used by the tests
# (../../x64/<assets>, ../../Engine/Graphics/...) resolve the same way.
set_target_properties(EngineTest PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/x64/$<CONFIG>"
)
New file Engine/ThirdParty/sal/sal.h
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
//
// Minimal stand-in for Microsoft's <sal.h> on non-Windows platforms.
// DirectXMath includes <sal.h>; on Linux these annotations have no meaning, so they expand to nothing.
// Only the annotations used by DirectXMath are defined here.
#pragma once
#ifndef _WIN32
#ifndef _In_
#define _In_
#endif
#ifndef _In_opt_
#define _In_opt_
#endif
#ifndef _In_reads_
#define _In_reads_(size)
#endif
#ifndef _In_reads_bytes_
#define _In_reads_bytes_(size)
#endif
#ifndef _Out_
#define _Out_
#endif
#ifndef _Out_opt_
#define _Out_opt_
#endif
#ifndef _Out_writes_
#define _Out_writes_(size)
#endif
#ifndef _Out_writes_bytes_
#define _Out_writes_bytes_(size)
#endif
#ifndef _Inout_
#define _Inout_
#endif
#ifndef _Success_
#define _Success_(expr)
#endif
#ifndef _Use_decl_annotations_
#define _Use_decl_annotations_
#endif
#ifndef _Analysis_assume_
#define _Analysis_assume_(expr)
#endif
#endif // !_WIN32
Edit .gitignore — append:
# CMake (Linux build) / clangd
/build/
.cache/
# CLion default CMake output folders
cmake-build-*/
Notes:
- DirectXMath is fetched (pinned tarball + SHA256); it needs
<sal.h>, provided by the stub on Linux. -ffp-contract=fast -fno-math-errno, not-ffast-math(that breaks NaN/Inf handling).- EngineTest output goes to
x64/<Config>/so the../../x64/...and../../Engine/...relative paths work the same as on Windows.
Verify: cmake --preset linux-debug configures. The build stops at compile errors — those are part B.
Commit: Add Linux CMake build support for Engine and EngineTest
A4 — Portable includes in shared files
Backslashes in #include don't work on Linux; MSVC-only #pragma comment(lib) gets guarded; the test
selection macros become overridable from CMake.
Edit Engine/Graphics/Direct3D12/D3D12CommonHeaders.h
--- a/Engine/Graphics/Direct3D12/D3D12CommonHeaders.h
+++ b/Engine/Graphics/Direct3D12/D3D12CommonHeaders.h
@@ -2,8 +2,8 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
-#include "Graphics\Renderer.h"
-#include "Platform\Window.h"
+#include "Graphics/Renderer.h"
+#include "Platform/Window.h"
// Skip definition of min/max macros in windows.h
#ifndef NOMINMAX
Edit Engine/Graphics/Direct3D12/D3D12Interface.cpp
--- a/Engine/Graphics/Direct3D12/D3D12Interface.cpp
+++ b/Engine/Graphics/Direct3D12/D3D12Interface.cpp
@@ -6,7 +6,7 @@
#include "D3D12Content.h"
#include "D3D12Light.h"
#include "D3D12Camera.h"
-#include "Graphics\GraphicsPlatformInterface.h"
+#include "Graphics/GraphicsPlatformInterface.h"
namespace primal::graphics::d3d12 {
Edit Engine/Graphics/Direct3D12/D3D12Shaders.cpp
--- a/Engine/Graphics/Direct3D12/D3D12Shaders.cpp
+++ b/Engine/Graphics/Direct3D12/D3D12Shaders.cpp
@@ -1,8 +1,8 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "D3D12Shaders.h"
-#include "Content\ContentLoader.h"
-#include "Content\ContentToEngine.h"
+#include "Content/ContentLoader.h"
+#include "Content/ContentToEngine.h"
namespace primal::graphics::d3d12::shaders {
namespace {
Edit Engine/Graphics/Renderer.cpp
--- a/Engine/Graphics/Renderer.cpp
+++ b/Engine/Graphics/Renderer.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "Renderer.h"
#include "GraphicsPlatformInterface.h"
-#include "Direct3D12\D3D12Interface.h"
+#include "Direct3D12/D3D12Interface.h"
namespace primal::graphics {
Edit EngineTest/TestEntityComponents.h
--- a/EngineTest/TestEntityComponents.h
+++ b/EngineTest/TestEntityComponents.h
@@ -3,8 +3,8 @@
#pragma once
#include "Test.h"
-#include "..\Engine\Components\Entity.h"
-#include "..\Engine\Components\Transform.h"
+#include "../Engine/Components/Entity.h"
+#include "../Engine/Components/Transform.h"
#include <iostream>
#include <ctime>
Edit EngineTest/TestWindow.h
--- a/EngineTest/TestWindow.h
+++ b/EngineTest/TestWindow.h
@@ -2,8 +2,8 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "Test.h"
-#include "..\Platform\PlatformTypes.h"
-#include "..\Platform\Platform.h"
+#include "../Platform/PlatformTypes.h"
+#include "../Platform/Platform.h"
using namespace primal;
Edit EngineTest/Main.cpp
--- a/EngineTest/Main.cpp
+++ b/EngineTest/Main.cpp
@@ -2,7 +2,9 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "Test.h"
+#ifdef _MSC_VER
#pragma comment(lib, "engine.lib")
+#endif
#if TEST_ENTITY_COMPONENTS
#include "TestEntityComponents.h"
Edit EngineTest/Test.h
--- a/EngineTest/Test.h
+++ b/EngineTest/Test.h
@@ -5,9 +5,15 @@
#include <chrono>
#include <string>
+#ifndef TEST_ENTITY_COMPONENTS
#define TEST_ENTITY_COMPONENTS 0
+#endif
+#ifndef TEST_WINDOW
#define TEST_WINDOW 0
+#endif
+#ifndef TEST_RENDERER
#define TEST_RENDERER 1
+#endif
class test
{
Commit: part of 5d512e7.
B. Phase 2 — Core portability (TEST_ENTITY_COMPONENTS runs)
B1 — Platform detection header
One place that decides the platform; everything else uses #if PRIMAL_PLATFORM_WINDOWS / #if PRIMAL_PLATFORM_LINUX
(always 0/1 → use #if, not #ifdef) instead of _WIN64.
New file Engine/Common/PlatformDetection.h
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
// Platform detection. Use these instead of checking compiler-specific macros (_WIN64, __linux__, ...)
// directly. Each macro is always defined, as 0 or 1, so use #if (not #ifdef).
#if defined(_WIN64)
#define PRIMAL_PLATFORM_WINDOWS 1
#define PRIMAL_PLATFORM_LINUX 0
#elif defined(__linux__) && defined(__x86_64__)
#define PRIMAL_PLATFORM_WINDOWS 0
#define PRIMAL_PLATFORM_LINUX 1
#else
#error Unsupported platform. Primal supports 64-bit Windows and x86-64 Linux.
#endif
// Graphics backends compiled into the engine. Can be overridden by the build system.
#ifndef PRIMAL_GRAPHICS_D3D12
#define PRIMAL_GRAPHICS_D3D12 PRIMAL_PLATFORM_WINDOWS
#endif
#ifndef PRIMAL_GRAPHICS_VULKAN
#define PRIMAL_GRAPHICS_VULKAN 0
#endif
Edit Engine/Common/CommonHeaders.h
--- a/Engine/Common/CommonHeaders.h
+++ b/Engine/Common/CommonHeaders.h
@@ -2,7 +2,9 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
-#ifdef _WIN64
+#include "PlatformDetection.h"
+
+#ifdef _MSC_VER
#pragma warning(disable: 4530) // disable exception warning
#endif
Edit Engine/Engine.vcxproj
--- a/Engine/Engine.vcxproj
+++ b/Engine/Engine.vcxproj
@@ -21,6 +21,7 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="Common\CommonHeaders.h" />
+ <ClInclude Include="Common\PlatformDetection.h" />
<ClInclude Include="Common\Id.h" />
<ClInclude Include="Common\PrimitiveTypes.h" />
<ClInclude Include="Components\ComponentsCommon.h" />
Edit Engine/Engine.vcxproj.filters
--- a/Engine/Engine.vcxproj.filters
+++ b/Engine/Engine.vcxproj.filters
@@ -2,6 +2,7 @@
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClInclude Include="Common\CommonHeaders.h" />
+ <ClInclude Include="Common\PlatformDetection.h" />
<ClInclude Include="Common\PrimitiveTypes.h" />
<ClInclude Include="Common\Id.h" />
<ClInclude Include="Components\Entity.h" />
Commit: Add platform detection header
B2 — Math and threading portability
DirectXMath on every platform, <immintrin.h> for SSE intrinsics, std::bit_width instead of _BitScan*.
log2 keeps its results (ceil(log2), 0 for 0 and 1) and becomes constexpr.
Edit Engine/Utilities/Math.h
--- a/Engine/Utilities/Math.h
+++ b/Engine/Utilities/Math.h
@@ -4,10 +4,9 @@
#include "CommonHeaders.h"
-// platform specific headers
-#if defined(_WIN64)
+#include <bit>
+#include <immintrin.h> // _mm_crc32_u64 (SSE4.2)
#include <DirectXMath.h>
-#endif
#include "../Utilities/MathTypes.h"
@@ -125,19 +124,12 @@
return crc;
}
-// TODO: _BitScan*() functions are Microsoft specific.
-[[nodiscard]] inline u8
+// Returns ceil(log2(value)): the exact log for powers of two, otherwise rounded up.
+// Returns 0 for value 0 and 1.
+[[nodiscard]] constexpr u8
log2(u64 value)
{
- unsigned long mssb; // most significant set bit
- unsigned long lssb; // least significant set bit
-
- // If perfect power of two (only one set bit), return index of bit. Otherwise round up
- // fractional log by adding 1 to most significant set bit's index.
- if (_BitScanReverse64(&mssb, value) > 0 && _BitScanForward64(&lssb, value) > 0)
- return u8(mssb + (mssb == lssb ? 0 : 1));
- else
- return 0;
+ return value ? u8(std::bit_width(value - 1)) : u8(0);
}
constexpr math::v3 to_radians(math::v3 degrees)
Edit Engine/Utilities/MathTypes.h
--- a/Engine/Utilities/MathTypes.h
+++ b/Engine/Utilities/MathTypes.h
@@ -13,7 +13,6 @@
constexpr f32 epsilon{ 1e-5f };
constexpr f32 to_rad{ pi * (1.f/180.f)};
constexpr f32 to_deg{ inv_pi * 180.f};
-#if defined(_WIN64)
using v2 = DirectX::XMFLOAT2;
using v2a = DirectX::XMFLOAT2A;
using v3 = DirectX::XMFLOAT3;
@@ -29,6 +28,5 @@
using m3x3 = DirectX::XMFLOAT3X3; // NOTE: DirectXMath doesn't have aligned 3x3 matrices
using m4x4 = DirectX::XMFLOAT4X4;
using m4x4a = DirectX::XMFLOAT4X4A;
-#endif
}
Edit Engine/Utilities/Threading.h
--- a/Engine/Utilities/Threading.h
+++ b/Engine/Utilities/Threading.h
@@ -2,10 +2,12 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
+#include <atomic>
+#include <immintrin.h> // _mm_pause
namespace primal::utl {
-#if _WIN64
+#if PRIMAL_PLATFORM_WINDOWS
class ticket_mutex {
public:
ticket_mutex() = default;
Commit: Make math and threading utilities portable
B3 — Gate the D3D12 backend; fix a narrowing error
Edit Engine/Graphics/Renderer.cpp
--- a/Engine/Graphics/Renderer.cpp
+++ b/Engine/Graphics/Renderer.cpp
@@ -2,7 +2,9 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "Renderer.h"
#include "GraphicsPlatformInterface.h"
+#if PRIMAL_GRAPHICS_D3D12
#include "Direct3D12/D3D12Interface.h"
+#endif
namespace primal::graphics {
@@ -22,9 +24,11 @@
{
switch (platform)
{
+#if PRIMAL_GRAPHICS_D3D12
case graphics_platform::direct3d12:
d3d12::get_platform_interface(pi);
break;
+#endif
default:
return false;
}
Edit Engine/Content/ContentToEngine.cpp — clang rejects the implicit size_t → u32 narrowing
--- a/Engine/Content/ContentToEngine.cpp
+++ b/Engine/Content/ContentToEngine.cpp
@@ -85,7 +85,7 @@
assert(lod_count);
blob.skip(sizeof(f32) * lod_count); // skip thresholds
// add size of lod_count, thresholds and lod offsets to the size of hierarchy.
- u32 size{ sizeof(u32) + (sizeof(f32) + sizeof(lod_offset)) * lod_count };
+ u32 size{ (u32)(sizeof(u32) + (sizeof(f32) + sizeof(lod_offset)) * lod_count) };
u32 mesh_count{ 0 };
for (u32 lod_idx{ 0 }; lod_idx < lod_count; ++lod_idx)
Commit: Gate D3D12 backend behind PRIMAL_GRAPHICS_D3D12
B4 — Make utl::vector relocation safe (+ free_list item fix)
The most important fix of the session (see Lessons). It also includes the overlapping-memcpy fix
in erase(). Found by ASan (overlap) and by DXC crashing on corrupted std::wstrings (relocation).
Edit Engine/Utilities/Vector.h
--- a/Engine/Utilities/Vector.h
+++ b/Engine/Utilities/Vector.h
@@ -2,6 +2,7 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
+#include <type_traits>
namespace primal::utl {
@@ -12,6 +13,15 @@
template<typename T, bool destruct = true>
class vector
{
+ // Items are relocated (when growing or erasing) with realloc()/memcpy() unless that would break
+ // them: types that aren't trivially copyable but have a move constructor are move-constructed
+ // instead. E.g. std::string/std::wstring and std::unordered_map in libstdc++ hold pointers into
+ // themselves; MSVC's happen to survive a byte copy. Types that can't be moved (DISABLE_MOVE)
+ // keep the bitwise relocation the engine relies on, and so does vector<T, false> (used by
+ // free_list), whose storage may contain destroyed items.
+ static constexpr bool relocate_with_move{ destruct && !std::is_trivially_copyable_v<T> &&
+ std::is_move_constructible_v<T> };
+
public:
// Default constructor. Doesn't allocate memory.
constexpr vector() = default;
@@ -167,6 +177,24 @@
{
if (new_capacity > _capacity)
{
+ if constexpr (relocate_with_move)
+ {
+ T *const new_buffer{ static_cast<T*>(malloc(new_capacity * sizeof(T))) };
+ assert(new_buffer);
+ if (new_buffer)
+ {
+ for (u64 i{ 0 }; i < _size; ++i)
+ {
+ new (std::addressof(new_buffer[i])) T(std::move(_data[i]));
+ _data[i].~T();
+ }
+ free(_data);
+ _data = new_buffer;
+ _capacity = new_capacity;
+ }
+ return;
+ }
+
// NOTE: realoc() will automatically copy the data in the buffer
// if a new region of memory is allocated.
void* new_buffer{ realloc(_data, new_capacity * sizeof(T)) };
@@ -195,7 +223,18 @@
--_size;
if (item < std::addressof(_data[_size]))
{
- memcpy(item, item + 1, (std::addressof(_data[_size]) - item) * sizeof(T));
+ if constexpr (relocate_with_move)
+ {
+ for (T* at{ item }; at < std::addressof(_data[_size]); ++at)
+ {
+ new (at) T(std::move(*(at + 1)));
+ (at + 1)->~T();
+ }
+ }
+ else
+ {
+ memmove(item, item + 1, (std::addressof(_data[_size]) - item) * sizeof(T));
+ }
}
return item;
@@ -217,7 +256,15 @@
--_size;
if (item < std::addressof(_data[_size]))
{
- memcpy(item, std::addressof(_data[_size]), sizeof(T));
+ if constexpr (relocate_with_move)
+ {
+ new (item) T(std::move(_data[_size]));
+ _data[_size].~T();
+ }
+ else
+ {
+ memcpy(item, std::addressof(_data[_size]), sizeof(T));
+ }
}
return item;
Edit Engine/Content/ContentToEngine.cpp — free_list relocates bitwise, so keep the map on the heap
--- a/Engine/Content/ContentToEngine.cpp
+++ b/Engine/Content/ContentToEngine.cpp
@@ -58,8 +58,10 @@
};
// NOTE: This is needed to maintain compatibility with STL vector.
+// NOTE: free_list relocates its items bitwise, which breaks std::unordered_map in libstdc++
+// (it can point into itself). Keeping the map on the heap makes the item relocatable.
struct noexcept_map {
- std::unordered_map<u32, std::unique_ptr<u8[]>> map;
+ std::unique_ptr<std::unordered_map<u32, std::unique_ptr<u8[]>>> map{ std::make_unique<std::unordered_map<u32, std::unique_ptr<u8[]>>>() };
noexcept_map() = default;
noexcept_map(const noexcept_map&) = default;
noexcept_map(noexcept_map&&) noexcept = default;
@@ -356,7 +358,7 @@
const u64 size{ shader_ptr->buffer_size() };
std::unique_ptr<u8[]> shader{ std::make_unique<u8[]>(size) };
memcpy(shader.get(), shaders[i], size);
- group.map[keys[i]] = std::move(shader);
+ (*group.map)[keys[i]] = std::move(shader);
}
std::lock_guard lock{ shader_mutex };
return shader_groups.add(std::move(group));
@@ -368,7 +370,7 @@
std::lock_guard lock{ shader_mutex };
assert(id::is_valid(id));
- shader_groups[id].map.clear();
+ shader_groups[id].map->clear();
shader_groups.remove(id);
}
@@ -378,7 +380,7 @@
std::lock_guard lock{ shader_mutex };
assert(id::is_valid(id));
- for (const auto& [key, value] : shader_groups[id].map)
+ for (const auto& [key, value] : *shader_groups[id].map)
{
if (key == shader_key)
{
Commit: Fix utl::vector relocation of non-trivially-relocatable types
B5 — EngineTest on Linux (entity components test)
Linux main() (no _CrtSetDbgFlag; use the sanitizer build for leaks), portable time_it.
The working-directory helper is still duplicated here; it moves into the platform layer in C2.
Edit EngineTest/Main.cpp
--- a/EngineTest/Main.cpp
+++ b/EngineTest/Main.cpp
@@ -16,9 +16,10 @@
#error One of the tests need to be enabled
#endif
-#ifdef _WIN64
+#include <filesystem>
+
+#if PRIMAL_PLATFORM_WINDOWS
#include <Windows.h>
-#include <filesystem>
// TODO: duplicate!
std::filesystem::path
@@ -63,19 +64,33 @@
return 0;
}
-#else
+#elif PRIMAL_PLATFORM_LINUX
+
+// TODO: duplicate!
+std::filesystem::path
+set_current_directory_to_executable_path()
+{
+ // set the working directory to the executable path
+ std::error_code ec;
+ const std::filesystem::path p{ std::filesystem::read_symlink("/proc/self/exe", ec) };
+ if (ec) return {};
+ std::filesystem::current_path(p.parent_path(), ec);
+ if (ec) return {};
+ return std::filesystem::current_path();
+}
+
+// NOTE: there is no _CrtSetDbgFlag on Linux. For leak checking, configure with
+// -DPRIMAL_ENABLE_SANITIZERS=ON (AddressSanitizer includes LeakSanitizer).
int main()
{
-#if _DEBUG
- _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
-#endif
+ set_current_directory_to_executable_path();
engine_test test{};
-
if (test.initialize())
{
+ // TODO: replace with the platform event pump once the platform layer is ported (Phase 3).
test.run();
}
-
test.shutdown();
+ return 0;
}
-#endif // _WIN64
+#endif
Edit EngineTest/Test.h
--- a/EngineTest/Test.h
+++ b/EngineTest/Test.h
@@ -1,6 +1,7 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
+#include "../Engine/Common/PlatformDetection.h"
#include <thread>
#include <chrono>
#include <string>
@@ -23,13 +24,17 @@
virtual void shutdown() = 0;
};
-#if _WIN64
+#if PRIMAL_PLATFORM_WINDOWS
#include <Windows.h>
+#else
+#include <cstdio>
+#endif
+
class time_it
{
public:
- using clock = std::chrono::high_resolution_clock;
- using time_stamp = std::chrono::steady_clock::time_point;
+ using clock = std::chrono::steady_clock;
+ using time_stamp = clock::time_point;
// Average frame time per second.
constexpr float dt_avg() const { return _dt_avg * 1e-6f; }
@@ -48,11 +53,13 @@
if (std::chrono::duration_cast<std::chrono::seconds>(clock::now() - _seconds).count() >= 1)
{
- OutputDebugStringA("Avg. frame (ms): ");
- OutputDebugStringA(std::to_string(_us_avg * 0.001f).c_str());
- OutputDebugStringA((" " + std::to_string(_counter)).c_str());
- OutputDebugStringA(" fps");
- OutputDebugStringA("\n");
+ const std::string msg{ "Avg. frame (ms): " + std::to_string(_us_avg * 0.001f) +
+ " " + std::to_string(_counter) + " fps\n" };
+#if PRIMAL_PLATFORM_WINDOWS
+ OutputDebugStringA(msg.c_str());
+#else
+ std::fputs(msg.c_str(), stderr);
+#endif
_us_avg = 0.f;
_counter = 1;
_seconds = clock::now();
@@ -66,4 +73,3 @@
time_stamp _start;
time_stamp _seconds{ clock::now() };
};
-#endif // _WIN64
Verify:
cmake --preset linux-debug -DPRIMAL_ENGINE_TEST=ENTITY_COMPONENTS && cmake --build --preset linux-debug
cd x64/Debug && printf 'x\nq\n' | ./EngineTest # prints 'Entities created/deleted' and exits
# repeat with the sanitizer build: must exit 0 with no ASan/UBSan reports
Commit: Run the entity components test on Linux → Windows checkpoint.
C. Phase 3 — One platform API for both platforms (TEST_WINDOW runs)
The Win32 WNDPROC callback, wchar_t captions and raw HWNDs are replaced by a shared API:
window_event_callback, UTF-8 captions, native_window_handle, pump_events()/post_quit(),
window::close() and set_current_directory_to_executable_path(). C2 and C3 must be committed
together — after C2 alone, the Windows consumers don't compile.
C1 — Key mapping helpers (Win32) and SDL input
Edit Engine/Input/InputWin32.h
--- a/Engine/Input/InputWin32.h
+++ b/Engine/Input/InputWin32.h
@@ -1,8 +1,8 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
-#ifdef _WIN64
#include "CommonHeaders.h"
+#if PRIMAL_PLATFORM_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
@@ -14,6 +14,12 @@
HRESULT process_input_message(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
+// Maps a virtual key code to an input code. Returns u32_invalid_id for unmapped keys.
+u32 map_virtual_key(u32 virtual_key);
+
+// Currently held modifier keys as modifier_key::key flags.
+u32 modifier_keys();
+
}
-#endif // !_WIN64
+#endif // PRIMAL_PLATFORM_WINDOWS
Edit Engine/Input/InputWin32.cpp
--- a/Engine/Input/InputWin32.cpp
+++ b/Engine/Input/InputWin32.cpp
@@ -1,8 +1,7 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
-#ifdef _WIN64
-
#include "InputWin32.h"
+#if PRIMAL_PLATFORM_WINDOWS
#include "Input.h"
namespace primal::input {
@@ -339,6 +338,25 @@
} // anonymous namespace
+u32
+map_virtual_key(u32 virtual_key)
+{
+ return virtual_key <= 0xff ? vk_mapping[virtual_key] : u32_invalid_id;
+}
+
+u32
+modifier_keys()
+{
+ u32 keys{ modifier_key::none };
+ if (GetKeyState(VK_LSHIFT) < 0) keys |= modifier_key::left_shift;
+ if (GetKeyState(VK_RSHIFT) < 0) keys |= modifier_key::right_shift;
+ if (GetKeyState(VK_LCONTROL) < 0) keys |= modifier_key::left_ctrl;
+ if (GetKeyState(VK_RCONTROL) < 0) keys |= modifier_key::right_ctrl;
+ if (GetKeyState(VK_LMENU) < 0) keys |= modifier_key::left_alt;
+ if (GetKeyState(VK_RMENU) < 0) keys |= modifier_key::right_alt;
+ return keys;
+}
+
HRESULT
process_input_message(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
New file Engine/Input/InputSDL.h
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
#if PRIMAL_PLATFORM_LINUX
#include "EngineAPI/Input.h"
union SDL_Event;
namespace primal::input {
// Updates the input state from an SDL keyboard, mouse button, mouse motion or mouse wheel event.
// Other events are ignored.
void process_input_event(const SDL_Event& event);
// Maps an SDL_Scancode to an input code. Returns u32_invalid_id for unmapped keys.
u32 map_scancode(u32 scancode);
// Currently held modifier keys as modifier_key::key flags.
u32 modifier_keys();
}
#endif // PRIMAL_PLATFORM_LINUX
New file Engine/Input/InputSDL.cpp
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "InputSDL.h"
#if PRIMAL_PLATFORM_LINUX
#include "Input.h"
#include <SDL3/SDL.h>
// SDL counterpart of InputWin32.cpp. Keys are mapped by physical position (SDL scancodes),
// so e.g. key_w is the key left of key_e regardless of the keyboard layout.
namespace primal::input {
namespace {
// Mouse wheel delta for one notch, to match Win32 (WHEEL_DELTA).
constexpr f32 wheel_delta{ 120.f };
u32 held_modifiers{ modifier_key::none };
void
set_modifier(u32 flag, bool is_down)
{
if (is_down) held_modifiers |= flag;
else held_modifiers &= ~flag;
}
// Win32 sends both the generic key (e.g. key_shift) and the left/right variant.
// Do the same here. The generic key stays down while either side is held.
void
set_modifier_key(input_code::code side_code, u32 side_flag, input_code::code generic_code, u32 generic_flags, bool is_down)
{
set_modifier(side_flag, is_down);
set(input_source::keyboard, side_code, { is_down ? 1.f : 0.f, 0.f, 0.f });
set(input_source::keyboard, generic_code, { (held_modifiers & generic_flags) ? 1.f : 0.f, 0.f, 0.f });
}
bool
process_modifier(SDL_Scancode scancode, bool is_down)
{
switch (scancode)
{
case SDL_SCANCODE_LSHIFT: set_modifier_key(input_code::key_left_shift, modifier_key::left_shift, input_code::key_shift, modifier_key::shift, is_down); return true;
case SDL_SCANCODE_RSHIFT: set_modifier_key(input_code::key_right_shift, modifier_key::right_shift, input_code::key_shift, modifier_key::shift, is_down); return true;
case SDL_SCANCODE_LCTRL: set_modifier_key(input_code::key_left_control, modifier_key::left_ctrl, input_code::key_control, modifier_key::ctrl, is_down); return true;
case SDL_SCANCODE_RCTRL: set_modifier_key(input_code::key_right_control, modifier_key::right_ctrl, input_code::key_control, modifier_key::ctrl, is_down); return true;
case SDL_SCANCODE_LALT: set_modifier_key(input_code::key_left_alt, modifier_key::left_alt, input_code::key_alt, modifier_key::alt, is_down); return true;
case SDL_SCANCODE_RALT: set_modifier_key(input_code::key_right_alt, modifier_key::right_alt, input_code::key_alt, modifier_key::alt, is_down); return true;
default: return false;
}
}
input_code::code
mouse_button_code(u8 button)
{
switch (button)
{
case SDL_BUTTON_LEFT: return input_code::mouse_left;
case SDL_BUTTON_RIGHT: return input_code::mouse_right;
case SDL_BUTTON_MIDDLE: return input_code::mouse_middle;
default: return (input_code::code)u32_invalid_id;
}
}
} // anonymous namespace
u32
map_scancode(u32 scancode)
{
switch ((SDL_Scancode)scancode)
{
case SDL_SCANCODE_BACKSPACE: return input_code::key_backspace;
case SDL_SCANCODE_TAB: return input_code::key_tab;
case SDL_SCANCODE_RETURN: return input_code::key_return;
case SDL_SCANCODE_KP_ENTER: return input_code::key_return; // Win32 reports VK_RETURN for both
case SDL_SCANCODE_LSHIFT: return input_code::key_left_shift;
case SDL_SCANCODE_RSHIFT: return input_code::key_right_shift;
case SDL_SCANCODE_LCTRL: return input_code::key_left_control;
case SDL_SCANCODE_RCTRL: return input_code::key_right_control;
case SDL_SCANCODE_LALT: return input_code::key_left_alt;
case SDL_SCANCODE_RALT: return input_code::key_right_alt;
case SDL_SCANCODE_PAUSE: return input_code::key_pause;
case SDL_SCANCODE_CAPSLOCK: return input_code::key_capslock;
case SDL_SCANCODE_ESCAPE: return input_code::key_escape;
case SDL_SCANCODE_SPACE: return input_code::key_space;
case SDL_SCANCODE_PAGEUP: return input_code::key_page_up;
case SDL_SCANCODE_PAGEDOWN: return input_code::key_page_down;
case SDL_SCANCODE_HOME: return input_code::key_home;
case SDL_SCANCODE_END: return input_code::key_end;
case SDL_SCANCODE_LEFT: return input_code::key_left;
case SDL_SCANCODE_UP: return input_code::key_up;
case SDL_SCANCODE_RIGHT: return input_code::key_right;
case SDL_SCANCODE_DOWN: return input_code::key_down;
case SDL_SCANCODE_PRINTSCREEN: return input_code::key_print_screen;
case SDL_SCANCODE_INSERT: return input_code::key_insert;
case SDL_SCANCODE_DELETE: return input_code::key_delete;
case SDL_SCANCODE_0: return input_code::key_0;
case SDL_SCANCODE_1: return input_code::key_1;
case SDL_SCANCODE_2: return input_code::key_2;
case SDL_SCANCODE_3: return input_code::key_3;
case SDL_SCANCODE_4: return input_code::key_4;
case SDL_SCANCODE_5: return input_code::key_5;
case SDL_SCANCODE_6: return input_code::key_6;
case SDL_SCANCODE_7: return input_code::key_7;
case SDL_SCANCODE_8: return input_code::key_8;
case SDL_SCANCODE_9: return input_code::key_9;
case SDL_SCANCODE_A: return input_code::key_a;
case SDL_SCANCODE_B: return input_code::key_b;
case SDL_SCANCODE_C: return input_code::key_c;
case SDL_SCANCODE_D: return input_code::key_d;
case SDL_SCANCODE_E: return input_code::key_e;
case SDL_SCANCODE_F: return input_code::key_f;
case SDL_SCANCODE_G: return input_code::key_g;
case SDL_SCANCODE_H: return input_code::key_h;
case SDL_SCANCODE_I: return input_code::key_i;
case SDL_SCANCODE_J: return input_code::key_j;
case SDL_SCANCODE_K: return input_code::key_k;
case SDL_SCANCODE_L: return input_code::key_l;
case SDL_SCANCODE_M: return input_code::key_m;
case SDL_SCANCODE_N: return input_code::key_n;
case SDL_SCANCODE_O: return input_code::key_o;
case SDL_SCANCODE_P: return input_code::key_p;
case SDL_SCANCODE_Q: return input_code::key_q;
case SDL_SCANCODE_R: return input_code::key_r;
case SDL_SCANCODE_S: return input_code::key_s;
case SDL_SCANCODE_T: return input_code::key_t;
case SDL_SCANCODE_U: return input_code::key_u;
case SDL_SCANCODE_V: return input_code::key_v;
case SDL_SCANCODE_W: return input_code::key_w;
case SDL_SCANCODE_X: return input_code::key_x;
case SDL_SCANCODE_Y: return input_code::key_y;
case SDL_SCANCODE_Z: return input_code::key_z;
case SDL_SCANCODE_KP_0: return input_code::key_numpad_0;
case SDL_SCANCODE_KP_1: return input_code::key_numpad_1;
case SDL_SCANCODE_KP_2: return input_code::key_numpad_2;
case SDL_SCANCODE_KP_3: return input_code::key_numpad_3;
case SDL_SCANCODE_KP_4: return input_code::key_numpad_4;
case SDL_SCANCODE_KP_5: return input_code::key_numpad_5;
case SDL_SCANCODE_KP_6: return input_code::key_numpad_6;
case SDL_SCANCODE_KP_7: return input_code::key_numpad_7;
case SDL_SCANCODE_KP_8: return input_code::key_numpad_8;
case SDL_SCANCODE_KP_9: return input_code::key_numpad_9;
case SDL_SCANCODE_KP_MULTIPLY: return input_code::key_multiply;
case SDL_SCANCODE_KP_PLUS: return input_code::key_add;
case SDL_SCANCODE_KP_MINUS: return input_code::key_subtract;
case SDL_SCANCODE_KP_PERIOD: return input_code::key_decimal;
case SDL_SCANCODE_KP_DIVIDE: return input_code::key_divide;
case SDL_SCANCODE_F1: return input_code::key_f1;
case SDL_SCANCODE_F2: return input_code::key_f2;
case SDL_SCANCODE_F3: return input_code::key_f3;
case SDL_SCANCODE_F4: return input_code::key_f4;
case SDL_SCANCODE_F5: return input_code::key_f5;
case SDL_SCANCODE_F6: return input_code::key_f6;
case SDL_SCANCODE_F7: return input_code::key_f7;
case SDL_SCANCODE_F8: return input_code::key_f8;
case SDL_SCANCODE_F9: return input_code::key_f9;
case SDL_SCANCODE_F10: return input_code::key_f10;
case SDL_SCANCODE_F11: return input_code::key_f11;
case SDL_SCANCODE_F12: return input_code::key_f12;
case SDL_SCANCODE_NUMLOCKCLEAR: return input_code::key_numlock;
case SDL_SCANCODE_SCROLLLOCK: return input_code::key_scrollock;
case SDL_SCANCODE_SEMICOLON: return input_code::key_colon; // VK_OEM_1
case SDL_SCANCODE_EQUALS: return input_code::key_plus; // VK_OEM_PLUS
case SDL_SCANCODE_COMMA: return input_code::key_comma;
case SDL_SCANCODE_MINUS: return input_code::key_minus;
case SDL_SCANCODE_PERIOD: return input_code::key_period;
case SDL_SCANCODE_SLASH: return input_code::key_question; // VK_OEM_2
case SDL_SCANCODE_LEFTBRACKET: return input_code::key_bracket_open; // VK_OEM_4
case SDL_SCANCODE_BACKSLASH: return input_code::key_pipe; // VK_OEM_5
case SDL_SCANCODE_RIGHTBRACKET: return input_code::key_bracket_close;// VK_OEM_6
case SDL_SCANCODE_APOSTROPHE: return input_code::key_quote; // VK_OEM_7
case SDL_SCANCODE_GRAVE: return input_code::key_tilde; // VK_OEM_3
default: return u32_invalid_id;
}
}
u32
modifier_keys()
{
return held_modifiers;
}
void
process_input_event(const SDL_Event& event)
{
switch (event.type)
{
case SDL_EVENT_KEY_DOWN:
case SDL_EVENT_KEY_UP:
{
const bool is_down{ event.type == SDL_EVENT_KEY_DOWN };
if (process_modifier(event.key.scancode, is_down)) break;
const u32 code{ map_scancode(event.key.scancode) };
if (code != u32_invalid_id)
{
set(input_source::keyboard, (input_code::code)code, { is_down ? 1.f : 0.f, 0.f, 0.f });
}
}
break;
case SDL_EVENT_MOUSE_MOTION:
{
const f32 x{ event.motion.x };
const f32 y{ event.motion.y };
set(input_source::mouse, input_code::mouse_position_x, { x, 0.f, 0.f });
set(input_source::mouse, input_code::mouse_position_y, { y, 0.f, 0.f });
set(input_source::mouse, input_code::mouse_position, { x, y, 0.f });
}
break;
case SDL_EVENT_MOUSE_BUTTON_DOWN:
case SDL_EVENT_MOUSE_BUTTON_UP:
{
// NOTE: SDL captures the mouse while a button is held (SDL_HINT_MOUSE_AUTO_CAPTURE),
// like SetCapture()/ReleaseCapture() in InputWin32.cpp.
const input_code::code code{ mouse_button_code(event.button.button) };
if (code != u32_invalid_id)
{
const f32 pressed{ event.type == SDL_EVENT_MOUSE_BUTTON_DOWN ? 1.f : 0.f };
set(input_source::mouse, code, { event.button.x, event.button.y, pressed });
}
}
break;
case SDL_EVENT_MOUSE_WHEEL:
{
f32 notches{ event.wheel.y };
if (event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) notches = -notches;
set(input_source::mouse, input_code::mouse_wheel, { notches * wheel_delta, 0.f, 0.f });
}
break;
default:
break;
}
}
}
#endif // PRIMAL_PLATFORM_LINUX
Commit: together with C2/C3, or alone (it compiles on its own: InputSDL isn't in CMake until C2).
C2 — Shared platform API and both platform layers
Replace Engine/Platform/PlatformTypes.h — the shared API (no more window_proc)
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
#include "Window.h"
#include "EngineAPI/Input.h"
#if PRIMAL_PLATFORM_WINDOWS
// NOTE: kept so code that relied on PlatformTypes.h pulling in Windows.h keeps compiling.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#endif // PRIMAL_PLATFORM_WINDOWS
namespace primal::platform {
// Opaque native window handle. Graphics backends create their surfaces from this (an HWND for
// DXGI, or a VkSurfaceKHR via VK_KHR_win32/xlib/wayland_surface), never from SDL objects, so
// windows created by a host application (the editor) work the same way.
// NOTE: window::handle() points into the platform's window list: copy the struct if it's needed
// after the next create_window()/remove_window().
struct native_window_handle
{
enum kind_t : u32 {
none,
win32, // display: HINSTANCE, window: HWND
x11, // display: Display*, window: X11 Window (XID)
wayland, // display: wl_display*, window: wl_surface*
};
kind_t kind{ none };
void* display{ nullptr };
u64 window{ 0 }; // the handle/pointer value cast to u64
};
using window_handle = const native_window_handle*;
struct window_event
{
enum type_t : u32 {
closed, // the user asked to close the window (it's hidden; call remove_window() to destroy it)
resized, // the client area changed size (sent once a drag-resize finishes)
key_down, // key repeats update the input state but aren't sent as events
key_up,
};
type_t type{};
window_id window{ id::invalid_id };
input::input_code::code key{}; // key_down / key_up
u32 modifiers{ 0 }; // input::modifier_key::key flags (key_down / key_up)
};
// Called from pump_events() (or the host's message loop for parented windows).
// It's safe to remove the window, or any other window, from the callback.
using window_event_callback = void(*)(const window_event&);
struct window_init_info
{
window_event_callback callback{ nullptr };
window_handle parent{ nullptr }; // host window for a child window (editor viewport)
const char* caption{ nullptr }; // UTF-8
s32 left{ 0 };
s32 top{ 0 };
s32 width{ 1920 };
s32 height{ 1080 };
};
// Processes all pending window and input events. Returns false once a quit was requested.
bool pump_events();
// Asks the application to quit: pump_events() returns false from now on (like PostQuitMessage).
void post_quit();
}
Edit Engine/Platform/Window.h
--- a/Engine/Platform/Window.h
+++ b/Engine/Platform/Window.h
@@ -6,6 +6,7 @@
namespace primal::platform {
DEFINE_TYPED_ID(window_id);
+struct native_window_handle;
class window
{
@@ -17,13 +18,15 @@
void set_fullscreen(bool is_fullscreen) const;
bool is_fullscreen() const;
- void* handle() const;
- void set_caption(const wchar_t* caption) const;
+ const native_window_handle* handle() const;
+ void set_caption(const char* caption) const; // UTF-8
math::u32v4 size() const;
void resize(u32 width, u32 height) const;
u32 width() const;
u32 height() const;
bool is_closed() const;
+ // Same as the user closing the window: it's hidden and a window_event::closed is sent.
+ void close() const;
private:
window_id _id{ id::invalid_id };
};
Edit Engine/Platform/Window.cpp
--- a/Engine/Platform/Window.cpp
+++ b/Engine/Platform/Window.cpp
@@ -19,7 +19,7 @@
return is_window_fullscreen(_id);
}
-void*
+const native_window_handle*
window::handle() const
{
assert(is_valid());
@@ -27,7 +27,7 @@
}
void
-window::set_caption(const wchar_t* caption) const
+window::set_caption(const char* caption) const
{
assert(is_valid());
set_window_caption(_id, caption);
@@ -67,5 +67,12 @@
assert(is_valid());
return is_window_closed(_id);
}
+
+void
+window::close() const
+{
+ assert(is_valid());
+ close_window(_id);
+}
}
#endif // INCLUDE_WINDOW_CPP
Edit Engine/Platform/Platform.h
--- a/Engine/Platform/Platform.h
+++ b/Engine/Platform/Platform.h
@@ -3,6 +3,7 @@
#pragma once
#include "CommonHeaders.h"
#include "Window.h"
+#include <filesystem>
namespace primal::platform {
@@ -10,4 +11,8 @@
window create_window(const window_init_info* const init_info = nullptr);
void remove_window(window_id id);
+
+// Sets the working directory to the folder of the running executable.
+// Returns the new working directory, or an empty path on failure.
+std::filesystem::path set_current_directory_to_executable_path();
}
Replace Engine/Platform/PlatformWin32.cpp — messages → events, WM_CLOSE hides, UTF-8 → UTF-16, mouse tracking for child windows, pump_events
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "CommonHeaders.h"
#if PRIMAL_PLATFORM_WINDOWS
#include "Platform.h"
#include "PlatformTypes.h"
#include "Input/InputWin32.h"
#include <string>
namespace primal::platform {
namespace {
struct window_info
{
HWND hwnd{ nullptr };
window_event_callback callback{ nullptr };
native_window_handle native{};
RECT client_area{ 0, 0, 1920, 1080 };
RECT fullscreen_area{};
POINT top_left{ 0, 0 };
DWORD style{ WS_VISIBLE };
bool is_fullscreen{ false };
bool is_closed{ false };
bool is_tracking_mouse{ false };
};
utl::free_list<window_info> windows;
bool quit_requested{ false };
window_info&
get_from_id(window_id id)
{
assert(windows[id].hwnd);
return windows[id];
}
window_id
get_id_from_handle(HWND handle)
{
return window_id{ (id::id_type)GetWindowLongPtr(handle, GWLP_USERDATA) };
}
window_info&
get_from_handle(HWND handle)
{
return get_from_id(get_id_from_handle(handle));
}
std::wstring
to_wide(const char* utf8)
{
if (!utf8 || !*utf8) return {};
const int length{ MultiByteToWideChar(CP_UTF8, 0, utf8, -1, nullptr, 0) };
if (length <= 0) return {};
std::wstring wide((size_t)length, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wide.data(), length);
wide.resize((size_t)length - 1); // drop the terminating null
return wide;
}
// Lets a host (the editor) get WM_MOUSEHOVER/WM_MOUSELEAVE for child windows.
void
track_mouse(HWND hwnd)
{
TRACKMOUSEEVENT tme{};
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER | TME_LEAVE;
tme.dwHoverTime = 10;
tme.hwndTrack = hwnd;
TrackMouseEvent(&tme);
}
bool
is_key_message(UINT msg)
{
return msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP;
}
bool resized{ false };
LRESULT CALLBACK internal_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_NCCREATE:
{
// Put the window id in the user data field of window's data buffer.
DEBUG_OP(SetLastError(0));
const window_id id{ windows.add() };
windows[id].hwnd = hwnd;
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)id);
assert(GetLastError() == 0);
}
break;
case WM_CLOSE:
{
// Hide instead of destroying, so the HWND stays valid until remove_window().
window_info& info{ get_from_handle(hwnd) };
info.is_closed = true;
ShowWindow(hwnd, SW_HIDE);
if (info.callback) info.callback({ window_event::closed, get_id_from_handle(hwnd) });
return 0;
}
case WM_DESTROY:
get_from_handle(hwnd).is_closed = true;
break;
case WM_SIZE:
resized = (wparam != SIZE_MINIMIZED);
break;
case WM_MOUSEMOVE:
{
window_info& info{ get_from_handle(hwnd) };
if ((info.style & WS_CHILD) && !info.is_tracking_mouse)
{
track_mouse(hwnd);
info.is_tracking_mouse = true;
}
}
break;
case WM_MOUSELEAVE:
get_from_handle(hwnd).is_tracking_mouse = false;
break;
default:
break;
}
input::process_input_message(hwnd, msg, wparam, lparam);
// Collect the event now, but send it last: the callback is allowed to remove this window.
window_event event{};
bool has_event{ false };
if (resized && GetKeyState(VK_LBUTTON) >= 0)
{
window_info& info{ get_from_handle(hwnd) };
assert(info.hwnd);
GetClientRect(info.hwnd, info.is_fullscreen ? &info.fullscreen_area : &info.client_area);
resized = false;
event = { window_event::resized, get_id_from_handle(hwnd) };
has_event = true;
}
else if (is_key_message(msg))
{
const bool is_down{ msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN };
const bool is_repeat{ is_down && (lparam & (1 << 30)) };
const u32 code{ input::map_virtual_key((u32)wparam) };
if (!is_repeat && code != u32_invalid_id)
{
event = { is_down ? window_event::key_down : window_event::key_up, get_id_from_handle(hwnd) };
event.key = (input::input_code::code)code;
event.modifiers = input::modifier_keys();
has_event = true;
}
}
const window_event_callback callback{ has_event ? get_from_handle(hwnd).callback : nullptr };
LRESULT result{ 0 };
if (msg == WM_SYSCOMMAND && wparam == SC_KEYMENU)
{
// Don't activate the (non-existent) window menu when Alt is pressed.
result = 0;
}
else if (msg == WM_SYSCHAR && wparam == VK_RETURN && (HIWORD(lparam) & KF_ALTDOWN))
{
result = 0;
}
else
{
result = DefWindowProc(hwnd, msg, wparam, lparam);
}
if (callback) callback(event);
return result;
}
void
resize_window(const window_info& info, const RECT& area)
{
// Adjust the window size for correct device size
RECT window_rect{ area };
AdjustWindowRect(&window_rect, info.style, FALSE);
const s32 width{ window_rect.right - window_rect.left };
const s32 height{ window_rect.bottom - window_rect.top };
MoveWindow(info.hwnd, info.top_left.x, info.top_left.y, width, height, true);
}
void
resize_window(window_id id, u32 width, u32 height)
{
window_info& info{ get_from_id(id) };
// NOTE: when we host the window in the level editor we just update
// the internal data (i.e. the client area dimensions).
if (info.style & WS_CHILD)
{
GetClientRect(info.hwnd, &info.client_area);
}
else
{
// NOTE: we also resize while in fullscreen mode to support the case
// when the user changes the screen resolution.
RECT& area{ info.is_fullscreen ? info.fullscreen_area : info.client_area };
area.bottom = area.top + height;
area.right = area.left + width;
resize_window(info, area);
}
}
void
set_window_fullscreen(window_id id, bool is_fullscreen)
{
window_info& info{ get_from_id(id) };
if (info.is_fullscreen != is_fullscreen)
{
info.is_fullscreen = is_fullscreen;
if (is_fullscreen)
{
// Store the current window dimensions so they can be restored
// when switching out of fullscreen state.
GetClientRect(info.hwnd, &info.client_area);
RECT rect;
GetWindowRect(info.hwnd, &rect);
info.top_left.x = rect.left;
info.top_left.y = rect.top;
SetWindowLongPtr(info.hwnd, GWL_STYLE, 0);
ShowWindow(info.hwnd, SW_MAXIMIZE);
}
else
{
SetWindowLongPtr(info.hwnd, GWL_STYLE, info.style);
resize_window(info, info.client_area);
ShowWindow(info.hwnd, SW_SHOWNORMAL);
}
}
}
bool
is_window_fullscreen(window_id id)
{
return get_from_id(id).is_fullscreen;
}
window_handle
get_window_handle(window_id id)
{
return &get_from_id(id).native;
}
void
set_window_caption(window_id id, const char* caption)
{
window_info& info{ get_from_id(id) };
SetWindowTextW(info.hwnd, to_wide(caption).c_str());
}
math::u32v4
get_window_size(window_id id)
{
window_info& info{ get_from_id(id) };
RECT& area{ info.is_fullscreen ? info.fullscreen_area : info.client_area };
return { (u32)area.left, (u32)area.top, (u32)area.right, (u32)area.bottom };
}
bool
is_window_closed(window_id id)
{
return get_from_id(id).is_closed;
}
void
close_window(window_id id)
{
PostMessage(get_from_id(id).hwnd, WM_CLOSE, 0, 0);
}
} // anonymous namespace
window
create_window(const window_init_info* init_info /* = nullptr */)
{
HWND parent{ (init_info && init_info->parent) ? (HWND)init_info->parent->window : nullptr };
assert(!init_info || !init_info->parent || init_info->parent->kind == native_window_handle::win32);
// Setup a window class
WNDCLASSEXW wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEXW);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = internal_window_proc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = 0;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = CreateSolidBrush(RGB(26, 48, 76));
wc.lpszMenuName = NULL;
wc.lpszClassName = L"PrimalWindow";
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
// Register the window class
RegisterClassExW(&wc);
window_info info{};
info.callback = init_info ? init_info->callback : nullptr;
info.client_area.right = (init_info && init_info->width) ? info.client_area.left + init_info->width : info.client_area.right;
info.client_area.bottom = (init_info && init_info->height) ? info.client_area.top + init_info->height : info.client_area.bottom;
info.style |= parent ? WS_CHILD : WS_OVERLAPPEDWINDOW;
RECT rect{ info.client_area };
// adjust the window size for correct device size
AdjustWindowRect(&rect, info.style, FALSE);
const std::wstring caption{ to_wide((init_info && init_info->caption) ? init_info->caption : "Primal Game") };
const s32 left{ init_info ? init_info->left : info.top_left.x };
const s32 top{ init_info ? init_info->top : info.top_left.y };
const s32 width{ rect.right - rect.left };
const s32 height{ rect.bottom - rect.top };
// Create an instance of the window class
info.hwnd = CreateWindowExW(
0, // extended style
wc.lpszClassName, // window class name
caption.c_str(), // instance title
info.style, // window style
left, top, // initial window position
width, height, // initial window dimensions
parent, // handle to parent window
NULL, // handle to menu
NULL, // intance of this application
NULL); // extra creation parameters
if (info.hwnd)
{
info.native = { native_window_handle::win32, (void*)GetModuleHandleW(nullptr), (u64)info.hwnd };
ShowWindow(info.hwnd, SW_SHOWNORMAL);
UpdateWindow(info.hwnd);
window_id id{ get_id_from_handle(info.hwnd) };
windows[id] = info;
return window{ id };
}
return {};
}
void
remove_window(window_id id)
{
window_info& info{ get_from_id(id) };
DestroyWindow(info.hwnd);
windows.remove(id);
}
std::filesystem::path
set_current_directory_to_executable_path()
{
wchar_t path[MAX_PATH]{};
const u32 length{ GetModuleFileNameW(0, &path[0], MAX_PATH) };
if (!length || GetLastError() == ERROR_INSUFFICIENT_BUFFER) return {};
std::error_code ec;
std::filesystem::current_path(std::filesystem::path{ path }.parent_path(), ec);
if (ec) return {};
return std::filesystem::current_path();
}
bool
pump_events()
{
MSG msg{};
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
if (msg.message == WM_QUIT) quit_requested = true;
}
return !quit_requested;
}
void
post_quit()
{
quit_requested = true;
}
}
#include "IncludeWindowCpp.h"
#endif // PRIMAL_PLATFORM_WINDOWS
New file Engine/Platform/PlatformLinux.cpp
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "CommonHeaders.h"
#if PRIMAL_PLATFORM_LINUX
#include "Platform.h"
#include "PlatformTypes.h"
#include "Input/InputSDL.h"
#include <SDL3/SDL.h>
#include <cstdio>
// Linux counterpart of PlatformWin32.cpp, using SDL3 for standalone windows.
// Graphics backends must use window::handle() (a native_window_handle), not SDL objects.
namespace primal::platform {
namespace {
struct window_info
{
SDL_Window* sdl_window{ nullptr };
window_event_callback callback{ nullptr };
native_window_handle native{};
bool is_fullscreen{ false };
bool is_closed{ false };
};
constexpr const char* window_id_property{ "primal.window_id" };
// Background color used until a graphics surface draws to the window.
// Same as the window class brush in PlatformWin32.cpp: RGB(26, 48, 76).
constexpr u8 background_color[3]{ 26, 48, 76 };
utl::free_list<window_info> windows;
u32 window_count{ 0 };
bool quit_requested{ false };
bool is_pumping_events{ false };
window_info&
get_from_id(window_id id)
{
assert(windows[id].sdl_window);
return windows[id];
}
// Returns false if the SDL window isn't one of ours (or doesn't exist anymore).
bool
get_id_from_sdl(SDL_WindowID sdl_id, window_id& id)
{
SDL_Window *const sdl_window{ SDL_GetWindowFromID(sdl_id) };
if (!sdl_window) return false;
const s64 value{ SDL_GetNumberProperty(SDL_GetWindowProperties(sdl_window), window_id_property, -1) };
if (value < 0) return false;
id = window_id{ (id::id_type)value };
return true;
}
bool
init_video()
{
if (SDL_WasInit(SDL_INIT_VIDEO)) return true;
// Like Win32: closing the last window doesn't quit. The application decides (post_quit()).
SDL_SetHint(SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE, "0");
if (!SDL_InitSubSystem(SDL_INIT_VIDEO))
{
std::fprintf(stderr, "SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s\n", SDL_GetError());
return false;
}
return true;
}
// NOTE: deferred while pump_events() runs: an event callback may remove all windows and then
// create new ones (e.g. a restart), and SDL must stay initialized for the rest of the loop.
void
shutdown_video()
{
if (window_count == 0 && !is_pumping_events && SDL_WasInit(SDL_INIT_VIDEO))
{
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
}
bool
query_native_handle(SDL_Window* sdl_window, native_window_handle& handle)
{
const SDL_PropertiesID props{ SDL_GetWindowProperties(sdl_window) };
const char *const driver{ SDL_GetCurrentVideoDriver() };
handle = {};
if (driver && SDL_strcmp(driver, "x11") == 0)
{
handle.kind = native_window_handle::x11;
handle.display = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, nullptr);
handle.window = (u64)SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0);
}
else if (driver && SDL_strcmp(driver, "wayland") == 0)
{
handle.kind = native_window_handle::wayland;
handle.display = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, nullptr);
handle.window = (u64)(uintptr_t)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, nullptr);
}
else
{
std::fprintf(stderr, "Unsupported SDL video driver: %s\n", driver ? driver : "(none)");
return false;
}
return handle.display && handle.window;
}
// TODO: once a graphics backend creates a surface for a window, it must stop this
// (SDL_DestroyWindowSurface) before creating its swapchain.
void
paint_background(const window_info& info)
{
SDL_Surface *const surface{ SDL_GetWindowSurface(info.sdl_window) };
if (!surface) return;
const u32 color{ SDL_MapSurfaceRGB(surface, background_color[0], background_color[1], background_color[2]) };
SDL_FillSurfaceRect(surface, nullptr, color);
SDL_UpdateWindowSurface(info.sdl_window);
}
void
send_event(const window_info& info, const window_event& event)
{
if (info.callback) info.callback(event);
}
void
process_window_event(const SDL_Event& e)
{
window_id id{};
if (!get_id_from_sdl(e.window.windowID, id)) return;
window_info& info{ get_from_id(id) };
switch (e.type)
{
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
// Hide instead of destroying, so the native handle stays valid until remove_window().
// (On Win32 the HWND is destroyed here, and is_closed() becomes true.)
info.is_closed = true;
SDL_HideWindow(info.sdl_window);
send_event(info, { window_event::closed, id });
break;
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
paint_background(info);
send_event(info, { window_event::resized, id });
break;
case SDL_EVENT_WINDOW_EXPOSED:
paint_background(info);
break;
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN:
info.is_fullscreen = true;
break;
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN:
info.is_fullscreen = false;
break;
default:
break;
}
}
void
process_key_event(const SDL_Event& e)
{
input::process_input_event(e);
// Key repeats update the input state above, but aren't sent as window events.
if (e.key.repeat) return;
window_id id{};
if (!get_id_from_sdl(e.key.windowID, id)) return;
const u32 code{ input::map_scancode(e.key.scancode) };
if (code == u32_invalid_id) return;
window_event event{ e.type == SDL_EVENT_KEY_DOWN ? window_event::key_down : window_event::key_up, id };
event.key = (input::input_code::code)code;
event.modifiers = input::modifier_keys();
send_event(get_from_id(id), event);
}
void
resize_window(window_id id, u32 width, u32 height)
{
window_info& info{ get_from_id(id) };
// NOTE: like PlatformWin32.cpp, this also resizes while in fullscreen mode.
SDL_SetWindowSize(info.sdl_window, (int)width, (int)height);
}
void
set_window_fullscreen(window_id id, bool is_fullscreen)
{
window_info& info{ get_from_id(id) };
if (info.is_fullscreen != is_fullscreen)
{
// Borderless desktop fullscreen, like PlatformWin32.cpp (no display mode change).
if (SDL_SetWindowFullscreen(info.sdl_window, is_fullscreen))
{
info.is_fullscreen = is_fullscreen;
}
}
}
bool
is_window_fullscreen(window_id id)
{
return get_from_id(id).is_fullscreen;
}
window_handle
get_window_handle(window_id id)
{
return &get_from_id(id).native;
}
void
set_window_caption(window_id id, const char* caption)
{
SDL_SetWindowTitle(get_from_id(id).sdl_window, caption);
}
math::u32v4
get_window_size(window_id id)
{
// Client area in pixels as { left, top, right, bottom }, like GetClientRect() on Win32.
int width{ 0 }, height{ 0 };
SDL_GetWindowSizeInPixels(get_from_id(id).sdl_window, &width, &height);
return { 0, 0, (u32)width, (u32)height };
}
bool
is_window_closed(window_id id)
{
return get_from_id(id).is_closed;
}
void
close_window(window_id id)
{
// Handled in pump_events() like a close request from the user (Win32: PostMessage(WM_CLOSE)).
SDL_Event e{};
e.type = SDL_EVENT_WINDOW_CLOSE_REQUESTED;
e.window.windowID = SDL_GetWindowID(get_from_id(id).sdl_window);
SDL_PushEvent(&e);
}
} // anonymous namespace
window
create_window(const window_init_info* init_info /* = nullptr */)
{
if (init_info && init_info->parent)
{
assert(init_info->parent->kind == native_window_handle::x11);
assert(false && "Parented windows are not supported on Linux yet.");
return {};
}
if (!init_video()) return {};
const char *const caption{ (init_info && init_info->caption) ? init_info->caption : "Primal Game" };
const s32 width{ (init_info && init_info->width) ? init_info->width : 1920 };
const s32 height{ (init_info && init_info->height) ? init_info->height : 1080 };
const SDL_PropertiesID props{ SDL_CreateProperties() };
SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, caption);
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width);
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height);
if (init_info)
{
// NOTE: Wayland compositors ignore window positions.
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, init_info->left);
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, init_info->top);
}
SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true);
SDL_Window *const sdl_window{ SDL_CreateWindowWithProperties(props) };
SDL_DestroyProperties(props);
if (!sdl_window)
{
std::fprintf(stderr, "SDL_CreateWindowWithProperties failed: %s\n", SDL_GetError());
shutdown_video();
return {};
}
window_info info{};
info.sdl_window = sdl_window;
info.callback = init_info ? init_info->callback : nullptr;
if (!query_native_handle(sdl_window, info.native))
{
SDL_DestroyWindow(sdl_window);
shutdown_video();
return {};
}
const window_id id{ windows.add(info) };
++window_count;
SDL_SetNumberProperty(SDL_GetWindowProperties(sdl_window), window_id_property, (s64)(id::id_type)id);
paint_background(windows[id]);
return window{ id };
}
void
remove_window(window_id id)
{
window_info& info{ get_from_id(id) };
SDL_DestroyWindow(info.sdl_window);
windows.remove(id);
assert(window_count > 0);
--window_count;
shutdown_video();
}
std::filesystem::path
set_current_directory_to_executable_path()
{
std::error_code ec;
const std::filesystem::path path{ std::filesystem::read_symlink("/proc/self/exe", ec) };
if (ec) return {};
std::filesystem::current_path(path.parent_path(), ec);
if (ec) return {};
return std::filesystem::current_path();
}
bool
pump_events()
{
if (SDL_WasInit(SDL_INIT_EVENTS))
{
is_pumping_events = true;
SDL_Event e;
while (SDL_PollEvent(&e))
{
if (e.type == SDL_EVENT_QUIT)
{
quit_requested = true;
}
else if (e.type >= SDL_EVENT_WINDOW_FIRST && e.type <= SDL_EVENT_WINDOW_LAST)
{
process_window_event(e);
}
else if (e.type == SDL_EVENT_KEY_DOWN || e.type == SDL_EVENT_KEY_UP)
{
process_key_event(e);
}
else
{
input::process_input_event(e);
}
}
is_pumping_events = false;
shutdown_video();
}
return !quit_requested;
}
void
post_quit()
{
quit_requested = true;
}
}
#include "IncludeWindowCpp.h"
#endif // PRIMAL_PLATFORM_LINUX
Edit Engine/CMakeLists.txt
--- a/Engine/CMakeLists.txt
+++ b/Engine/CMakeLists.txt
@@ -14,7 +14,11 @@
Input/Input.cpp
)
-# NOTE: Windows-only sources (Win32 platform layer, D3D12 backend) are not part of the Linux build.
+# Linux platform layer (SDL3). Window.cpp is compiled through PlatformLinux.cpp (IncludeWindowCpp.h).
+target_sources(Engine PRIVATE
+ Input/InputSDL.cpp
+ Platform/PlatformLinux.cpp
+)
target_include_directories(Engine PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
@@ -25,6 +29,7 @@
primal::build_settings
primal::sal
Microsoft::DirectXMath
+ SDL3::SDL3
)
# PIC so the engine can later be linked into a shared EngineDLL (libEngineDLL.so) for the editor.
Edit cmake/PrimalDependencies.cmake
--- a/cmake/PrimalDependencies.cmake
+++ b/cmake/PrimalDependencies.cmake
@@ -18,6 +18,9 @@
add_library(Microsoft::DirectXMath ALIAS DirectXMath)
endif()
+# SDL3 (system package) for standalone windows, input and the event loop.
+find_package(SDL3 3.2 REQUIRED CONFIG COMPONENTS SDL3-shared)
+
# DirectXMath includes <sal.h>, which only exists on Windows. Provide a minimal stub elsewhere.
add_library(primal_sal_stub INTERFACE)
add_library(primal::sal ALIAS primal_sal_stub)
Commit: together with C3 (one commit).
C3 — Move every consumer to the shared API
Edit Engine/Graphics/Direct3D12/D3D12Surface.cpp — HWND comes from the native handle
--- a/Engine/Graphics/Direct3D12/D3D12Surface.cpp
+++ b/Engine/Graphics/Direct3D12/D3D12Surface.cpp
@@ -3,6 +3,7 @@
#include "D3D12Surface.h"
#include "D3D12Core.h"
#include "D3D12LightCulling.h"
+#include "Platform/PlatformTypes.h"
namespace primal::graphics::d3d12 {
namespace {
@@ -44,7 +45,9 @@
desc.Stereo = false;
IDXGISwapChain1* swap_chain;
- HWND hwnd{ (HWND)_window.handle() };
+ const platform::native_window_handle *const native{ _window.handle() };
+ assert(native && native->kind == platform::native_window_handle::win32);
+ HWND hwnd{ (HWND)native->window };
DXCall(factory->CreateSwapChainForHwnd(cmd_queue, hwnd, &desc, nullptr, nullptr, &swap_chain));
DXCall(factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER));
DXCall(swap_chain->QueryInterface(IID_PPV_ARGS(&_swap_chain)));
Edit EngineDLL/EngineAPI.cpp — host HWND wrapped as the parent; WinProc/mouse tracking removed (now in PlatformWin32). The C ABI and C# side are unchanged
--- a/EngineDLL/EngineAPI.cpp
+++ b/EngineDLL/EngineAPI.cpp
@@ -70,37 +70,6 @@
u8* data;
};
-bool tracking{ false };
-void track_mouse(HWND hwnd)
-{
- TRACKMOUSEEVENT tme;
- tme.cbSize = sizeof(TRACKMOUSEEVENT);
- tme.dwFlags = TME_HOVER | TME_LEAVE;
- tme.dwHoverTime = 10;
- tme.hwndTrack = hwnd;
-
- TrackMouseEvent(&tme);
-}
-
-LRESULT
-WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
-{
- switch (msg)
- {
- case WM_MOUSEMOVE:
- if (!tracking)
- {
- track_mouse(hwnd);
- tracking = true;
- }
- break;
- case WM_MOUSELEAVE:
- tracking = false;
- break;
- }
- return DefWindowProc(hwnd, msg, wparam, lparam);
-}
-
u8*
patch_material_data(u8* data)
{
@@ -259,7 +228,9 @@
std::lock_guard lock{ mutex };
assert(host);
- platform::window_init_info info{ &WinProc, host, nullptr, 0, 0, width, height };
+ // NOTE: PlatformWin32.cpp tracks the mouse for child windows (WM_MOUSEHOVER/WM_MOUSELEAVE for the editor).
+ const platform::native_window_handle parent{ platform::native_window_handle::win32, nullptr, (u64)host };
+ platform::window_init_info info{ nullptr, &parent, nullptr, 0, 0, width, height };
viewport_surface surface{};
surface.window = platform::create_window(&info);
surface.surface = graphics::create_surface(surface.window);
@@ -295,7 +266,7 @@
{
std::lock_guard lock{ mutex };
assert(id < surfaces.size());
- return (HWND)surfaces[id].window.handle();
+ return (HWND)surfaces[id].window.handle()->window;
}
EDITOR_INTERFACE id::id_type
Edit Engine/Core/EngineWin32.cpp — still EngineWin32.cpp here; renamed in D2
--- a/Engine/Core/EngineWin32.cpp
+++ b/Engine/Core/EngineWin32.cpp
@@ -13,29 +13,22 @@
graphics::render_surface game_window{};
-LRESULT win_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
+void on_window_event(const platform::window_event& event)
{
- switch (msg)
+ switch (event.type)
{
- case WM_DESTROY:
- {
- if (game_window.window.is_closed())
- {
- PostQuitMessage(0);
- return 0;
- }
- }
- break;
- case WM_SYSCHAR:
- if (wparam == VK_RETURN && (HIWORD(lparam) & KF_ALTDOWN))
+ case platform::window_event::closed:
+ platform::post_quit();
+ break;
+ case platform::window_event::key_down:
+ if (event.key == input::input_code::key_return && (event.modifiers & input::modifier_key::alt))
{
game_window.window.set_fullscreen(!game_window.window.is_fullscreen());
- return 0;
}
break;
+ default:
+ break;
}
-
- return DefWindowProc(hwnd, msg, wparam, lparam);
}
} // anonymous namespace
@@ -47,7 +40,7 @@
platform::window_init_info info
{
- &win_proc, nullptr, L"Primal Game" // TODO: get the game name from the loaded game file
+ &on_window_event, nullptr, "Primal Game" // TODO: get the game name from the loaded game file
};
game_window.window = platform::create_window(&info);
Edit Engine/Core/MainWin32.cpp
--- a/Engine/Core/MainWin32.cpp
+++ b/Engine/Core/MainWin32.cpp
@@ -1,30 +1,15 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
-#ifdef _WIN64
#include "CommonHeaders.h"
-#include <filesystem>
+#if PRIMAL_PLATFORM_WINDOWS
+#include "Platform/PlatformTypes.h"
+#include "Platform/Platform.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // ! WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <crtdbg.h>
-
-namespace {
-// TODO: we might want to have an IO utility header/library and move this function in there.
-std::filesystem::path
-set_current_directory_to_executable_path()
-{
- // set the working directory to the executable path
- wchar_t path[MAX_PATH]{};
- const u32 length{ GetModuleFileName(0, &path[0], MAX_PATH) };
- if (!length || GetLastError() == ERROR_INSUFFICIENT_BUFFER) return {};
- std::filesystem::path p{ path };
- std::filesystem::current_path(p.parent_path());
- return std::filesystem::current_path();
-}
-
-}
#ifndef USE_WITH_EDITOR
@@ -38,21 +23,12 @@
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
- set_current_directory_to_executable_path();
+ primal::platform::set_current_directory_to_executable_path();
if (engine_initialize())
{
- MSG msg{};
- bool is_running{ true };
- while (is_running)
+ while (primal::platform::pump_events())
{
- while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
- {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- is_running &= (msg.message != WM_QUIT);
- }
-
engine_update();
}
}
@@ -61,4 +37,4 @@
}
#endif // USE_WITH_EDITOR
-#endif // _WIN64
+#endif // PRIMAL_PLATFORM_WINDOWS
Replace EngineTest/Main.cpp — one run_test() loop for both platforms
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "Test.h"
#ifdef _MSC_VER
#pragma comment(lib, "engine.lib")
#endif
#if TEST_ENTITY_COMPONENTS
#include "TestEntityComponents.h"
#elif TEST_WINDOW
#include "TestWindow.h"
#elif TEST_RENDERER
#include "TestRenderer.h"
#else
#error One of the tests need to be enabled
#endif
#include "../Engine/Platform/PlatformTypes.h"
#include "../Engine/Platform/Platform.h"
int
run_test()
{
primal::platform::set_current_directory_to_executable_path();
engine_test test{};
if (test.initialize())
{
#if TEST_ENTITY_COMPONENTS
test.run(); // runs its own console loop
#else
while (primal::platform::pump_events())
{
test.run();
}
#endif
}
test.shutdown();
return 0;
}
#if PRIMAL_PLATFORM_WINDOWS
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
#if _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// When a leak is detected, call _CrtSetBreakAlloc(N) with leak number N to
// break at leak site.
#endif
return run_test();
}
#elif PRIMAL_PLATFORM_LINUX
// NOTE: there is no _CrtSetDbgFlag on Linux. For leak checking, configure with
// -DPRIMAL_ENABLE_SANITIZERS=ON (AddressSanitizer includes LeakSanitizer).
int main()
{
return run_test();
}
#endif
Replace EngineTest/TestWindow.h — one version for both platforms
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "Test.h"
#include "../Platform/PlatformTypes.h"
#include "../Platform/Platform.h"
#include <cstdio>
#include <iterator>
using namespace primal;
platform::window _windows[4];
void on_window_event(const platform::window_event& event)
{
using platform::window_event;
switch (event.type)
{
case window_event::closed:
{
bool all_closed{ true };
for (u32 i{ 0 }; i < std::size(_windows); ++i)
{
if (!_windows[i].is_closed())
{
all_closed = false;
}
}
if (all_closed)
{
platform::post_quit();
}
}
break;
case window_event::resized:
{
const platform::window win{ event.window };
std::fprintf(stderr, "window %u resized: %u x %u\n", (u32)(id::id_type)event.window, win.width(), win.height());
}
break;
case window_event::key_down:
if (event.key == input::input_code::key_return && (event.modifiers & input::modifier_key::alt))
{
const platform::window win{ event.window };
win.set_fullscreen(!win.is_fullscreen());
}
break;
default:
break;
}
}
class engine_test : public test
{
public:
bool initialize() override
{
platform::window_init_info info[]
{
{&on_window_event, nullptr, "Test window 1", 100, 100, 400, 800},
{&on_window_event, nullptr, "Test window 2", 150, 150, 800, 400},
{&on_window_event, nullptr, "Test window 3", 200, 200, 400, 400},
{&on_window_event, nullptr, "Test window 4", 250, 250, 800, 600},
};
static_assert(std::size(info) == std::size(_windows));
for (u32 i{ 0 }; i < std::size(_windows); ++i)
{
_windows[i] = platform::create_window(&info[i]);
if (!_windows[i].is_valid()) return false;
}
return true;
}
void run() override
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void shutdown() override
{
for (u32 i{ 0 }; i < std::size(_windows); ++i)
{
if (_windows[i].is_valid()) platform::remove_window(_windows[i].get_id());
}
}
};
Edit EngineTest/TestRenderer.cpp — event callback: Esc closes, Space toggles vsync, F11 restarts, Alt+Enter fullscreen
--- a/EngineTest/TestRenderer.cpp
+++ b/EngineTest/TestRenderer.cpp
@@ -14,6 +14,7 @@
#include "../EngineDLL/ShaderCompilation.cpp"
#include <filesystem>
#include <fstream>
+#include <iterator>
#if TEST_RENDERER
using namespace primal;
@@ -80,16 +81,30 @@
void remove_lights();
void test_lights(f32 dt);
-LRESULT win_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
-{
- bool toggle_fullscreen{ false };
-
- switch (msg)
- {
- case WM_DESTROY:
+camera_surface*
+find_camera_surface(platform::window_id id)
+{
+ for (u32 i{ 0 }; i < std::size(_surfaces); ++i)
+ {
+ if (_surfaces[i].surface.window.is_valid() && _surfaces[i].surface.window.get_id() == id)
+ {
+ return &_surfaces[i];
+ }
+ }
+ return nullptr;
+}
+
+void on_window_event(const platform::window_event& event)
+{
+ using platform::window_event;
+ using input::input_code;
+
+ switch (event.type)
+ {
+ case window_event::closed:
{
bool all_closed{ true };
- for (u32 i{ 0 }; i < _countof(_surfaces); ++i)
+ for (u32 i{ 0 }; i < std::size(_surfaces); ++i)
{
if (_surfaces[i].surface.window.is_valid())
{
@@ -105,67 +120,48 @@
}
if (all_closed && !is_restarting)
{
- PostQuitMessage(0);
- return 0;
+ platform::post_quit();
}
}
break;
- case WM_SIZE:
- resized = (wparam != SIZE_MINIMIZED);
+ case window_event::resized:
+ if (camera_surface *const surface{ find_camera_surface(event.window) })
+ {
+ const platform::window win{ surface->surface.window };
+ surface->surface.surface.resize(win.width(), win.height());
+ surface->camera.aspect_ratio((f32)win.width() / win.height());
+ }
break;
- case WM_SYSCHAR:
- toggle_fullscreen = (wparam == VK_RETURN && (HIWORD(lparam) & KF_ALTDOWN));
- break;
- case WM_KEYDOWN:
- if (wparam == VK_ESCAPE)
- {
- PostMessage(hwnd, WM_CLOSE, 0, 0);
- return 0;
- }
- else if(wparam == VK_SPACE)
+ case window_event::key_down:
+ if (event.key == input_code::key_escape)
+ {
+ platform::window{ event.window }.close();
+ }
+ else if (event.key == input_code::key_space)
{
bool vsync{ false };
graphics::get_option(graphics::renderer_option::vsync, &vsync, sizeof(bool));
vsync = !vsync;
graphics::set_option(graphics::renderer_option::vsync, &vsync, sizeof(bool));
}
- else if (wparam == VK_F11)
+ else if (event.key == input_code::key_f11)
{
is_restarting = true;
test_shutdown();
test_initialize();
}
- }
-
- if ((resized && GetKeyState(VK_LBUTTON) >= 0) || toggle_fullscreen)
- {
- platform::window win{ platform::window_id{(id::id_type)GetWindowLongPtr(hwnd, GWLP_USERDATA)} };
- for (u32 i{ 0 }; i < _countof(_surfaces); ++i)
- {
- if (win.get_id() == _surfaces[i].surface.window.get_id())
+ else if (event.key == input_code::key_return && (event.modifiers & input::modifier_key::alt))
+ {
+ if (camera_surface *const surface{ find_camera_surface(event.window) })
{
- if (toggle_fullscreen)
- {
- win.set_fullscreen(!win.is_fullscreen());
- // The default window procedure will play a system notification sound
- // when pressing the Alt+Enter keyboard combination if WM_SYSCHAR is
- // not handled. By returning 0 we can tell the system that we handled
- // this message.
- return 0;
- }
- else
- {
- _surfaces[i].surface.surface.resize(win.width(), win.height());
- _surfaces[i].camera.aspect_ratio((f32)win.width() / win.height());
-
- resized = false;
- }
- break;
+ const platform::window win{ surface->surface.window };
+ win.set_fullscreen(!win.is_fullscreen());
}
}
- }
-
- return DefWindowProc(hwnd, msg, wparam, lparam);
+ break;
+ default:
+ break;
+ }
}
game_entity::entity
@@ -257,14 +253,14 @@
platform::window_init_info info[]
{
- {&win_proc, nullptr, L"Render window 1", 100 - 3000, 100 - 700, 400, 800},
- {&win_proc, nullptr, L"Render window 2", 150 - 3000, 150 - 700, 800, 400},
- {&win_proc, nullptr, L"Render window 3", 200 - 3000, 200 - 700, 400, 400},
- {&win_proc, nullptr, L"Render window 4", 250 - 3000, 250 - 700, 800, 600},
+ {&on_window_event, nullptr, "Render window 1", 100, 100, 400, 800},
+ {&on_window_event, nullptr, "Render window 2", 150, 150, 800, 400},
+ {&on_window_event, nullptr, "Render window 3", 200, 200, 400, 400},
+ {&on_window_event, nullptr, "Render window 4", 250, 250, 800, 600},
};
- static_assert(_countof(info) == _countof(_surfaces));
-
- for (u32 i{ 0 }; i < _countof(_surfaces); ++i)
+ static_assert(std::size(info) == std::size(_surfaces));
+
+ for (u32 i{ 0 }; i < std::size(_surfaces); ++i)
create_camera_surface(_surfaces[i], info[i]);
@@ -320,7 +316,7 @@
remove_lights();
joint_test_workers();
- for (u32 i{ 0 }; i < _countof(_surfaces); ++i)
+ for (u32 i{ 0 }; i < std::size(_surfaces); ++i)
destroy_camera_surface(_surfaces[i]);
graphics::shutdown();
@@ -344,7 +340,7 @@
const f32 dt{ timer.dt_avg() };
script::update(dt);
//test_lights(dt);
- for (u32 i{ 0 }; i < _countof(_surfaces); ++i)
+ for (u32 i{ 0 }; i < std::size(_surfaces); ++i)
{
if (_surfaces[i].surface.surface.is_valid())
{
@@ -358,7 +354,7 @@
info.average_frame_time = dt;
info.camera_id = _surfaces[i].camera.get_id();
- assert(_countof(thresholds) >= info.render_item_count);
+ assert(std::size(thresholds) >= info.render_item_count);
_surfaces[i].surface.surface.render(info);
}
}
Verify:
cmake --preset linux-debug -DPRIMAL_ENGINE_TEST=WINDOW && cmake --build --preset linux-debug
./x64/Debug/EngineTest # 4 blue windows; resize; Alt+Enter; close all → exits
SDL_VIDEO_DRIVER=x11 ./x64/Debug/EngineTest # same on X11
timeout --preserve-status -s TERM 4 ./x64/Debug/EngineTest; echo $? # SIGTERM → clean exit (0)
# sanitizer build: X11 clean; Wayland shows only the known 256-byte SDL library leak
# optional: the close/remove-in-callback test in section V
Commit: Shared platform API: event callbacks, UTF-8 captions, native handles, SDL3 on Linux
→ Windows checkpoint (Win32 platform layer, EngineDLL, D3D12 surface, editor viewport hover/leave).
D. Phase 4 — Content loader, game executable, paths
D1 — Platform-neutral content loader
git mv Engine/Content/ContentLoaderWin32.cpp Engine/Content/ContentLoader.cpp
Edit Engine/Content/ContentLoader.cpp — also fixes the 1-byte u32 reads
--- a/Engine/Content/ContentLoaderWin32.cpp
+++ b/Engine/Content/ContentLoader.cpp
@@ -6,11 +6,11 @@
#include "Components/Script.h"
#include "Graphics/Renderer.h"
-#if !defined(SHIPPING) && defined(_WIN64)
+#if !defined(SHIPPING)
#include <fstream>
#include <filesystem>
-#include <Windows.h>
+#include <iterator>
namespace primal::content {
namespace {
@@ -18,6 +18,16 @@
utl::vector<game_entity::entity> entities;
transform::init_info transform_info{};
script::init_info script_info{};
+
+// NOTE: reads 4 bytes. (Reading *data directly only reads the lowest byte of the u32.)
+u32
+read_u32(const u8*& data)
+{
+ u32 value;
+ memcpy(&value, data, sizeof(u32));
+ data += sizeof(u32);
+ return value;
+}
bool
read_transform(const u8*& data, game_entity::entity_info& info)
@@ -45,7 +55,7 @@
read_script(const u8*& data, game_entity::entity_info& info)
{
assert(!info.script);
- const u32 name_length{ *data }; data += sizeof(u32);
+ const u32 name_length{ read_u32(data) };
if (!name_length) return false;
// if a script name is longer than 255 characters then something is probably
// very wrong, either with the binary writer or the game programmer.
@@ -72,7 +82,7 @@
read_script,
read_geometry,
};
-static_assert(_countof(component_readers) == component_type::count);
+static_assert(std::size(component_readers) == component_type::count);
bool
read_file(std::filesystem::path path, std::unique_ptr<u8[]>& data, u64& size)
@@ -106,7 +116,7 @@
assert(game_data.get());
const u8* at{ game_data.get() };
constexpr u32 su32{ sizeof(u32) };
- const u32 num_entities{ *at }; at += su32;
+ const u32 num_entities{ read_u32(at) };
if (!num_entities) return false;
for (u32 entity_index{ 0 }; entity_index < num_entities; ++entity_index)
@@ -115,12 +125,12 @@
//const u32 entity_type{ *at };
// skip over entity type (for now):
at += su32;
- const u32 num_components{ *at }; at += su32;
+ const u32 num_components{ read_u32(at) };
if (!num_components) return false;
for (u32 component_index{ 0 }; component_index < num_components; ++component_index)
{
- const u32 component_type{ *at }; at += su32;
+ const u32 component_type{ read_u32(at) };
assert(component_type < component_type::count);
if (!component_readers[component_type](at, info)) return false;
}
Edit Engine/Content/ContentLoader.h
--- a/Engine/Content/ContentLoader.h
+++ b/Engine/Content/ContentLoader.h
@@ -2,7 +2,7 @@
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
-#if !defined(SHIPPING) && defined(_WIN64)
+#if !defined(SHIPPING)
namespace primal::content {
bool load_game();
void unload_game();
Edit Engine/Engine.vcxproj
--- a/Engine/Engine.vcxproj
+++ b/Engine/Engine.vcxproj
@@ -74,7 +74,7 @@
<ClCompile Include="Components\Geometry.cpp" />
<ClCompile Include="Components\Script.cpp" />
<ClCompile Include="Components\Transform.cpp" />
- <ClCompile Include="Content\ContentLoaderWin32.cpp" />
+ <ClCompile Include="Content\ContentLoader.cpp" />
<ClCompile Include="Content\ContentToEngine.cpp" />
<ClCompile Include="Core\EngineWin32.cpp" />
<ClCompile Include="Core\MainWin32.cpp" />
Edit Engine/Engine.vcxproj.filters
--- a/Engine/Engine.vcxproj.filters
+++ b/Engine/Engine.vcxproj.filters
@@ -56,7 +56,7 @@
<ClCompile Include="Components\Script.cpp" />
<ClCompile Include="Core\MainWin32.cpp" />
<ClCompile Include="Core\EngineWin32.cpp" />
- <ClCompile Include="Content\ContentLoaderWin32.cpp" />
+ <ClCompile Include="Content\ContentLoader.cpp" />
<ClCompile Include="Platform\PlatformWin32.cpp" />
<ClCompile Include="Graphics\Renderer.cpp" />
<ClCompile Include="Graphics\Direct3D12\D3D12Interface.cpp" />
Edit Engine/CMakeLists.txt
--- a/Engine/CMakeLists.txt
+++ b/Engine/CMakeLists.txt
@@ -9,6 +9,7 @@
Components/Geometry.cpp
Components/Script.cpp
Components/Transform.cpp
+ Content/ContentLoader.cpp
Content/ContentToEngine.cpp
Graphics/Renderer.cpp
Input/Input.cpp
Commit: Make the content loader platform-neutral
D2 — Platform-neutral engine loop + Linux game main()
git mv Engine/Core/EngineWin32.cpp Engine/Core/Engine.cpp
Edit Engine/Core/Engine.cpp — drop the _WIN64 gate; don't remove a window that was never created
--- a/Engine/Core/EngineWin32.cpp
+++ b/Engine/Core/Engine.cpp
@@ -1,6 +1,6 @@
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
-#if !defined(SHIPPING) && defined(_WIN64)
+#if !defined(SHIPPING)
#include "Content/ContentLoader.h"
#include "Components/Script.h"
#include "Platform/PlatformTypes.h"
@@ -59,7 +59,7 @@
void
engine_shutdown()
{
- platform::remove_window(game_window.window.get_id());
+ if (game_window.window.is_valid()) platform::remove_window(game_window.window.get_id());
content::unload_game();
}
#endif // !defined(SHIPPING)
New file Engine/Core/MainLinux.cpp
// Copyright (c) 2026 Charles Smith
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "CommonHeaders.h"
#if PRIMAL_PLATFORM_LINUX
#include "Platform/PlatformTypes.h"
#include "Platform/Platform.h"
// Linux counterpart of MainWin32.cpp: entry point of a game executable linked with the engine.
// NOTE: an executable that defines its own main() (e.g. EngineTest) doesn't pull this in,
// because the linker only uses archive members that resolve undefined symbols.
#ifndef USE_WITH_EDITOR
extern bool engine_initialize();
extern void engine_update();
extern void engine_shutdown();
int main()
{
// NOTE: for leak checking, configure with -DPRIMAL_ENABLE_SANITIZERS=ON.
primal::platform::set_current_directory_to_executable_path();
if (engine_initialize())
{
while (primal::platform::pump_events())
{
engine_update();
}
}
engine_shutdown();
return 0;
}
#endif // USE_WITH_EDITOR
#endif // PRIMAL_PLATFORM_LINUX
Edit Engine/Engine.vcxproj
--- a/Engine/Engine.vcxproj
+++ b/Engine/Engine.vcxproj
@@ -76,7 +76,7 @@
<ClCompile Include="Components\Transform.cpp" />
<ClCompile Include="Content\ContentLoader.cpp" />
<ClCompile Include="Content\ContentToEngine.cpp" />
- <ClCompile Include="Core\EngineWin32.cpp" />
+ <ClCompile Include="Core\Engine.cpp" />
<ClCompile Include="Core\MainWin32.cpp" />
<ClCompile Include="Graphics\Direct3D12\D3D12Camera.cpp" />
<ClCompile Include="Graphics\Direct3D12\D3D12Content.cpp" />
Edit Engine/Engine.vcxproj.filters
--- a/Engine/Engine.vcxproj.filters
+++ b/Engine/Engine.vcxproj.filters
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClInclude Include="Common\CommonHeaders.h" />
@@ -55,7 +55,7 @@
<ClCompile Include="Components\Transform.cpp" />
<ClCompile Include="Components\Script.cpp" />
<ClCompile Include="Core\MainWin32.cpp" />
- <ClCompile Include="Core\EngineWin32.cpp" />
+ <ClCompile Include="Core\Engine.cpp" />
<ClCompile Include="Content\ContentLoader.cpp" />
<ClCompile Include="Platform\PlatformWin32.cpp" />
<ClCompile Include="Graphics\Renderer.cpp" />
Edit Engine/CMakeLists.txt
--- a/Engine/CMakeLists.txt
+++ b/Engine/CMakeLists.txt
@@ -11,12 +11,14 @@
Components/Transform.cpp
Content/ContentLoader.cpp
Content/ContentToEngine.cpp
+ Core/Engine.cpp
Graphics/Renderer.cpp
Input/Input.cpp
)
# Linux platform layer (SDL3). Window.cpp is compiled through PlatformLinux.cpp (IncludeWindowCpp.h).
target_sources(Engine PRIVATE
+ Core/MainLinux.cpp
Input/InputSDL.cpp
Platform/PlatformLinux.cpp
)
Verify with the scratch game in section V (hand-made game.bin, run from another directory, SIGTERM → exit 0;
without game.bin → exit 0, no assert).
Commit: Add Linux game entry point; make the engine loop platform-neutral
D3 — Forward-slash paths
Edit Engine/Graphics/Renderer.cpp
--- a/Engine/Graphics/Renderer.cpp
+++ b/Engine/Graphics/Renderer.cpp
@@ -12,8 +12,8 @@
// Defines where the compiled engine shaders file is located for each one of the supported APIs.
constexpr const char* engine_shader_paths[]{
- ".\\shaders\\d3d12\\shaders.bin",
- // ".\\shaders\\vulkan\\shaders.bin", etc.
+ "./shaders/d3d12/shaders.bin",
+ // "./shaders/vulkan/shaders.bin", etc.
};
platform_interface gfx{};
Edit EngineTest/RenderItem.cpp — 17 asset paths + the test shader folder (case-sensitive EngineTest)
--- a/EngineTest/RenderItem.cpp
+++ b/EngineTest/RenderItem.cpp
@@ -96,7 +96,7 @@
info.function = "TestShaderVS";
info.type = graphics::shader_type::vertex;
- const char* shader_path{ "..\\..\\enginetest\\" };
+ const char* shader_path{ "../../EngineTest/" };
std::wstring defines[]{ L"ELEMENTS_TYPE=0", L"ELEMENTS_TYPE=1", L"ELEMENTS_TYPE=3" };
utl::vector<u32> keys;
@@ -205,30 +205,30 @@
// https://ko-fi.com/gameengineseries/shop
// Use the editor to import the scene and put the 3 models in this location.
// You can replace them with any model that's available to you.
- assert(std::filesystem::exists("..\\..\\x64\\lab_model.model"));
- assert(std::filesystem::exists("..\\..\\x64\\fan_model.model"));
- assert(std::filesystem::exists("..\\..\\x64\\int_model.model"));
- assert(std::filesystem::exists("..\\..\\x64\\fembot_model.model"));
+ assert(std::filesystem::exists("../../x64/lab_model.model"));
+ assert(std::filesystem::exists("../../x64/fan_model.model"));
+ assert(std::filesystem::exists("../../x64/int_model.model"));
+ assert(std::filesystem::exists("../../x64/fembot_model.model"));
memset(&texture_ids[0], 0xff, sizeof(id::id_type) * _countof(texture_ids));
std::thread threads[]{
- std::thread{ [] { texture_ids[texture_usage::ambient_occlusion] = load_texture("..\\..\\x64\\ambient_occlusion.texture"); }},
- std::thread{ [] { texture_ids[texture_usage::base_color] = load_texture("..\\..\\x64\\base_color.texture"); }},
- std::thread{ [] { texture_ids[texture_usage::emissive] = load_texture("..\\..\\x64\\emissive.texture"); }},
- std::thread{ [] { texture_ids[texture_usage::metal_rough] = load_texture("..\\..\\x64\\metal_rough.texture"); }},
- std::thread{ [] { texture_ids[texture_usage::normal] = load_texture("..\\..\\x64\\normal.texture"); }},
-
- std::thread{ [] { ibl_brdf_lut_id = load_texture("..\\..\\x64\\ibl\\brdf_lut.texture"); } },
-
- std::thread{ [] { ibl_diffuse_id = load_texture("..\\..\\x64\\ibl\\set4\\diffuse.texture"); } },
- std::thread{ [] { ibl_specular_id = load_texture("..\\..\\x64\\ibl\\set4\\specular.texture"); } },
-
- std::thread{ [] { lab_model_id = load_model("..\\..\\x64\\lab_model.model"); } },
- std::thread{ [] { fan_model_id = load_model("..\\..\\x64\\fan_model.model"); } },
- std::thread{ [] { int_model_id = load_model("..\\..\\x64\\int_model.model"); } },
- std::thread{ [] { fembot_model_id = load_model("..\\..\\x64\\fembot_model.model"); } },
- std::thread{ [] { sphere_model_id = load_model("..\\..\\x64\\sphere_model.model"); } },
+ std::thread{ [] { texture_ids[texture_usage::ambient_occlusion] = load_texture("../../x64/ambient_occlusion.texture"); }},
+ std::thread{ [] { texture_ids[texture_usage::base_color] = load_texture("../../x64/base_color.texture"); }},
+ std::thread{ [] { texture_ids[texture_usage::emissive] = load_texture("../../x64/emissive.texture"); }},
+ std::thread{ [] { texture_ids[texture_usage::metal_rough] = load_texture("../../x64/metal_rough.texture"); }},
+ std::thread{ [] { texture_ids[texture_usage::normal] = load_texture("../../x64/normal.texture"); }},
+
+ std::thread{ [] { ibl_brdf_lut_id = load_texture("../../x64/ibl/brdf_lut.texture"); } },
+
+ std::thread{ [] { ibl_diffuse_id = load_texture("../../x64/ibl/set4/diffuse.texture"); } },
+ std::thread{ [] { ibl_specular_id = load_texture("../../x64/ibl/set4/specular.texture"); } },
+
+ std::thread{ [] { lab_model_id = load_model("../../x64/lab_model.model"); } },
+ std::thread{ [] { fan_model_id = load_model("../../x64/fan_model.model"); } },
+ std::thread{ [] { int_model_id = load_model("../../x64/int_model.model"); } },
+ std::thread{ [] { fembot_model_id = load_model("../../x64/fembot_model.model"); } },
+ std::thread{ [] { sphere_model_id = load_model("../../x64/sphere_model.model"); } },
std::thread{ [] { load_shaders(); } },
};
Before Phase 7: copy the renderer test assets generated on Windows (x64/*.model, x64/*.texture, x64/ibl/...) to x64/ on Linux.
Commit: Use forward-slash paths for shaders and test assets → Windows checkpoint.
E. Phase 5 — Shader compiler, HLSL → SPIR-V
E1 — Vulkan graphics platform id and shader path
Edit Engine/Graphics/Renderer.h
--- a/Engine/Graphics/Renderer.h
+++ b/Engine/Graphics/Renderer.h
@@ -252,6 +252,7 @@
enum class graphics_platform :u32
{
direct3d12 = 0,
+ vulkan = 1,
};
#else
#include "Graphics/GraphicsPlatform.h"
Edit Engine/Graphics/Renderer.cpp
--- a/Engine/Graphics/Renderer.cpp
+++ b/Engine/Graphics/Renderer.cpp
@@ -13,7 +13,7 @@
// Defines where the compiled engine shaders file is located for each one of the supported APIs.
constexpr const char* engine_shader_paths[]{
"./shaders/d3d12/shaders.bin",
- // "./shaders/vulkan/shaders.bin", etc.
+ "./shaders/vulkan/shaders.bin",
};
platform_interface gfx{};
Commit: Add graphics_platform::vulkan
E2 — Backend-aware shader compiler (DXIL + SPIR-V), Linux DXC
First iterate on the flags with the CLI (section V has the script), then port the C++. The resulting Vulkan binding layout (used by Phase 6):
| HLSL | Vulkan |
|---|---|
register(bN, space0) |
set 0, binding N |
register(tN, space0) |
set 0, binding 100 + N |
register(uN, space0) |
set 0, binding 200 + N |
register(sN, space0) |
set 0, binding 300 + N |
ResourceDescriptorHeap[] |
set 1, binding 0 (mutable descriptors; typed views alias it) |
SamplerDescriptorHeap[] |
set 2, binding 0 (unused today) |
Replace EngineDLL/ShaderCompilation.h — platform parameter with a per-OS default, so callers are unchanged
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#pragma once
#include "CommonHeaders.h"
#include "Graphics/Renderer.h"
struct shader_file_info
{
const char* file_name;
const char* function;
primal::graphics::shader_type::type type;
};
// Shader target of the platform's default graphics backend: DXIL for Direct3D 12, SPIR-V for Vulkan.
constexpr primal::graphics::graphics_platform default_shader_platform{
#if PRIMAL_PLATFORM_WINDOWS
primal::graphics::graphics_platform::direct3d12
#else
primal::graphics::graphics_platform::vulkan
#endif
};
std::unique_ptr<u8[]> compile_shader(shader_file_info info, u8* code, u32 code_size, primal::utl::vector<std::wstring>& extra_args,
bool include_errors_and_disassembly = false,
primal::graphics::graphics_platform platform = default_shader_platform);
std::unique_ptr<u8[]> compile_shader(shader_file_info info, const char* file_path, primal::utl::vector<std::wstring>& extra_args,
bool include_errors_and_disassembly = false,
primal::graphics::graphics_platform platform = default_shader_platform);
bool compile_shaders(primal::graphics::graphics_platform platform = default_shader_platform);
Replace EngineDLL/ShaderCompilation.cpp — COM pointer wrapper, SPIR-V args, FNV-1a hash for SPIR-V, Attach() leak fix
// Copyright (c) Arash Khatami
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
#include "ShaderCompilation.h"
#if PRIMAL_PLATFORM_WINDOWS
#include <wrl.h>
#include <dxcapi.h>
#include <d3d12shader.h>
#else
// DXC's Linux build: libdxcompiler.so plus a small COM emulation layer (WinAdapter.h).
#include <dxc/dxcapi.h>
#endif
#include "Graphics/Renderer.h"
#include "Content/ContentToEngine.h"
#include "Utilities/IOStream.h"
#include <cstdio>
#include <fstream>
#include <filesystem>
#include <iterator>
#include <string>
using namespace primal;
namespace {
#if PRIMAL_PLATFORM_WINDOWS
template<typename T> using com_ptr = Microsoft::WRL::ComPtr<T>;
#define DEBUG_BREAK() __debugbreak()
#else
// CComPtr from WinAdapter.h, with the Get() accessor of WRL's ComPtr.
template<typename T>
class com_ptr : public CComPtr<T>
{
public:
using CComPtr<T>::CComPtr;
T* Get() const { return this->p; }
};
#define DEBUG_BREAK() __builtin_debugtrap()
#endif
void
shader_log(const char* message)
{
#if PRIMAL_PLATFORM_WINDOWS
OutputDebugStringA(message);
#else
std::fputs(message, stderr);
#endif
}
} // anonymous namespace
// Assert that COM call to D3D API succeeded
#ifdef _DEBUG
#ifndef DXCall
#define DXCall(x) \
if(FAILED(x)) { \
char line_number[32]; \
snprintf(line_number, sizeof(line_number), "%u", __LINE__); \
shader_log("Error in: "); \
shader_log(__FILE__); \
shader_log("\nLine: "); \
shader_log(line_number); \
shader_log("\n"); \
shader_log(#x); \
shader_log("\n"); \
DEBUG_BREAK(); \
}
#endif //DXCall
#else
#ifndef DXCall
#define DXCall(x) x
#endif //DXCall
#endif //_DEBUG
namespace {
// TODO: move some of this stuff into shader_compiler.
struct engine_shader {
enum id : u32 {
fullscreen_triangle_vs = 0,
post_process_ps,
grid_frustums_cs,
light_culling_cs,
count
};
};
struct engine_shader_info
{
engine_shader::id id;
shader_file_info info;
};
// NOTE: the HLSL sources are shared by the Direct3D 12 and Vulkan backends.
constexpr const char* shaders_source_path{ "../../Engine/Graphics/Direct3D12/Shaders/" };
constexpr engine_shader_info engine_shader_files[]
{
{engine_shader::fullscreen_triangle_vs, {"FullScreenTriangle.hlsl", "FullScreenTriangleVS", graphics::shader_type::vertex}},
{engine_shader::post_process_ps, {"PostProcess.hlsl", "PostProcessPS", graphics::shader_type::pixel}},
{engine_shader::grid_frustums_cs, {"GridFrustums.hlsl", "ComputeGridFrustumsCS", graphics::shader_type::compute}},
{engine_shader::light_culling_cs, {"CullLights.hlsl", "CullLightsCS", graphics::shader_type::compute}},
};
static_assert(std::size(engine_shader_files) == engine_shader::count);
constexpr u32 shader_hash_length{ 16 };
static_assert(content::compiled_shader::hash_length == shader_hash_length);
struct dxc_compiled_shader
{
com_ptr<IDxcBlob> byte_code;
com_ptr<IDxcBlobUtf8> errors;
com_ptr<IDxcBlobUtf8> assembly;
u8 hash[shader_hash_length]{};
};
std::wstring
to_wstring(const char* c)
{
std::string s{ c };
return { s.begin(), s.end() };
}
// 128-bit FNV-1a. DXC only computes a shader hash for DXIL, so SPIR-V byte code is hashed here.
// The hash is used to identify byte code, not for security.
void
hash_byte_code(const u8 *const data, u64 size, u8 (&hash)[shader_hash_length])
{
// offset basis 0x6c62272e07bb014262b821756295c58d, prime 2^88 + 0x13b
u64 hi{ 0x6c62272e07bb0142ull };
u64 lo{ 0x62b821756295c58dull };
constexpr u64 prime_low{ 0x13b };
for (u64 i{ 0 }; i < size; ++i)
{
lo ^= data[i];
// (hi, lo) *= prime (mod 2^128)
const u64 lo_lo{ (lo & 0xffff'ffffull) * prime_low };
const u64 lo_hi{ (lo >> 32) * prime_low };
const u64 new_lo{ lo_lo + (lo_hi << 32) };
const u64 carry{ (lo_hi >> 32) + (new_lo < lo_lo ? 1ull : 0ull) };
hi = hi * prime_low + carry + (lo << 24);
lo = new_lo;
}
memcpy(&hash[0], &lo, sizeof(lo));
memcpy(&hash[sizeof(lo)], &hi, sizeof(hi));
}
class shader_compiler
{
public:
explicit shader_compiler(graphics::graphics_platform platform)
: _platform{ platform }
{
HRESULT hr{ S_OK };
DXCall(hr = DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&_compiler)));
if (FAILED(hr)) return;
DXCall(hr = DxcCreateInstance(CLSID_DxcUtils, IID_PPV_ARGS(&_utils)));
if (FAILED(hr)) return;
DXCall(hr = _utils->CreateDefaultIncludeHandler(&_include_handler));
if (FAILED(hr)) return;
}
DISABLE_COPY_AND_MOVE(shader_compiler);
dxc_compiled_shader compile(u8* data, u32 data_size, graphics::shader_type::type type, const char* function, utl::vector<std::wstring>& extra_args)
{
assert(_compiler && _utils && _include_handler);
assert(data && data_size && function);
assert(type < graphics::shader_type::count);
HRESULT hr{ S_OK };
com_ptr<IDxcBlobEncoding> source_blob{ nullptr };
DXCall(hr = _utils->CreateBlob(data, data_size, 0, &source_blob));
if (FAILED(hr)) return {};
assert(source_blob && source_blob->GetBufferSize());
shader_file_info info{};
info.function = function;
info.type = type;
// TODO: do proper developer logging
shader_log("Compiling ");
shader_log(function);
shader_log("\n");
return compile(source_blob.Get(), get_args(info, extra_args));
}
dxc_compiled_shader compile(shader_file_info info, std::filesystem::path full_path, utl::vector<std::wstring>& extra_args)
{
assert(_compiler && _utils && _include_handler);
HRESULT hr{ S_OK };
// Load the source file using Utils interface.
com_ptr<IDxcBlobEncoding> source_blob{ nullptr };
DXCall(hr = _utils->LoadFile(full_path.wstring().c_str(), nullptr, &source_blob));
if (FAILED(hr)) return {};
assert(source_blob && source_blob->GetBufferSize());
shader_log("Compiling ");
shader_log(info.file_name);
shader_log(" : ");
shader_log(info.function);
shader_log("\n");
return compile(source_blob.Get(), get_args(info, extra_args));
}
dxc_compiled_shader compile(IDxcBlobEncoding* source_blob, utl::vector<std::wstring> compiler_args)
{
DxcBuffer buffer{};
buffer.Encoding = DXC_CP_ACP; // auto-detect text format, I guess?
buffer.Ptr = source_blob->GetBufferPointer();
buffer.Size = source_blob->GetBufferSize();
utl::vector<LPCWSTR> args;
for (const auto& arg : compiler_args)
{
args.emplace_back(arg.c_str());
}
HRESULT hr{ S_OK };
com_ptr<IDxcResult> results{ nullptr };
DXCall(hr = _compiler->Compile(&buffer, args.data(), (u32)args.size(), _include_handler.Get(), IID_PPV_ARGS(&results)));
if (FAILED(hr)) return {};
com_ptr<IDxcBlobUtf8> errors{ nullptr };
DXCall(hr = results->GetOutput(DXC_OUT_ERRORS, IID_PPV_ARGS(&errors), nullptr));
if (FAILED(hr)) return {};
if (errors && errors->GetStringLength())
{
shader_log("\nShader compilation error: \n");
shader_log(errors->GetStringPointer());
}
else
{
shader_log(" [ Succeeded ]");
}
shader_log("\n");
HRESULT status{ S_OK };
DXCall(hr = results->GetStatus(&status));
if (FAILED(hr) || FAILED(status)) return {};
com_ptr<IDxcBlob> shader{ nullptr };
DXCall(hr = results->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&shader), nullptr));
if (FAILED(hr) || !shader) return {};
dxc_compiled_shader result{};
if (is_spirv())
{
hash_byte_code((const u8*)shader->GetBufferPointer(), shader->GetBufferSize(), result.hash);
}
else
{
com_ptr<IDxcBlob> hash{ nullptr };
DXCall(hr = results->GetOutput(DXC_OUT_SHADER_HASH, IID_PPV_ARGS(&hash), nullptr));
if (FAILED(hr) || !hash) return {};
DxcShaderHash *const hash_buffer{ (DxcShaderHash *const)hash->GetBufferPointer() };
// different source code could result in the same byte code, so we only care about byte code hash.
assert(!(hash_buffer->Flags & DXC_HASHFLAG_INCLUDES_SOURCE));
static_assert(sizeof(DxcShaderHash::HashDigest) == shader_hash_length);
memcpy(&result.hash[0], &hash_buffer->HashDigest[0], shader_hash_length);
}
shader_log("Shader hash: ");
for (u32 i{ 0 }; i < shader_hash_length; ++i)
{
char hash_bytes[4]{}; // 2 chars for hex value, a space and termination 0.
snprintf(hash_bytes, sizeof(hash_bytes), "%02x ", (u32)result.hash[i]);
shader_log(hash_bytes);
}
shader_log("\n");
// NOTE: disassembly is optional (only used by the editor's shader view). DXC can only
// disassemble DXIL; use spirv-dis for SPIR-V.
buffer.Ptr = shader->GetBufferPointer();
buffer.Size = shader->GetBufferSize();
buffer.Encoding = 0;
com_ptr<IDxcResult> disasm_results{ nullptr };
if (!is_spirv() && SUCCEEDED(_compiler->Disassemble(&buffer, IID_PPV_ARGS(&disasm_results))) && disasm_results)
{
com_ptr<IDxcBlobUtf8> disassembly{ nullptr };
if (SUCCEEDED(disasm_results->GetOutput(DXC_OUT_DISASSEMBLY, IID_PPV_ARGS(&disassembly), nullptr)))
{
result.assembly.Attach(disassembly.Detach());
}
}
// NOTE: Attach() takes over the reference. (Constructing from a raw pointer adds one,
// which leaked the blobs.)
result.byte_code.Attach(shader.Detach());
result.errors.Attach(errors.Detach());
return result;
}
private:
bool is_spirv() const { return _platform == graphics::graphics_platform::vulkan; }
utl::vector<std::wstring> get_args(const shader_file_info& info, utl::vector<std::wstring>& extra_args)
{
utl::vector<std::wstring> args{};
if (info.file_name) args.emplace_back(to_wstring(info.file_name));
args.emplace_back(L"-E");
args.emplace_back(to_wstring(info.function)); // Entry function
args.emplace_back(L"-T");
args.emplace_back(to_wstring(_profile_strings[(u32)info.type])); // Target profile
args.emplace_back(L"-I");
args.emplace_back(to_wstring(shaders_source_path)); // Include path
args.emplace_back(L"-enable-16bit-types");
args.emplace_back(DXC_ARG_ALL_RESOURCES_BOUND);
#if _DEBUG
args.emplace_back(DXC_ARG_DEBUG);
args.emplace_back(DXC_ARG_SKIP_OPTIMIZATIONS);
#else
args.emplace_back(DXC_ARG_OPTIMIZATION_LEVEL3);
#endif
args.emplace_back(DXC_ARG_WARNINGS_ARE_ERRORS);
if (is_spirv())
{
add_spirv_args(args);
}
else
{
args.emplace_back(L"-Qstrip_reflect"); // Strip reflections into a separate blob
args.emplace_back(L"-Qstrip_debug"); // Strip debug information into a separate blob
}
for (const auto& arg : extra_args)
{
args.emplace_back(arg.c_str());
}
return args;
}
// HLSL -> SPIR-V for the Vulkan backend. See Docs/LinuxVulkanPort.md, Phase 5.
static void add_spirv_args(utl::vector<std::wstring>& args)
{
args.emplace_back(L"-spirv");
args.emplace_back(L"-fspv-target-env=vulkan1.3");
// Same buffer layout rules as Direct3D 12, so SharedTypes.h structs match on both backends.
// Requires the scalarBlockLayout feature (core in Vulkan 1.2).
args.emplace_back(L"-fvk-use-dx-layout");
// register(xN, space0) -> descriptor set 0, binding = N + shift.
const wchar_t* shifts[][2]{ { L"-fvk-b-shift", L"0" }, { L"-fvk-t-shift", L"100" },
{ L"-fvk-u-shift", L"200" }, { L"-fvk-s-shift", L"300" } };
for (const auto& shift : shifts)
{
args.emplace_back(shift[0]);
args.emplace_back(shift[1]);
args.emplace_back(L"0"); // register space
}
// SM 6.6 ResourceDescriptorHeap[] / SamplerDescriptorHeap[] -> one large descriptor array each
// (binding 0 of set 1 / set 2). Needs VK_EXT_mutable_descriptor_type for the resource heap.
args.emplace_back(L"-fvk-bind-resource-heap");
args.emplace_back(L"0");
args.emplace_back(L"1");
args.emplace_back(L"-fvk-bind-sampler-heap");
args.emplace_back(L"0");
args.emplace_back(L"2");
}
// NOTE: Shader Model 6.x can also be used (AS and MS are only supported from SM6.5 on).
constexpr static const char* _profile_strings[]{ "vs_6_6", "hs_6_6", "ds_6_6", "gs_6_6", "ps_6_6", "cs_6_6", "as_6_6", "ms_6_6" };
static_assert(std::size(_profile_strings) == graphics::shader_type::count);
com_ptr<IDxcCompiler3> _compiler{ nullptr };
com_ptr<IDxcUtils> _utils{ nullptr };
com_ptr<IDxcIncludeHandler> _include_handler{ nullptr };
graphics::graphics_platform _platform;
};
// Get the path to the compiled shaders binary file.
std::filesystem::path
engine_shaders_file_path(graphics::graphics_platform platform)
{
return std::filesystem::path{ graphics::get_engine_shaders_path(platform) };
}
bool
compiled_shaders_are_up_to_date(graphics::graphics_platform platform)
{
auto engine_shaders_path = engine_shaders_file_path(platform);
if (!std::filesystem::exists(engine_shaders_path)) return false;
auto shaders_compilation_time = std::filesystem::last_write_time(engine_shaders_path);
for (const auto& entry : std::filesystem::directory_iterator{ shaders_source_path })
{
if (entry.last_write_time() > shaders_compilation_time)
{
return false;
}
}
return true;
}
bool
save_compiled_shaders(utl::vector<dxc_compiled_shader>& shaders, graphics::graphics_platform platform)
{
auto engine_shaders_path = engine_shaders_file_path(platform);
std::filesystem::create_directories(engine_shaders_path.parent_path());
std::ofstream file(engine_shaders_path, std::ios::out | std::ios::binary);
if (!file || !std::filesystem::exists(engine_shaders_path))
{
file.close();
return false;
}
for (const auto& shader : shaders)
{
void *const byte_code{ shader.byte_code->GetBufferPointer() };
const u64 byte_code_length{ shader.byte_code->GetBufferSize() };
file.write((char*)&byte_code_length, sizeof(byte_code_length));
file.write((char*)&shader.hash[0], shader_hash_length);
file.write((char*)byte_code, byte_code_length);
}
file.close();
return true;
}
std::unique_ptr<u8[]>
pack_compiled_shader(dxc_compiled_shader compiled_shader, bool include_errors_and_disassembly)
{
if (compiled_shader.byte_code && compiled_shader.byte_code->GetBufferPointer() && compiled_shader.byte_code->GetBufferSize())
{
const u64 errors_length{ compiled_shader.errors ? (u64)compiled_shader.errors->GetStringLength() : 0 };
const u64 assembly_length{ compiled_shader.assembly ? (u64)compiled_shader.assembly->GetStringLength() : 0 };
const u64 extra_size{ include_errors_and_disassembly ? sizeof(u64) + sizeof(u64) + errors_length + assembly_length : 0 };
const u64 buffer_size{ sizeof(u64) + content::compiled_shader::hash_length + compiled_shader.byte_code->GetBufferSize() + extra_size };
std::unique_ptr<u8[]> buffer{ std::make_unique<u8[]>(buffer_size) };
utl::blob_stream_writer blob{ buffer.get(), buffer_size };
blob.write((u64)compiled_shader.byte_code->GetBufferSize());
blob.write(compiled_shader.hash, content::compiled_shader::hash_length);
blob.write((u8*)compiled_shader.byte_code->GetBufferPointer(), compiled_shader.byte_code->GetBufferSize());
if (include_errors_and_disassembly)
{
blob.write(errors_length);
blob.write(assembly_length);
if (errors_length) blob.write(compiled_shader.errors->GetStringPointer(), errors_length);
if (assembly_length) blob.write(compiled_shader.assembly->GetStringPointer(), assembly_length);
}
assert(blob.offset() == buffer_size);
return buffer;
}
return {};
}
} // anonymous namespace
std::unique_ptr<u8[]>
compile_shader(shader_file_info info, u8* code, u32 code_size, utl::vector<std::wstring>& extra_args, bool include_errors_and_disassembly/*=false*/,
graphics::graphics_platform platform/*=default_shader_platform*/)
{
assert(!info.file_name && info.function && code && code_size);
// NOTE: according to marcelolr (https://github.com/Microsoft/DirectXShaderCompiler/issues/79)
// "creating compiler instances is pretty cheap, so it's probably not worth the hassle of caching / sharing them."
return pack_compiled_shader(shader_compiler{ platform }.compile(code, code_size, info.type, info.function, extra_args), include_errors_and_disassembly);
}
std::unique_ptr<u8[]>
compile_shader(shader_file_info info, const char* file_path, utl::vector<std::wstring>& extra_args, bool include_errors_and_disassembly/*=false*/,
graphics::graphics_platform platform/*=default_shader_platform*/)
{
std::filesystem::path full_path{ file_path };
full_path += info.file_name;
if (!std::filesystem::exists(full_path)) return {};
// NOTE: according to marcelolr (https://github.com/Microsoft/DirectXShaderCompiler/issues/79)
// "creating compiler instances is pretty cheap, so it's probably not worth the hassle of caching / sharing them."
return pack_compiled_shader(shader_compiler{ platform }.compile(info, full_path, extra_args), include_errors_and_disassembly);
}
bool
compile_shaders(graphics::graphics_platform platform/*=default_shader_platform*/)
{
if (compiled_shaders_are_up_to_date(platform)) return true;
shader_compiler compiler{ platform };
utl::vector<dxc_compiled_shader> shaders;
std::filesystem::path full_path{};
for (u32 i{ 0 }; i < engine_shader::count; ++i)
{
auto& file = engine_shader_files[i];
full_path = shaders_source_path;
full_path += file.info.file_name;
if (!std::filesystem::exists(full_path)) return false;
utl::vector<std::wstring> extra_args{};
if (file.id == engine_shader::grid_frustums_cs ||
file.id == engine_shader::light_culling_cs)
{
// TODO: get TILE_SIZE value from d3d12::delight
extra_args.emplace_back(L"-D");
extra_args.emplace_back(L"TILE_SIZE=32");
}
dxc_compiled_shader compiled_shader{ compiler.compile(file.info, full_path, extra_args) };
if (compiled_shader.byte_code && compiled_shader.byte_code->GetBufferPointer() && compiled_shader.byte_code->GetBufferSize())
{
shaders.emplace_back(std::move(compiled_shader));
}
else
{
return false;
}
}
return save_compiled_shaders(shaders, platform);
}
Edit Engine/CMakeLists.txt
--- a/Engine/CMakeLists.txt
+++ b/Engine/CMakeLists.txt
@@ -35,6 +35,14 @@
SDL3::SDL3
)
+# Shader compiler (HLSL -> DXIL/SPIR-V via DXC). Reusable by EngineTest and, later, a Linux EngineDLL.
+# NOTE: on Windows the .vcxproj files compile EngineDLL/ShaderCompilation.cpp directly.
+find_library(DXCOMPILER_LIBRARY NAMES dxcompiler REQUIRED)
+add_library(ShaderCompiler STATIC ${PROJECT_SOURCE_DIR}/EngineDLL/ShaderCompilation.cpp)
+target_include_directories(ShaderCompiler PUBLIC ${PROJECT_SOURCE_DIR}/EngineDLL)
+target_link_libraries(ShaderCompiler PUBLIC Engine ${DXCOMPILER_LIBRARY})
+set_target_properties(ShaderCompiler PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
# PIC so the engine can later be linked into a shared EngineDLL (libEngineDLL.so) for the editor.
set_target_properties(Engine PROPERTIES
POSITION_INDEPENDENT_CODE ON
Verify (section V shadertest): compile_shaders(vulkan) writes x64/Debug/shaders/vulkan/shaders.bin (4 modules, magic
07230203), the 5 TestShader variants compile, and all 9 modules pass
spirv-val --target-env vulkan1.3 --scalar-block-layout.
Commit: Port the shader compiler to Linux and add SPIR-V output → Windows checkpoint (EngineDLL + EngineTest compile the same .cpp).
V. Verification helpers
Throwaway programs used during the session. Keep them outside the repo (or in a tools/ folder if you want them permanently).
Paths assume they're compiled from the repo root against the debug build in build/linux-debug (or build/asan).
V1 — Close / remove-in-callback / quit test (Phase 3)
#include "Platform/PlatformTypes.h"
#include "Platform/Platform.h"
#include <cstdio>
using namespace primal;
platform::window w[2];
int closed_events{ 0 };
void cb(const platform::window_event& e)
{
if (e.type != platform::window_event::closed) return;
++closed_events;
std::printf("closed event for window %u, is_closed=%d\n", (u32)(id::id_type)e.window, (int)platform::window{ e.window }.is_closed());
platform::remove_window(e.window); // removing from the callback must be safe
if (closed_events == 2) platform::post_quit();
}
int main()
{
for (auto& x : w) { platform::window_init_info i{ &cb, nullptr, "close test", 0, 0, 320, 240 }; x = platform::create_window(&i); }
w[0].close(); w[1].close();
int frames{ 0 };
while (platform::pump_events() && frames < 500) ++frames;
std::printf("loop exited after %d frames, closed_events=%d\n", frames, closed_events);
return closed_events == 2 ? 0 : 1;
}
B=build/asan # sanitizer build
clang++ -std=c++23 -g -fsanitize=address,undefined -msse4.2 -mavx2 -mfma -mf16c -D_DEBUG \
-IEngine -IEngine/Common -IEngine/ThirdParty/sal -I$(find $B/_deps -maxdepth 3 -type d -name Inc | head -1) \
closetest.cpp $B/Engine/libengine.a -lSDL3 -o closetest
SDL_VIDEO_DRIVER=x11 ./closetest; SDL_VIDEO_DRIVER=wayland ./closetest # 2 closed events, exit 0
V2 — Scratch game executable + hand-made game.bin (Phase 4)
clang++ -fsanitize=address,undefined -o game -Wl,--whole-archive build/asan/Engine/libengine.a -Wl,--no-whole-archive -lSDL3
import struct
d = struct.pack('<I', 1) # entity count
d += struct.pack('<II', 0, 1) # entity type (reserved), component count
d += struct.pack('<I', 0) # component type: transform
d += struct.pack('<9f', 1,2,3, 0,0.5,0, 1,1,1) # position, rotation (radians), scale
open('game.bin', 'wb').write(d) # put it next to the game executable
V3 — DXC CLI flag check (Phase 5)
#!/bin/bash
# usage: compile.sh <out_dir> <shader_dir> <file> <entry> <profile> [extra dxc args...]
out=$1; dir=$2; f=$3; e=$4; t=$5; shift 5
FLAGS=(-spirv -fspv-target-env=vulkan1.3 -fvk-use-dx-layout
-fvk-b-shift 0 0 -fvk-t-shift 100 0 -fvk-u-shift 200 0 -fvk-s-shift 300 0
-fvk-bind-resource-heap 0 1 -fvk-bind-sampler-heap 0 2
-enable-16bit-types -all_resources_bound -WX -I Engine/Graphics/Direct3D12/Shaders)
echo "== $f : $e $*"
dxc "${FLAGS[@]}" "$@" -T "$t" -E "$e" "$dir/$f" -Fo "$out/$e.spv" 2>&1 | head -15
[ -f "$out/$e.spv" ] && spirv-val --target-env vulkan1.3 --scalar-block-layout "$out/$e.spv" && echo "valid"
S=Engine/Graphics/Direct3D12/Shaders
./compile.sh out $S FullScreenTriangle.hlsl FullScreenTriangleVS vs_6_6
./compile.sh out $S PostProcess.hlsl PostProcessPS ps_6_6
./compile.sh out $S GridFrustums.hlsl ComputeGridFrustumsCS cs_6_6 -D TILE_SIZE=32
./compile.sh out $S CullLights.hlsl CullLightsCS cs_6_6 -D TILE_SIZE=32
./compile.sh out EngineTest TestShader.hlsl TestShaderVS vs_6_6 -D ELEMENTS_TYPE=1 # also 0 and 3
./compile.sh out EngineTest TestShader.hlsl TestShaderPS ps_6_6 -D TEXTURED_MTL=1
V4 — Shader compiler driver (Phase 5)
Links the ShaderCompiler library, compiles the engine shaders and test variants through the C++ API, and splits
the output into .spv files for spirv-val. Run it from x64/Debug (the shader paths are relative).
#include "ShaderCompilation.h"
#include <cstdio>
#include <fstream>
#include <string>
using namespace primal;
static bool write_file(const std::string& path, const u8* data, u64 size)
{
std::ofstream f{ path, std::ios::binary };
f.write((const char*)data, (std::streamsize)size);
return (bool)f;
}
int main(int argc, char** argv)
{
const std::string out{ argv[1] };
if (!compile_shaders(graphics::graphics_platform::vulkan)) { std::puts("compile_shaders FAILED"); return 1; }
// split shaders.bin: { u64 size, u8 hash[16], u8 code[size] } * N
std::ifstream bin{ "./shaders/vulkan/shaders.bin", std::ios::binary };
for (int i{ 0 }; ; ++i)
{
u64 size{ 0 }; u8 hash[16]{};
if (!bin.read((char*)&size, 8)) break;
bin.read((char*)hash, 16);
std::string code(size, '\0'); bin.read(code.data(), (std::streamsize)size);
const u32 magic{ *(const u32*)code.data() };
std::printf("engine shader %d: %llu bytes, magic %08x, hash %02x%02x..\n", i, (unsigned long long)size, magic, hash[0], hash[1]);
write_file(out + "/engine" + std::to_string(i) + ".spv", (const u8*)code.data(), size);
}
struct variant { const char* fn; graphics::shader_type::type type; const wchar_t* define; };
const variant variants[]{ { "TestShaderVS", graphics::shader_type::vertex, L"ELEMENTS_TYPE=0" },
{ "TestShaderVS", graphics::shader_type::vertex, L"ELEMENTS_TYPE=1" },
{ "TestShaderVS", graphics::shader_type::vertex, L"ELEMENTS_TYPE=3" },
{ "TestShaderPS", graphics::shader_type::pixel, nullptr },
{ "TestShaderPS", graphics::shader_type::pixel, L"TEXTURED_MTL=1" } };
int index{ 0 };
for (const auto& v : variants)
{
shader_file_info info{ "TestShader.hlsl", v.fn, v.type };
utl::vector<std::wstring> args{};
if (v.define) { args.emplace_back(L"-D"); args.emplace_back(v.define); }
auto packed = compile_shader(info, "../../EngineTest/", args, true, graphics::graphics_platform::vulkan);
if (!packed) { std::printf("variant %d FAILED\n", index); return 1; }
const u8* at{ packed.get() };
u64 size; memcpy(&size, at, 8); at += 8 + 16;
const u8* code{ at }; at += size;
u64 errors, assembly; memcpy(&errors, at, 8); memcpy(&assembly, at + 8, 8);
std::printf("variant %d: %llu bytes, errors %llu chars, disassembly %llu chars\n", index, (unsigned long long)size, (unsigned long long)errors, (unsigned long long)assembly);
write_file(out + "/variant" + std::to_string(index) + ".spv", code, size);
++index;
}
return 0;
}
B=build/linux-debug
clang++ -std=c++23 -g -msse4.2 -mavx2 -mfma -mf16c -D_DEBUG -IEngine -IEngine/Common -IEngineDLL -IEngine/ThirdParty/sal \
-I$(find $B/_deps -maxdepth 3 -type d -name Inc | head -1) \
shadertest.cpp $B/Engine/libShaderCompiler.a $B/Engine/libengine.a -ldxcompiler -lSDL3 -o shadertest
mkdir -p out && (cd x64/Debug && ../../shadertest ../../out)
for f in out/*.spv; do spirv-val --target-env vulkan1.3 --scalar-block-layout "$f" && echo "$f valid"; done
N. What's next
-
All open items, including the checklist for the next Windows boot, are in one list: "Open items" at the top of
LinuxVulkanPort.md. Keep that list current. -
Windows checkpoint and Vulkan on Windows: done 2026-11-06 (see
LinuxVulkanPort.md). -
Milestone b done on Linux 2026-11-06, c on 2026-11-07, d–g on 2026-11-08 ("Phase 6b–6g – done"): Phase 6 complete on Linux. Windows session (Open items A1–6, A9) done 2026-11-08 — 2 bugs fixed, see LinuxVulkanPort.md. Next: Phase 7 steps 2–5 on Linux. Lesson (6g): run GPU-assisted validation (
VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1) for bindless code — the normal layer can't see heap reads; GPU-AV also found a groupshared data race inCullLights.hlsl. Lesson (6e): check constants instead of assuming them —D3D12_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLEis 4; the validation layer's index-range check found it. After pulling d: deletex64/<config>/shaders/vulkan/shaders.binonce (SPIR-V entry points are nowmain). Windows build + run of b–g happens once at the end of Phase 6. Lesson: a parameter with the same name as a struct member (type,stages) is MSVC C4458 at /W4; clang only reports it with-Wshadow-all, so check new Vulkan code with that flag. -
Vulkan backend output goes through
vulkan::log_message()(stderr +OutputDebugStringAon Windows) andPRIMAL_VK_DEBUG_BREAK()(2026-11-06, "Vulkan on Windows" step 3) — use them instead offprintf/__builtin_debugtrap. -
Vulkan on Windows: plan in
LinuxVulkanPort.md(Phase 6, "Vulkan on Windows"). -
Decide: GCC support (API renames), the exact MSVC C++23 setting, moving
Direct3D12/Shaders/to a sharedGraphics/Shaders/. -
Phase 6 (Vulkan backend, milestones a–g) and Phase 7 (renderer test on Vulkan): see
LinuxVulkanPort.md. Milestone a (instance/device/frames/swapchains,SURFACEStest) is done after367babd; this file doesn't have step-by-step diffs for Phase 6 (the code is inEngine/Graphics/Vulkan/, the lessons are above). Remaining reminders: (negative viewport height: done in c,vkx::set_viewport()); DXGI →VkFormattable for textures; root constants are uniform buffers (decided in milestone b); switchTestRenderer.cppfrom#include-ingShaderCompilation.cppto linkingShaderCompileron Linux.