feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data

Window
- updateInterval runs Update on the window's own clock while the
  compositor sends no frame callbacks (hidden, minimized): the Wayland loop
  is a poll() loop, and the Win32 loop sleeps until the next update. Both
  read the interval each pass.
- SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or
  whose swapchain has other than numFrames images (Mesa's Mailbox has four),
  falls back to FIFO until the mode is set again.
- AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors.
- The swapchain has TRANSFER_DST where the surface allows it.
- CaptureNextFrame replaces SaveFrame: it records the copy in the frame,
  before the present, where SaveFrame read an image already presented. A
  frame unwound past before the write still frees the readback buffer.
- Inter-pass barriers on the swapchain image carry the access masks of the
  stages the passes use.

Deferred deletion (issue #101)
- VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand
  their handles to the deletion queue from their destructors and moves, as
  a frame in flight may still use them; a static owner goes after the
  driver has torn down. VulkanShader and PipelineRTVulkan move and can't be
  copied; re-Load and re-Init queue the old pipeline.
- The queue and its mutex are never destroyed, and the queue takes handles
  from any thread; Device::frameCounter is atomic. Both the queue and the
  staging rings count frames as one window renders them (documented).
- DrainDeletions also lets every buffer's staging ring start over: without
  a Window nothing else reclaims either, so an app without one calls it
  after waiting for its work.

Meshes and buffers
- A Mesh rebuild queues the old acceleration structure and builds into the
  same storage after a barrier, so the BLAS address stays put when it fits.
  The refit and rebuild barriers cover compute ray queries too.
- RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque,
  and the refit and rebuild fallbacks keep the flags.
- A re-upload into a buffer a frame in flight may read (UploadDeviceLocal
  of the same size, UploadDeviceLocalRange) copies on the GPU, after those
  reads, through a per-frame staging ring; on ReBAR it used to write the
  buffer in place. Empty uploads record nothing.
- A compressed Mesh::Build that keeps its buffers decompresses into them
  after the reads of frames in flight, and the hit shaders and ray queries
  wait for the decompress as well as the BLAS build. Its vertex buffer
  takes a ranged refit's copies.
- Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced
  in place or erased from a vector.
- VulkanBuffer::Create asks for a device address only for buffers with
  SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the
  others have address 0. UIRenderer::RegisterBuffer refuses those.
- Build inputs are synchronized as shader reads.

Other
- RTPass pushes the app's own push data and traces at an explicit size.
- DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and
  keeps its free lists sorted.
- ImageVulkan's mip chain clamps each level to 1 texel: a non-square
  image's shorter side went to 0.
- VulkanShader throws on a missing file instead of failing in bad_alloc.
- CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct
  GPUs Vulkan lists; anything but such a number is an error.
- The debug messenger prints info messages only with
  CRAFTER_GRAPHICS_VALIDATION set.
- Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT
  headers don't compile as C++), -lcombase dropped, a reference leak fixed.
- project.cpp honours --local for Crafter.Event, Math and Asset, as Asset
  does for Math, and builds every test through one helper, projectArgs
  included.
- Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection,
  HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime,
  RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress,
  VulkanShaderLifetime, WindowUpdateClock; others extended.

Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a
buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is
std::atomic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-10-20 19:07:54 +02:00
commit 079b6b0e1f
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
47 changed files with 3572 additions and 1430 deletions

View file

@ -14,13 +14,7 @@ module;
#include <cstring>
#endif
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <windows.gaming.input.h>
#include <roapi.h>
#include <initguid.h>
#include "Crafter.Graphics-GamepadWin32.h"
#endif
module Crafter.Graphics;
import std;
@ -407,37 +401,15 @@ void Crafter::Gamepad::Rumble(Device& dev, float low, float high,
#endif
// ────────────────────────────────────────────────────────────────────
// Win32 backend (Windows.Gaming.Input via C ABI)
// Win32 backend (Windows.Gaming.Input, through Crafter.Graphics-GamepadWin32.c)
// ────────────────────────────────────────────────────────────────────
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
namespace {
using IGamepad = __x_ABI_CWindows_CGaming_CInput_CIGamepad;
using IGamepadStatics = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics;
using GamepadAddedHandler = __FIEventHandler_1_Windows__CGaming__CInput__CGamepad;
using GamepadRemovedHandler = __FIEventHandler_1_Windows__CGaming__CInput__CGamepad;
using GamepadReading = __x_ABI_CWindows_CGaming_CInput_CGamepadReading;
using GamepadVibration = __x_ABI_CWindows_CGaming_CInput_CGamepadVibration;
using GamepadButtons = __x_ABI_CWindows_CGaming_CInput_CGamepadButtons;
// Maps a connected gamepad to its Crafter::Gamepad::Device. The pointer
// is stable for as long as the gamepad stays connected.
std::unordered_map<CrafterWgiGamepad*, Crafter::Gamepad::Device*> g_byGamepad;
IGamepadStatics* g_statics = nullptr;
EventRegistrationToken g_addedToken {};
EventRegistrationToken g_removedToken {};
bool g_initialized = false;
// Cross-thread queue. WGI fires Added/Removed on a thread pool; the
// event loop drains this on the main thread inside Tick().
struct QueueEntry {
bool added;
IGamepad* gamepad; // AddRef'd
};
std::mutex g_queueMutex;
std::vector<QueueEntry> g_queue;
// Maps a live IGamepad* to its Crafter::Gamepad::Device. Pointer is
// stable from WGI's perspective for the lifetime of the connection.
std::unordered_map<IGamepad*, Crafter::Gamepad::Device*> g_byGamepad;
std::uint32_t PointerToId(IGamepad* g) {
std::uint32_t PointerToId(CrafterWgiGamepad* g) {
// Hash the pointer for a stable-while-connected id. (NonRoamableId
// would be more durable across reconnects but adds another COM
// round-trip; pointer hash is fine for v1.)
@ -449,86 +421,29 @@ namespace {
return out == 0 ? 1 : out;
}
// ── Delegate vtable for GamepadAdded / GamepadRemoved ───────────
struct AddedDelegate {
// The first member matches the C ABI vtable layout. Cast yields
// a valid GamepadAddedHandler*.
void* vtbl;
LONG refCount;
bool isAdded;
};
extern GamepadAddedHandler::__GamepadAddedHandlerVtbl g_addedVtbl;
extern GamepadAddedHandler::__GamepadAddedHandlerVtbl g_removedVtbl;
HRESULT STDMETHODCALLTYPE DelegateQI(GamepadAddedHandler* This, REFIID riid, void** out) {
if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAgileObject) ||
IsEqualIID(riid, &IID___FIEventHandler_1_Windows__CGaming__CInput__CGamepad))
{
*out = This;
This->lpVtbl->AddRef(This);
return S_OK;
}
*out = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE DelegateAddRef(GamepadAddedHandler* This) {
AddedDelegate* d = reinterpret_cast<AddedDelegate*>(This);
return (ULONG)InterlockedIncrement(&d->refCount);
}
ULONG STDMETHODCALLTYPE DelegateRelease(GamepadAddedHandler* This) {
AddedDelegate* d = reinterpret_cast<AddedDelegate*>(This);
LONG r = InterlockedDecrement(&d->refCount);
return (ULONG)r;
}
HRESULT STDMETHODCALLTYPE DelegateInvoke(GamepadAddedHandler* This, IInspectable* sender, IGamepad* gamepad) {
AddedDelegate* d = reinterpret_cast<AddedDelegate*>(This);
if (gamepad) IGamepad_AddRef(gamepad);
{
std::lock_guard<std::mutex> lock(g_queueMutex);
g_queue.push_back({ d->isAdded, gamepad });
}
return S_OK;
}
GamepadAddedHandler::__GamepadAddedHandlerVtbl g_addedVtbl = {
DelegateQI, DelegateAddRef, DelegateRelease, DelegateInvoke
};
GamepadAddedHandler::__GamepadAddedHandlerVtbl g_removedVtbl = {
DelegateQI, DelegateAddRef, DelegateRelease, DelegateInvoke
};
AddedDelegate g_addedDelegate { &g_addedVtbl, 1, true };
AddedDelegate g_removedDelegate { &g_removedVtbl, 1, false };
// Translate GamepadReading.Buttons bitfield to our Button enum.
bool ReadingHas(const GamepadReading& r, GamepadButtons b) {
return (r.Buttons & b) != 0;
}
void ApplyReading(Crafter::Gamepad::Device* dev, const GamepadReading& r) {
void ApplyReading(Crafter::Gamepad::Device* dev, const CrafterWgiReading& r) {
using B = Crafter::Gamepad::Button;
using A = Crafter::Gamepad::Axis;
struct Map { B which; GamepadButtons mask; };
struct Map { B which; std::uint32_t mask; };
static const Map buttonMap[] = {
{ B::DPadUp, GamepadButtons_DPadUp },
{ B::DPadDown, GamepadButtons_DPadDown },
{ B::DPadLeft, GamepadButtons_DPadLeft },
{ B::DPadRight, GamepadButtons_DPadRight },
{ B::Start, GamepadButtons_Menu },
{ B::Select, GamepadButtons_View },
{ B::LeftStickClick, GamepadButtons_LeftThumbstick },
{ B::RightStickClick,GamepadButtons_RightThumbstick },
{ B::LeftBumper, GamepadButtons_LeftShoulder },
{ B::RightBumper, GamepadButtons_RightShoulder },
{ B::South, GamepadButtons_A },
{ B::East, GamepadButtons_B },
{ B::West, GamepadButtons_X },
{ B::North, GamepadButtons_Y },
{ B::DPadUp, CRAFTER_WGI_BUTTON_DPAD_UP },
{ B::DPadDown, CRAFTER_WGI_BUTTON_DPAD_DOWN },
{ B::DPadLeft, CRAFTER_WGI_BUTTON_DPAD_LEFT },
{ B::DPadRight, CRAFTER_WGI_BUTTON_DPAD_RIGHT },
{ B::Start, CRAFTER_WGI_BUTTON_MENU },
{ B::Select, CRAFTER_WGI_BUTTON_VIEW },
{ B::LeftStickClick, CRAFTER_WGI_BUTTON_LEFT_THUMBSTICK },
{ B::RightStickClick,CRAFTER_WGI_BUTTON_RIGHT_THUMBSTICK },
{ B::LeftBumper, CRAFTER_WGI_BUTTON_LEFT_SHOULDER },
{ B::RightBumper, CRAFTER_WGI_BUTTON_RIGHT_SHOULDER },
{ B::South, CRAFTER_WGI_BUTTON_A },
{ B::East, CRAFTER_WGI_BUTTON_B },
{ B::West, CRAFTER_WGI_BUTTON_X },
{ B::North, CRAFTER_WGI_BUTTON_Y },
};
for (const Map& m : buttonMap) {
bool now = ReadingHas(r, m.mask);
bool now = (r.buttons & m.mask) != 0;
bool& cur = dev->buttons[(std::size_t)m.which];
if (cur == now) continue;
cur = now;
@ -545,12 +460,12 @@ namespace {
cur = v;
dev->onAxisChanged.Invoke(which);
};
axis(A::LeftStickX, (float)r.LeftThumbstickX);
axis(A::LeftStickY, (float)r.LeftThumbstickY);
axis(A::RightStickX, (float)r.RightThumbstickX);
axis(A::RightStickY, (float)r.RightThumbstickY);
axis(A::LeftTrigger, (float)r.LeftTrigger);
axis(A::RightTrigger, (float)r.RightTrigger);
axis(A::LeftStickX, (float)r.leftStickX);
axis(A::LeftStickY, (float)r.leftStickY);
axis(A::RightStickX, (float)r.rightStickX);
axis(A::RightStickY, (float)r.rightStickY);
axis(A::LeftTrigger, (float)r.leftTrigger);
axis(A::RightTrigger, (float)r.rightTrigger);
// Triggers also expose digital "pressed" buttons at a threshold.
constexpr float kTriggerThreshold = 0.1f;
@ -562,81 +477,52 @@ namespace {
if (now) dev->onButtonDown.Invoke(which);
else dev->onButtonUp .Invoke(which);
};
trigBtn(B::LeftTrigger, r.LeftTrigger);
trigBtn(B::RightTrigger, r.RightTrigger);
}
void EnsureInit() {
if (g_initialized) return;
g_initialized = true;
// RoInitialize is required once per thread; ignore RPC_E_CHANGED_MODE
// (some hosts initialize as STA, that's fine for WGI).
RoInitialize(RO_INIT_MULTITHREADED);
HSTRING_HEADER header;
HSTRING className;
const wchar_t* name = RuntimeClass_Windows_Gaming_Input_Gamepad;
if (FAILED(WindowsCreateStringReference(name,
(UINT32)wcslen(name), &header, &className))) return;
if (FAILED(RoGetActivationFactory(className,
&IID___x_ABI_CWindows_CGaming_CInput_CIGamepadStatics,
(void**)&g_statics))) return;
__x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadAdded(
g_statics,
reinterpret_cast<GamepadAddedHandler*>(&g_addedDelegate),
&g_addedToken);
__x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadRemoved(
g_statics,
reinterpret_cast<GamepadAddedHandler*>(&g_removedDelegate),
&g_removedToken);
trigBtn(B::LeftTrigger, r.leftTrigger);
trigBtn(B::RightTrigger, r.rightTrigger);
}
}
void Crafter::Gamepad::Tick() {
EnsureInit();
if (!g_statics) return;
if (!CrafterWgiStart()) return;
// Drain the cross-thread connect/disconnect queue.
std::vector<QueueEntry> pending;
{
std::lock_guard<std::mutex> lock(g_queueMutex);
pending.swap(g_queue);
}
for (QueueEntry& e : pending) {
if (!e.gamepad) continue;
if (e.added) {
if (g_byGamepad.find(e.gamepad) != g_byGamepad.end()) {
IGamepad_Release(e.gamepad);
continue;
}
auto dev = std::make_unique<Crafter::Gamepad::Device>();
dev->id = PointerToId(e.gamepad);
dev->name = "Gamepad";
auto* raw = dev.get();
g_byGamepad[e.gamepad] = raw;
connected.push_back(std::move(dev));
onConnected.Invoke(raw);
// keep AddRef'd; released on disconnect
} else {
auto it = g_byGamepad.find(e.gamepad);
if (it != g_byGamepad.end()) {
Crafter::Gamepad::Device* raw = it->second;
onDisconnected.Invoke(raw);
for (auto vi = connected.begin(); vi != connected.end(); ++vi) {
if (vi->get() == raw) { connected.erase(vi); break; }
// The connects and disconnects since the last tick.
std::array<CrafterWgiEvent, 16> events;
for (std::size_t count; (count = CrafterWgiTakeEvents(events.data(), events.size())) != 0;) {
for (const CrafterWgiEvent& e : std::span(events.data(), count)) {
if (e.added) {
if (g_byGamepad.find(e.gamepad) != g_byGamepad.end()) {
CrafterWgiRelease(e.gamepad);
continue;
}
g_byGamepad.erase(it);
auto dev = std::make_unique<Crafter::Gamepad::Device>();
dev->id = PointerToId(e.gamepad);
dev->name = "Gamepad";
auto* raw = dev.get();
g_byGamepad[e.gamepad] = raw;
connected.push_back(std::move(dev));
onConnected.Invoke(raw);
// The event's reference is kept until the disconnect.
} else {
auto it = g_byGamepad.find(e.gamepad);
if (it != g_byGamepad.end()) {
Crafter::Gamepad::Device* raw = it->second;
onDisconnected.Invoke(raw);
for (auto vi = connected.begin(); vi != connected.end(); ++vi) {
if (vi->get() == raw) { connected.erase(vi); break; }
}
// The connect's reference, then the disconnect's.
CrafterWgiRelease(it->first);
g_byGamepad.erase(it);
}
CrafterWgiRelease(e.gamepad);
}
IGamepad_Release(e.gamepad);
}
}
// Poll each connected gamepad.
for (auto& [gp, dev] : g_byGamepad) {
GamepadReading reading{};
if (FAILED(__x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(gp, &reading))) continue;
CrafterWgiReading reading {};
if (!CrafterWgiRead(gp, &reading)) continue;
ApplyReading(dev, reading);
}
}
@ -646,16 +532,13 @@ void Crafter::Gamepad::Rumble(Device& dev, float low, float high,
{
// WGI vibration is "set and forget" — no duration. Caller can stop
// by re-calling with zero magnitudes. We honor 0 duration as stop.
IGamepad* gp = nullptr;
CrafterWgiGamepad* gp = nullptr;
for (auto& [g, d] : g_byGamepad) {
if (d == &dev) { gp = g; break; }
}
if (!gp) return;
auto clamp01 = [](float v) { return v < 0 ? 0.0f : v > 1.0f ? 1.0f : v; };
GamepadVibration vib{};
vib.LeftMotor = clamp01(low);
vib.RightMotor = clamp01(high);
__x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gp, vib);
CrafterWgiVibrate(gp, clamp01(low), clamp01(high));
}
#endif