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.
431 lines
20 KiB
C++
431 lines
20 KiB
C++
//SPDX-License-Identifier: MIT
|
||
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||
|
||
// RTVolume — procedural (AABB) ray tracing on both backends. Demonstrates
|
||
// the two features this example was written to exercise:
|
||
//
|
||
// * VK_GEOMETRY_TYPE_AABBS_KHR — a BLAS built from AABBs
|
||
// (Mesh::BuildProcedural) whose surface is supplied by an intersection
|
||
// shader (here an analytic ray–sphere test). The boxes are unit cubes
|
||
// [-1,1]^3; the intersection shader turns each into a sphere.
|
||
//
|
||
// * any-hit — the spheres are registered non-opaque, and an any-hit
|
||
// shader punches a spherical checkerboard of holes by ignoring the
|
||
// intersection for half the cells. Without any-hit the spheres are
|
||
// solid; with it you can see the background (and other spheres)
|
||
// through the cut-out cells.
|
||
//
|
||
// A 3×3×3 grid of these procedural spheres is shaded by surface normal +
|
||
// a fixed sun. The Vulkan path runs the same scene through hardware RT
|
||
// (PROCEDURAL_HIT_GROUP_KHR with GLSL intersection / any-hit shaders, a
|
||
// fixed camera in raygen.glsl); the WebGPU path is the software wavefront
|
||
// tracer with a host-driven free camera.
|
||
|
||
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
|
||
#include "vulkan/vulkan.h"
|
||
|
||
import Crafter.Graphics;
|
||
import Crafter.Math;
|
||
import std;
|
||
|
||
using namespace Crafter;
|
||
|
||
namespace {
|
||
constexpr int kGrid = 3;
|
||
constexpr float kSpacing = 3.0f;
|
||
}
|
||
|
||
int main() {
|
||
const int instanceCount = kGrid * kGrid * kGrid;
|
||
std::println("[RTVolume] grid {}^3 = {} procedural spheres", kGrid, instanceCount);
|
||
|
||
// The raygen takes the heap's buffer start as a uint16_t spec constant,
|
||
// and aabbs.comp declares its AABB buffer `layout(scalar)`.
|
||
Device::Initialize({.vulkan10 = {.shaderInt16 = VK_TRUE}, .vulkan12 = {.scalarBlockLayout = VK_TRUE}});
|
||
Window window(1280, 720, "RTVolume");
|
||
VkCommandBuffer cmd = window.StartInit();
|
||
|
||
DescriptorHeapVulkan descriptorHeap;
|
||
descriptorHeap.Initialize(/*images*/ 1, /*buffers*/ 1, /*samplers*/ 0);
|
||
|
||
// Specialization constant: the TLAS slot offset (same pattern as the
|
||
// Sponza example). Camera is fixed in raygen.glsl — no user buffers.
|
||
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,
|
||
};
|
||
|
||
auto imgSlots = descriptorHeap.AllocateImageSlots(1);
|
||
auto bufSlots = descriptorHeap.AllocateBufferSlots(1);
|
||
|
||
// SBT order fixes the shader indices used by the groups below.
|
||
std::array<VulkanShader, 5> 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, nullptr },
|
||
{ "anyhit.spv", "main", VK_SHADER_STAGE_ANY_HIT_BIT_KHR, nullptr },
|
||
{ "intersection.spv", "main", VK_SHADER_STAGE_INTERSECTION_BIT_KHR, nullptr },
|
||
}};
|
||
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,
|
||
} }};
|
||
// One procedural hit group: closest-hit + any-hit + intersection.
|
||
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> hitGroups {{ {
|
||
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
|
||
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR,
|
||
.generalShader = VK_SHADER_UNUSED_KHR, .closestHitShader = 2,
|
||
.anyHitShader = 3, .intersectionShader = 4,
|
||
} }};
|
||
|
||
PipelineRTVulkan pipeline;
|
||
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, shaderTable);
|
||
|
||
// ── One procedural unit-box BLAS, built from a DEVICE buffer the GPU
|
||
// writes (issue #37). A compute shader (aabbs.comp.glsl) writes the
|
||
// box [-r,r]^3 into a device-local buffer; that buffer is fed straight
|
||
// into Mesh::BuildProcedural by device address — no host copy of the
|
||
// AABBs. The intersection shader then treats the box as the bounding
|
||
// volume of a sphere centred at the object origin. opaque=false so the
|
||
// any-hit cut-out runs. ──────────────────────────────────────────────
|
||
constexpr std::uint32_t kBoxCount = 1;
|
||
VulkanBuffer<RTAabb, false> aabbDevice;
|
||
aabbDevice.Resize(
|
||
VK_BUFFER_USAGE_2_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR
|
||
| VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT
|
||
| VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, kBoxCount);
|
||
|
||
// The producer reaches its output through a buffer_reference (device
|
||
// address pushed below). It binds no heap descriptors, but a
|
||
// descriptor-heap compute pipeline still expects a heap bound for its
|
||
// push-data path — the render loop binds it every frame, but the init
|
||
// command buffer hasn't, so bind it here before dispatching.
|
||
descriptorHeap.Bind(cmd, window.currentFrame);
|
||
|
||
ComputeShader aabbWriter;
|
||
aabbWriter.Load("aabbs.comp.spv", descriptorHeap);
|
||
struct AabbPush { VkDeviceAddress boxes; std::uint32_t count; float time; } push {
|
||
aabbDevice.address, kBoxCount, 0.0f };
|
||
aabbWriter.Dispatch(cmd, &push, sizeof(push), (kBoxCount + 63) / 64);
|
||
|
||
// Order the producing writes before the BLAS build reads the buffer. A
|
||
// build reads its geometry as a shader read.
|
||
VkMemoryBarrier aabbBarrier {
|
||
.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
|
||
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
|
||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||
};
|
||
vkCmdPipelineBarrier(cmd,
|
||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
|
||
0, 1, &aabbBarrier, 0, nullptr, 0, nullptr);
|
||
|
||
Mesh sphere;
|
||
// allowUpdate so the GPU-written boxes can be refit in place each frame
|
||
// (the per-frame companion to this build — see the headless
|
||
// BLASBuildOptions test for the device-buffer refit path).
|
||
sphere.BuildProcedural(aabbDevice.address, kBoxCount, /*opaque*/ false, cmd,
|
||
RTBuildOptions{ .allowUpdate = true });
|
||
|
||
// ── Instance grid. ─────────────────────────────────────────────────
|
||
static std::vector<RenderingElement3D> renderers;
|
||
renderers.reserve(static_cast<std::size_t>(instanceCount));
|
||
const float origin0 = -0.5f * static_cast<float>(kGrid - 1) * kSpacing;
|
||
for (int x = 0; x < kGrid; ++x)
|
||
for (int y = 0; y < kGrid; ++y)
|
||
for (int z = 0; z < kGrid; ++z) {
|
||
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] = origin0 + float(x) * kSpacing;
|
||
tx[1][0] = 0; tx[1][1] = 1; tx[1][2] = 0; tx[1][3] = origin0 + float(y) * kSpacing;
|
||
tx[2][0] = 0; tx[2][1] = 0; tx[2][2] = 1; tx[2][3] = origin0 + float(z) * kSpacing;
|
||
r.instance.instanceCustomIndex = static_cast<std::uint32_t>(renderers.size() - 1);
|
||
r.instance.mask = 0xFF;
|
||
r.instance.instanceShaderBindingTableRecordOffset = 0;
|
||
// flags = 0: do NOT force opaque, so the any-hit shader runs.
|
||
r.instance.flags = 0;
|
||
r.instance.accelerationStructureReference = sphere.blasAddr;
|
||
RenderingElement3D::Add(&r);
|
||
}
|
||
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
|
||
RenderingElement3D::BuildTLAS(cmd, f);
|
||
}
|
||
|
||
window.FinishInit();
|
||
|
||
// Write descriptors: each frame's TLAS at bufSlots[0] of that frame's
|
||
// copy of the heap — same pattern as the Sponza example. 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];
|
||
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);
|
||
destinations.reserve(Window::numFrames);
|
||
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,
|
||
});
|
||
}
|
||
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();
|
||
}
|
||
|
||
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
|
||
|
||
import Crafter.Graphics;
|
||
import Crafter.Math;
|
||
import Crafter.Event;
|
||
import std;
|
||
|
||
using namespace Crafter;
|
||
namespace fs = std::filesystem;
|
||
|
||
namespace {
|
||
constexpr int kGrid = 3;
|
||
constexpr float kSpacing = 3.0f;
|
||
|
||
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);
|
||
}
|
||
|
||
int main() {
|
||
const int instanceCount = kGrid * kGrid * kGrid;
|
||
std::println("[RTVolume] grid {}^3 = {} procedural spheres", kGrid, instanceCount);
|
||
|
||
Device::Initialize();
|
||
static Window window(1280, 720, "RTVolume");
|
||
auto cmd = window.StartInit();
|
||
|
||
DescriptorHeapWebGPU heap;
|
||
heap.Initialize(/*images*/ 1, /*buffers*/ 2, /*samplers*/ 1);
|
||
|
||
// SBT order fixes the shader indices used by the groups below.
|
||
std::array<WebGPUShader, 6> 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("anyhit.wgsl"), "anyhit_main", WebGPURTStage::AnyHit),
|
||
WebGPUShader(fs::path("intersection.wgsl"), "intersection_main", WebGPURTStage::Intersection),
|
||
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 } }};
|
||
// One procedural hit group: closest-hit + any-hit + intersection.
|
||
std::array<RTShaderGroup, 1> hitGroups {{ {
|
||
.type = RTShaderGroupType::ProceduralHitGroup,
|
||
.closestHitShader = 2,
|
||
.anyHitShader = 3,
|
||
.intersectionShader = 4,
|
||
} }};
|
||
|
||
std::array<UICustomBinding, 1> bindings {{
|
||
{ .group = 3, .binding = 0, .kind = UICustomBindingKind::Buffer, .pushOffset = 0 },
|
||
}};
|
||
|
||
PipelineRTWebGPU pipeline;
|
||
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, sbt, bindings);
|
||
|
||
// ── One procedural unit-box BLAS, built from a DEVICE buffer the GPU
|
||
// writes (issue #37). A compute shader (aabbs.comp.wgsl) writes the
|
||
// box [-r,r]^3 into a device storage buffer; that buffer is fed
|
||
// straight into Mesh::BuildProcedural by handle — no host copy of the
|
||
// AABBs — and RefitProcedural re-consumes it each frame so the boxes
|
||
// can breathe. The intersection shader treats the box as the bounding
|
||
// volume of a sphere; opaque=false so the any-hit cut-out runs. ──────
|
||
constexpr std::uint32_t kBoxCount = 1;
|
||
// worldBounds must enclose every box the producer can write (r ≤ 1.15).
|
||
constexpr RTAabb kWorldBounds { .min = {-1.2f, -1.2f, -1.2f}, .max = {1.2f, 1.2f, 1.2f} };
|
||
|
||
static WebGPUBuffer<RTAabb, false> aabbBuf;
|
||
aabbBuf.Create(kBoxCount);
|
||
|
||
// GPU producer: writes the boxes into aabbBuf. No rayQuery → the storage
|
||
// buffer binding lives at group 1.
|
||
struct AabbParams { std::uint32_t count; float time; std::uint32_t _0, _1; };
|
||
std::array<UICustomBinding, 1> aabbBindings {{
|
||
{ .group = 1, .binding = 0, .kind = UICustomBindingKind::BufferReadWrite, .pushOffset = 0 },
|
||
}};
|
||
static PlainComputeShader aabbWriter;
|
||
aabbWriter.Load(fs::path("aabbs.comp.wgsl"), sizeof(AabbParams), aabbBindings);
|
||
static std::array<std::uint32_t, 1> aabbHandles { aabbBuf.handle };
|
||
|
||
{
|
||
AabbParams params { kBoxCount, 0.0f, 0, 0 };
|
||
aabbWriter.Dispatch(¶ms, sizeof(params), aabbHandles, (kBoxCount + 63u) / 64u);
|
||
}
|
||
|
||
static Mesh sphere;
|
||
sphere.BuildProcedural(aabbBuf.handle, kBoxCount, kWorldBounds, /*opaque*/ false, cmd);
|
||
|
||
// ── Camera buffer + handle array. ─────────────────────────────────
|
||
WebGPUBuffer<CameraGPU, true> cameraBuf;
|
||
cameraBuf.Create(1);
|
||
static std::array<std::uint32_t, 1> userHandles { cameraBuf.handle };
|
||
|
||
// ── Instance grid. ────────────────────────────────────────────────
|
||
static std::vector<RenderingElement3D> renderers;
|
||
renderers.reserve(static_cast<std::size_t>(instanceCount));
|
||
const float origin0 = -0.5f * static_cast<float>(kGrid - 1) * kSpacing;
|
||
for (int x = 0; x < kGrid; ++x)
|
||
for (int y = 0; y < kGrid; ++y)
|
||
for (int z = 0; z < kGrid; ++z) {
|
||
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] = origin0 + float(x) * kSpacing;
|
||
tx[1][0] = 0; tx[1][1] = 1; tx[1][2] = 0; tx[1][3] = origin0 + float(y) * kSpacing;
|
||
tx[2][0] = 0; tx[2][1] = 0; tx[2][2] = 1; tx[2][3] = origin0 + float(z) * kSpacing;
|
||
r.instance.instanceCustomIndex = static_cast<std::uint32_t>(renderers.size() - 1);
|
||
r.instance.mask = 0xFF;
|
||
r.instance.instanceShaderBindingTableRecordOffset = 0;
|
||
// flags = 0: do NOT force opaque, so the any-hit shader runs.
|
||
r.instance.flags = 0;
|
||
r.instance.accelerationStructureReference = sphere.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 = 1; // primary only
|
||
window.passes.push_back(&rtPass);
|
||
|
||
// ── Free camera framing the grid. ─────────────────────────────────
|
||
const float ext = float(kGrid - 1) * kSpacing;
|
||
struct CamState {
|
||
Vector<float, 3, 4> position;
|
||
float yaw;
|
||
float pitch;
|
||
} cam {
|
||
Vector<float, 3, 4>{ ext * 1.1f, ext * 0.8f, ext * 1.6f },
|
||
0.0f, 0.0f,
|
||
};
|
||
{
|
||
Vector<float, 3, 4> d { -cam.position.x, -cam.position.y, -cam.position.z };
|
||
const float len = std::sqrt(d.x*d.x + d.y*d.y + d.z*d.z);
|
||
cam.yaw = std::atan2(d.z, d.x);
|
||
cam.pitch = std::asin(d.y / len);
|
||
}
|
||
|
||
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);
|
||
|
||
const float kMoveSpeed = ext * 0.8f + 1.0f;
|
||
const float kLookSens = 0.05f;
|
||
const 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;
|
||
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;
|
||
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;
|
||
cameraBuf.FlushDevice();
|
||
});
|
||
|
||
// ── Per-frame procedural refit from the device buffer (issue #37). The
|
||
// GPU producer rewrites the breathing box into aabbBuf each frame and
|
||
// RefitProcedural re-consumes it by handle — no host copy, and the
|
||
// BLAS handle (blasAddr) stays stable so the TLAS instances built
|
||
// above keep referencing it. worldBounds is constant so the TLAS need
|
||
// not rebuild. ───────────────────────────────────────────────────────
|
||
EventListener<void> aabbTick(&window.onBeforeUpdate, [&]() {
|
||
static float t = 0.0f;
|
||
t += kDt;
|
||
AabbParams params { kBoxCount, t, 0, 0 };
|
||
aabbWriter.Dispatch(¶ms, sizeof(params), aabbHandles, (kBoxCount + 63u) / 64u);
|
||
sphere.RefitProcedural(aabbBuf.handle, kBoxCount, kWorldBounds);
|
||
});
|
||
|
||
window.Render();
|
||
window.StartUpdate();
|
||
window.StartSync();
|
||
return 0;
|
||
}
|
||
#endif
|