Crafter.Graphics/examples/Sponza/main.cpp
Jorijn van der Graaf 89111e0d65
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render
At a resize RebuildSwapchain sent wp_viewport.set_destination for the
new size at once, and the configure listener, which had called it,
acknowledged the configure and committed the surface. The destination
is the surface's size, and it is state the next wl_surface.commit
applies whatever buffer is attached then. That commit was the
listener's, or the one a consumer makes to ask for a frame callback,
and it put the old frame at the new size, where it stayed until the
consumer's next frame brought a buffer of that size (#199). The
acknowledgement named that commit as the answer to the configure. And
the rebuild ran inside libwayland's dispatch: the consumer's loop stood
still in it, each new size before a frame cost a swapchain, and a
Vulkan error there was thrown from inside the dispatch, where the `try`
a consumer has around Update() does not cover it (#200).

Window: the configure listener keeps a new size (deferredLogicalWidth
and Height, surface-local) and, where a frame is owed, the serial
(unackedConfigure), and makes no Vulkan call. Render() takes what waits
at its two boundaries (RebuildIfDeferred) and makes the swapchain again
where that calls for one: first thing, for what came since the last
frame, and after its present, as before, for what its listeners and the
present asked for, and now for a size configured while they ran. Right
before its present a frame sends what the surface is to take with its
buffer (SendFrameSurfaceState): the destination, when the surface's
size is not the one last sent (sentLogicalWidth and Height), and the
acknowledgement of the configure it answers, the last one when several
came. The present's commit then applies them together with the buffer.
The constructor sends no destination: the window's first frame does.

The surface's size is state of the window for that, beside the buffers'
(logicalWidth and Height; logicalConfigured says which of the two sizes
the window was given). TakeDeferredSize makes a configured size the
surface's, unchanged, and works the pixels out of it with the scale of
that moment. MatchSizesToScale does the same before every swapchain is
made, and for a window the application sized (the constructor's size,
Resize) works the surface's size out of the pixels, which is what
RebuildSwapchain and the constructor did when they sent the
destination. The destination is that state as it is and not ceil(width
/ scale) at the present, because the scale is the compositor's to
change in any dispatch: between a configure and the frame that takes
it, and in the middle of a frame, when a listener reads the clipboard
or makes a window. And a size and a scale that change together can come
to the pixels the swapchain has: then no swapchain is made, and the
frame still brings the surface its size with the acknowledgement.

With that the destination of a configured size is the size itself,
where it was worked back from the pixels and could come out larger
(392x796 at 2.85 came back as 393x797), and a configure at the size the
surface has leaves a window the compositor sized alone while the scale
stays what it was, where it could make the window grow again (#201). A
window the application sized, configured at the size its surface has,
takes the pixels for that size once where its own do not come to it
(320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left
alone in the same way. That much of #201 comes with this change, since
the state it asks for is the one this needs. The buffers' size is still
rounded up, where the protocol rounds half away from zero: the rest of
#201.

A swapchain RebuildSwapchain made for another reason after the scale
changed (a present mode, a present that found the swapchain out of
date) applied the new scale by working the destination out again from
the pixels. It still does for a window the application sized. A window
the compositor sized keeps the surface's size and takes the pixels for
it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's
lines and sent no destination: it calls RebuildSwapchain now, and so
settles the two sizes as the other rebuilds do.

Of a Resize and a configured size the one asked for last is taken, as
when the listener resized on the spot: a configure with a size clears a
Resize that waits for its frame's present, also when its size is the
one the window has, and Resize clears a configured size that waits.

A configure that asks for nothing new while nothing is owed is
acknowledged in the listener, as before. One that comes while a size
waits, or while the surface does not show the window as it is (a
swapchain still to be made, one that has presented no frame yet, a size
not sent yet), waits for that frame. One for the size the window has,
when nothing else is owed, is acknowledged at once and takes the wait
away with it, as an acknowledgement of a serial older than the last is
a protocol error. A frame being recorded when a size comes does not
acknowledge it while that size waits; when a Resize later in the frame
takes the size's place, that frame does. The listener still commits,
which applies whatever else is pending on the surface, such as a
request for a frame callback that StartUpdate made after a frame.

For consumers: onResize for a compositor's resize fires from inside
Render(), before the onUpdate of the frame that brings the size, with
the queue idle and no frame being recorded, as Resize fires it; until
that frame the window keeps its old size on screen. A window that draws
on demand took onResize as its cue to ask for a frame, and gets
onFrameOwed for it: the Wayland backend's alone, fired from the
configure after onToplevelState, and only for a window that is still
there after that event's listeners, whenever the configure leaves a
frame owed. A size the surface does not have yet that comes to the
pixels the window has (the scale changed with it) fires onFrameOwed and
no onResize. Resize and SetPresentMode outside a frame rebuild at once
as they did, and there too the surface takes the new size with the next
frame. A rebuild that throws stays pending, since RebuildSwapchain
clears swapchainRebuildPending only once the swapchain is made, and the
next Render() tries it again. The README, the consumer notes and the
guide's gotchas say so, and the bug-prover lens section lists the
pending surface state and the scale among the re-entry contexts.

Examples: InputSystem and the native mains of VulkanTriangle, RTVolume
and Sponza drew one frame and then only ran the event loop, so nothing
would have answered a compositor's resize of their windows. They call
StartUpdate after that frame, as the examples that draw every frame do.

Not changed: a scale that changes by itself still reaches the buffers
and the surface only with the next swapchain or the next configured
size (#165); the first configure's size (#166); and Win32's WM_SIZE,
which still rebuilds from the window procedure. A window under
StartUpdate on the compositor's clock still draws from its frame
callback, so for it the rebuild, like every frame's Vulkan call, stays
inside libwayland's dispatch; one on its own clock is updated by
StartSync's loop after the dispatch, as before. #200 is answered for a
consumer that calls Update() itself. A present that fails after
SendFrameSurfaceState leaves what that sent pending for the surface's
next commit, whoever makes it.

Tests: ConfigureResize feeds the configure callbacks of a window whose
surfaces are proxies on a wl_display over a socketpair, as
ToplevelState does, with a made-up swapchain handle and no device,
steps the two ends of a frame, and reads the requests off the wire: a
configure for a new size sends one bare commit; the frame sends the
destination and the acknowledgement before its present, once; several
configures before a frame cost one of each, of the last serial; a
configure for nothing new, or back to the window's size, is
acknowledged in the listener, and the serial that waited never is; a
frame being recorded when a size comes does not acknowledge it while
the size waits, and does once a Resize has taken its place; the
window's first frame and the first at any new size of the surface bring
the destination, and a configure before it waits, and so does one for
the size a rebuild that threw is still pending for, and one that comes
after a present that found the swapchain out of date, whose surface
state is not sent a second time; without a viewport the acknowledgement
still waits. The destination is the configured size when the scale
changes before the frame, when it changes between the frame's start and
its present, and when the size and the scale together come to the
swapchain's pixels, in either order of the two events, which makes no
swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is
that size, and three more configures at it change nothing. A swapchain
made after the scale changed keeps a configured window's surface size
and an application-sized window's pixels. Of a Resize and a configured
size the later one is taken, also when it is the size the window has.
onFrameOwed fires after onToplevelState and not for a window its
listener destroyed; every acknowledgement names a later serial than the
one before.

ResizeViewport runs a window against the compositor with WAYLAND_DEBUG
set and stderr in a file, and replays the log, which has the driver's
attach and commit too: at every commit the destination in effect
belongs to the buffer in effect, to within a surface-local pixel, and
every acknowledgement of a configure that asked for a size, once the
surface has a buffer, is committed with a buffer of that size in effect
and with that size itself as the destination, through a Resize with a
commit before the next frame, a size the compositor configures (the
window asks to be maximized), and one it configures while the frame
loop of StartUpdate runs (the window asks to be restored), which that
loop takes and answers by itself. Where the compositor configures no
other size at that request, the step is a SKIP, and the test holds the
log to it: no configure for another size came. `ResizeViewport
--keyboard` is the manual probe for a phone: it asks for text input and
takes it back three times (SetTextInput), which is what brings a
phone's on-screen keyboard up and down, and holds the resizes that
makes to the same checks.
2026-11-19 09:03:28 +01:00

491 lines
22 KiB
C++

//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza on Vulkan + WebGPU. Same example source, two backends — picked
// by CRAFTER_GRAPHICS_WINDOW_DOM. Both paths:
// 1. Load a Sponza .cmesh (positions + indices, optional per-vertex
// data region) and a single albedo .ctex from disk. The source
// assets are fetched once by project.cpp (Crafter.Build::GitFetch)
// from https://github.com/jimmiebergmann/Sponza and compressed
// into the bin dir at build time — they don't live in this repo.
// 2. Build BLAS + TLAS via the existing Mesh / RenderingElement3D
// flow. The on-disk format is identical between backends; only
// the decompression path differs (VK_EXT_memory_decompression
// on Vulkan, CPU GDeflate on WebGPU).
// 3. Upload the albedo as Image2D<RGBA8>, register it in the
// backend descriptor heap, and run the RT pipeline. Closest-hit
// shaders sample the texture at the hit's barycentric coords —
// proof-of-binding rather than UV-correct shading. Per-vertex
// UV interpolation is follow-up work (the attribs heap is in
// place on WebGPU; the Vulkan side needs a sibling data buffer
// exposed off Mesh).
//
// Sponza model: CC BY 3.0 — Frank Meinl (Crytek), packaged by Jimmie
// Bergmann and Morgan McGuire. https://casual-effects.com/data
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
#include "vulkan/vulkan.h"
#endif
import Crafter.Graphics;
import Crafter.Asset;
import Crafter.Math;
import Crafter.Event;
import std;
using namespace Crafter;
namespace fs = std::filesystem;
namespace {
struct RGBA8 { std::uint8_t r, g, b, a; };
void RequireAssets(const fs::path& mesh, const fs::path& tex) {
const bool haveMesh = fs::exists(mesh);
const bool haveTex = fs::exists(tex);
if (haveMesh && haveTex) return;
std::println(std::cerr,
"[Sponza] missing asset(s):\n"
" mesh: {} {}\n"
" albedo: {} {}\n"
"The build should have populated these via cfg.assets +\n"
"GitFetch (see examples/Sponza/project.cpp). If you ran\n"
"the binary from outside its bin dir, cd into the bin dir\n"
"first — asset paths are relative to cwd.",
mesh.string(), haveMesh ? "OK" : "MISSING",
tex.string(), haveTex ? "OK" : "MISSING");
std::abort();
}
}
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
int main() {
// Native Vulkan path is single-material for now (see file header) —
// pick up just the first per-material output the build emits. The
// WebGPU branch below uses every mesh + a texture array.
const fs::path meshPath = "mesh_0.cmesh";
const fs::path texPath = "tex_0.ctex";
RequireAssets(meshPath, texPath);
CompressedMeshAsset loadedMesh = LoadCompressedMesh(meshPath);
CompressedTextureAsset loadedTex = LoadCompressedTexture(texPath);
std::println("[Sponza] loaded {} verts, {} idx, {}x{} albedo",
loadedMesh.vertexCount, loadedMesh.indexCount,
loadedTex.sizeX, loadedTex.sizeY);
// The raygen and closest-hit shaders take heap slots as uint16_t spec
// constants.
Device::Initialize({.vulkan10 = {.shaderInt16 = VK_TRUE}});
Window window(1280, 720, "Sponza");
VkCommandBuffer cmd = window.StartInit();
DescriptorHeapVulkan descriptorHeap;
descriptorHeap.Initialize(/*images*/ 2, /*buffers*/ 1, /*samplers*/ 1);
// Specialization constants: the TLAS slot offset for raygen (shared
// with the VulkanTriangle pattern), and the albedo's image and sampler
// slots for closesthit.
VkSpecializationMapEntry raygenEntry = { .constantID = 0, .offset = 0, .size = sizeof(std::uint16_t) };
VkSpecializationInfo raygenSpec = {
.mapEntryCount = 1, .pMapEntries = &raygenEntry,
.dataSize = sizeof(std::uint16_t), .pData = &descriptorHeap.bufferStartElement,
};
// Allocate the albedo's slots first so their indices are known when we
// compile closesthit.spv.
auto imgSlots = descriptorHeap.AllocateImageSlots(2);
auto bufSlots = descriptorHeap.AllocateBufferSlots(1);
auto samplerSlots = descriptorHeap.AllocateSamplerSlots(1);
std::uint16_t albedoHeapSlot = static_cast<std::uint16_t>(imgSlots.firstElement + 1);
const std::array<std::uint16_t, 2> hitConstants { albedoHeapSlot, samplerSlots.firstElement };
const std::array<VkSpecializationMapEntry, 2> hitEntries {{
{ .constantID = 0, .offset = 0, .size = sizeof(std::uint16_t) },
{ .constantID = 1, .offset = sizeof(std::uint16_t), .size = sizeof(std::uint16_t) },
}};
VkSpecializationInfo hitSpec = {
.mapEntryCount = static_cast<std::uint32_t>(hitEntries.size()), .pMapEntries = hitEntries.data(),
.dataSize = sizeof(hitConstants), .pData = hitConstants.data(),
};
std::array<VulkanShader, 3> shaders {{
{ "raygen.spv", "main", VK_SHADER_STAGE_RAYGEN_BIT_KHR, &raygenSpec },
{ "miss.spv", "main", VK_SHADER_STAGE_MISS_BIT_KHR, nullptr },
{ "closesthit.spv", "main", VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, &hitSpec },
}};
ShaderBindingTableVulkan shaderTable;
shaderTable.Init(shaders);
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> raygenGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 0, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> missGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 1, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> hitGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR,
.generalShader = VK_SHADER_UNUSED_KHR, .closestHitShader = 2,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
PipelineRTVulkan pipeline;
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, shaderTable);
Mesh sponzaMesh;
sponzaMesh.Build(loadedMesh, cmd);
Image2D<RGBA8> albedo;
albedo.Create(loadedTex.sizeX, loadedTex.sizeY, /*mipLevels*/ 1, cmd,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
albedo.Update(loadedTex, cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
static RenderingElement3D renderer;
renderer.instance = {
.transform = {},
.instanceCustomIndex = 0,
.mask = 0xFF,
.instanceShaderBindingTableRecordOffset = 0,
.flags = VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR,
.accelerationStructureReference = sponzaMesh.blasAddr,
};
MatrixRowMajor<float, 4, 3, 1>::Identity()
.Store(reinterpret_cast<float*>(renderer.instance.transform.matrix));
RenderingElement3D::elements.emplace_back(&renderer);
RenderingElement3D::BuildTLAS(cmd, 0);
RenderingElement3D::BuildTLAS(cmd, 1);
RenderingElement3D::BuildTLAS(cmd, 2);
window.FinishInit();
// Write descriptors: TLAS at bufSlots[0] and albedo (a sampled image) at
// imgSlots[1], into every frame's copy of the heap, each frame with its
// own TLAS, and the albedo's sampler at samplerSlots[0] in the sampler
// heap. The output image at imgSlots[0] is the swapchain's, which the
// window writes every frame with the image that frame draws into.
descriptorHeap.AddSwapchainSlot(imgSlots.firstElement, window);
VkDeviceAddressRangeKHR tlasRanges[Window::numFrames];
// The heap takes an image view's create-info, not a VkImageView.
const VkImageViewCreateInfo albedoView {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = albedo.image,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_R8G8B8A8_UNORM,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.levelCount = albedo.mipLevels,
.layerCount = 1,
},
};
const VkImageDescriptorInfoEXT albedoInfo {
.sType = VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT,
.pView = &albedoView,
.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
tlasRanges[f] = { .address = RenderingElement3D::tlases[f].address };
}
std::vector<VkResourceDescriptorInfoEXT> resources;
std::vector<VkHostAddressRangeEXT> destinations;
resources.reserve(Window::numFrames * 2);
destinations.reserve(Window::numFrames * 2);
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
resources.push_back({
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRanges[f] },
});
destinations.push_back({
.address = descriptorHeap.resourceHeap[f].value
+ descriptorHeap.BufferByteOffset(bufSlots.firstElement),
.size = Device::descriptorHeapProperties.bufferDescriptorSize,
});
resources.push_back({
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
.data = { .pImage = &albedoInfo },
});
destinations.push_back({
.address = descriptorHeap.resourceHeap[f].value
+ descriptorHeap.ImageByteOffset(albedoHeapSlot),
.size = Device::descriptorHeapProperties.imageDescriptorSize,
});
}
Device::vkWriteResourceDescriptorsEXT(Device::device,
static_cast<std::uint32_t>(resources.size()),
resources.data(), destinations.data());
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
descriptorHeap.resourceHeap[f].FlushDevice();
}
// The sampler heap takes a sampler's create-info, as
// UIRenderer::RegisterSampler writes it.
const VkSamplerCreateInfo albedoSamplerInfo {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.maxLod = VK_LOD_CLAMP_NONE,
};
VkSamplerCreateInfo samplerInfos[Window::numFrames];
VkHostAddressRangeEXT samplerDestinations[Window::numFrames];
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
samplerInfos[f] = albedoSamplerInfo;
samplerDestinations[f] = {
.address = descriptorHeap.samplerHeap[f].value
+ descriptorHeap.SamplerByteOffset(samplerSlots.firstElement),
.size = Device::descriptorHeapProperties.samplerDescriptorSize,
};
}
Device::vkWriteSamplerDescriptorsEXT(Device::device, Window::numFrames,
samplerInfos, samplerDestinations);
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
descriptorHeap.samplerHeap[f].FlushDevice();
}
window.descriptorHeap = &descriptorHeap;
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
window.Render();
// The scene is still, but its frames keep coming: a frame is what shows
// it at a new size, and on Wayland what answers the compositor when it
// resizes the window.
window.StartUpdate();
window.StartSync();
return 0;
}
#else
int main() {
// ── Read scene manifest (produced by project.cpp's ImportSponzaBundle).
//
// line 1: albedoCount
// line 2: meshCount
// line 3..: per-mesh albedoIdx (-1 means "no albedo")
const fs::path manifestPath = "scene.txt";
if (!fs::exists(manifestPath)) {
std::println(std::cerr,
"[Sponza] missing scene.txt — the build should have produced "
"it (see examples/Sponza/project.cpp). If you ran the binary "
"from outside its bin dir, cd in first.");
std::abort();
}
std::ifstream manifest(manifestPath);
std::uint32_t albedoCount = 0, meshCount = 0;
manifest >> albedoCount >> meshCount;
std::vector<std::int32_t> meshAlbedo(meshCount);
for (std::uint32_t i = 0; i < meshCount; ++i) manifest >> meshAlbedo[i];
std::println("[Sponza] scene: {} albedos, {} meshes", albedoCount, meshCount);
Device::Initialize();
static Window window(1280, 720, "Sponza");
auto cmd = window.StartInit();
DescriptorHeapWebGPU heap;
heap.Initialize(/*images*/ 2, /*buffers*/ 2, /*samplers*/ 2);
std::array<WebGPUShader, 4> shaders {{
WebGPUShader(fs::path("raygen.wgsl"), "raygen_main", WebGPURTStage::Raygen),
WebGPUShader(fs::path("miss.wgsl"), "miss_main", WebGPURTStage::Miss),
WebGPUShader(fs::path("closesthit.wgsl"), "closesthit_main", WebGPURTStage::ClosestHit),
WebGPUShader(fs::path("resolve.wgsl"), "resolve_main", WebGPURTStage::Resolve),
}};
ShaderBindingTableWebGPU sbt;
sbt.Init(shaders);
std::array<RTShaderGroup, 1> raygenGroups {{
{ .type = RTShaderGroupType::General, .generalShader = 0 },
}};
std::array<RTShaderGroup, 1> missGroups {{
{ .type = RTShaderGroupType::General, .generalShader = 1 },
}};
std::array<RTShaderGroup, 1> hitGroups {{
{ .type = RTShaderGroupType::TrianglesHitGroup, .closestHitShader = 2 },
}};
// Three user bindings at @group(3) (the wavefront pipeline reserves
// groups 0..2 for WfParams / data heaps / indirect args):
// binding 0 — albedo texture_2d_array (one layer per material)
// binding 1 — sampler (linear clamp)
// binding 2 — Camera storage buffer (host-driven, updated per frame)
std::array<UICustomBinding, 3> bindings {{
{ .group = 3, .binding = 0, .kind = UICustomBindingKind::SampledTextureArray, .pushOffset = 0 },
{ .group = 3, .binding = 1, .kind = UICustomBindingKind::Sampler, .pushOffset = 0 },
{ .group = 3, .binding = 2, .kind = UICustomBindingKind::Buffer, .pushOffset = 0 },
}};
PipelineRTWebGPU pipeline;
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, sbt, bindings);
// ── Albedo texture array — one rgba8unorm layer per material. ──────
//
// Probe layer 0 for the canonical layer dimensions; project.cpp
// already resized every albedo to the same square so any tex_N.ctex
// would do, layer 0 is just the first one we have.
Image2DArray<RGBA8> albedoArray;
{
CompressedTextureAsset probe = LoadCompressedTexture("tex_0.ctex");
albedoArray.Create(probe.sizeX, probe.sizeY, static_cast<std::uint16_t>(albedoCount));
albedoArray.UpdateLayer(0, probe);
for (std::uint32_t i = 1; i < albedoCount; ++i) {
CompressedTextureAsset tex = LoadCompressedTexture(std::format("tex_{}.ctex", i));
albedoArray.UpdateLayer(static_cast<std::uint16_t>(i), tex);
}
}
auto albedoArraySlot = albedoArray.AllocateSlot(heap);
SamplerSlot samplerSlot = AllocateLinearClampSampler(heap);
// Camera storage buffer — host writes (origin, right, up, forward,
// aspect, tanHalf) every frame from the input-driven free camera
// below. Layout matches the WGSL Camera struct in raygen.wgsl
// (vec3-aligned, std430). 64 bytes total.
struct CameraGPU {
float origin[3]; float pad0;
float right[3]; float tanHalf;
float up[3]; float aspect;
float forward[3]; float pad1;
};
static_assert(sizeof(CameraGPU) == 64);
WebGPUBuffer<CameraGPU, true> cameraBuf;
cameraBuf.Create(1);
// Handle array fed to RTPass — order matches the bindings declaration.
static std::array<std::uint32_t, 3> userHandles {
heap.imageTable [albedoArraySlot.firstElement],
heap.samplerTable[samplerSlot.firstElement],
cameraBuf.handle,
};
// ── Meshes + scene instances ───────────────────────────────────────
//
// One Mesh + one RenderingElement3D per material group from
// scene.txt. Meshes whose albedoIdx is -1 (the .obj's `usemtl` named
// something without a map_Kd in .mtl) get dropped — they're rare in
// Sponza and we'd have nothing to sample for them anyway.
//
// Vector capacity is reserved up-front: RenderingElement3D::Add
// takes a pointer that's stored in the static elements[] vector, so
// any later vector reallocation would dangle those pointers.
static std::vector<Mesh> meshes;
static std::vector<RenderingElement3D> renderers;
meshes.reserve(meshCount);
renderers.reserve(meshCount);
for (std::uint32_t i = 0; i < meshCount; ++i) {
if (meshAlbedo[i] < 0) continue;
CompressedMeshAsset loaded = LoadCompressedMesh(std::format("mesh_{}.cmesh", i));
meshes.emplace_back();
meshes.back().Build(loaded, cmd);
renderers.emplace_back();
RenderingElement3D& r = renderers.back();
auto& tx = r.instance.transform.matrix;
tx[0][0] = 1; tx[0][1] = 0; tx[0][2] = 0; tx[0][3] = 0;
tx[1][0] = 0; tx[1][1] = 1; tx[1][2] = 0; tx[1][3] = 0;
tx[2][0] = 0; tx[2][1] = 0; tx[2][2] = 1; tx[2][3] = 0;
// 24-bit instanceCustomIndex carries the albedo array layer that
// closesthit.wgsl reads as `hit.customIndex`.
r.instance.instanceCustomIndex = static_cast<std::uint32_t>(meshAlbedo[i]);
r.instance.mask = 0xFF;
r.instance.instanceShaderBindingTableRecordOffset = 0;
r.instance.flags = kRTGeometryInstanceForceOpaque;
r.instance.accelerationStructureReference = meshes.back().blasAddr;
RenderingElement3D::Add(&r);
}
RenderingElement3D::BuildTLAS(cmd, 0);
window.descriptorHeap = &heap;
window.FinishInit();
RTPass rtPass(&pipeline);
rtPass.handlesPtr = userHandles.data();
rtPass.handlesCount = static_cast<std::uint32_t>(userHandles.size());
rtPass.maxDepth = 2; // primary + shadow
window.passes.push_back(&rtPass);
// ── Free camera: WASD + mouse-delta look ───────────────────────────
//
// Initial pose puts the camera near one end of the atrium at eye
// height, looking +X down the long axis (bbox: X[-1921..1800],
// Y[-126..1429], Z[-1183..1105]). The user can fine-tune from there.
struct CamState {
// 3/4 view from a corner aimed at the atrium centre.
Vector<float, 3, 4> position{ -1400.0f, 700.0f, -600.0f };
float yaw = 0.405f; // radians, around world +Y
float pitch = -0.317f; // radians, +pitch looks up
} cam;
Input::Map inputMap;
Input::Action& moveAct = inputMap.AddAction("Move", Input::ActionType::Vector2);
Input::Action& lookAct = inputMap.AddAction("Look", Input::ActionType::Vector2);
moveAct.bindings = {
Input::WASDBind{
Key(CrafterKeys::W), Key(CrafterKeys::S),
Key(CrafterKeys::A), Key(CrafterKeys::D),
},
};
lookAct.bindings = {
Input::MouseDeltaBind{ 1.0f },
};
inputMap.Attach(window);
constexpr float kMoveSpeed = 1200.0f; // Sponza units / second (room is ~3700 wide)
constexpr float kLookSens = 0.05f; // radians per mouse pixel
constexpr float kDt = 1.0f / 60.0f;
EventListener<void> camTick(&window.onBeforeUpdate, [&]() {
inputMap.Tick();
cam.yaw += lookAct.vector2.x * kLookSens;
cam.pitch -= lookAct.vector2.y * kLookSens;
// Keep pitch just shy of straight up/down so the basis vectors
// don't collapse (cross(forward, world_up) would go zero).
cam.pitch = std::clamp(cam.pitch, -1.55f, 1.55f);
const float cp = std::cos(cam.pitch), sp = std::sin(cam.pitch);
const float cy = std::cos(cam.yaw), sy = std::sin(cam.yaw);
Vector<float, 3, 4> forward { cp * cy, sp, cp * sy };
Vector<float, 3, 4> worldUp { 0.0f, 1.0f, 0.0f };
Vector<float, 3, 4> right { forward.y * worldUp.z - forward.z * worldUp.y,
forward.z * worldUp.x - forward.x * worldUp.z,
forward.x * worldUp.y - forward.y * worldUp.x };
const float rLen = std::sqrt(right.x*right.x + right.y*right.y + right.z*right.z);
right.x /= rLen; right.y /= rLen; right.z /= rLen;
Vector<float, 3, 4> up { right.y * forward.z - right.z * forward.y,
right.z * forward.x - right.x * forward.z,
right.x * forward.y - right.y * forward.x };
const float dx = moveAct.vector2.x * kMoveSpeed * kDt;
const float dy = moveAct.vector2.y * kMoveSpeed * kDt;
cam.position.x += right.x * dx + forward.x * dy;
cam.position.y += right.y * dx + forward.y * dy;
cam.position.z += right.z * dx + forward.z * dy;
CameraGPU& g = cameraBuf.value[0];
g.origin[0] = cam.position.x; g.origin[1] = cam.position.y; g.origin[2] = cam.position.z; g.pad0 = 0.0f;
g.right[0] = right.x; g.right[1] = right.y; g.right[2] = right.z;
g.up[0] = up.x; g.up[1] = up.y; g.up[2] = up.z;
g.forward[0] = forward.x; g.forward[1] = forward.y; g.forward[2] = forward.z;
g.aspect = float(window.width) / float(window.height);
g.tanHalf = std::tan(70.0f * 3.14159265f / 360.0f);
g.pad1 = 0.0f;
cameraBuf.FlushDevice();
});
window.Render();
window.StartUpdate();
window.StartSync();
return 0;
}
#endif