Crafter.Graphics/examples/VulkanTriangle/main.cpp

244 lines
9.8 KiB
C++
Raw Normal View History

2026-07-22 18:09:06 +02:00
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
2026-05-18 18:43:30 +02:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
2026-03-02 23:53:13 +01:00
#include "vulkan/vulkan.h"
2026-05-18 18:43:30 +02:00
#endif
2026-04-05 22:53:59 +02:00
#include <cassert>
2025-06-13 23:59:36 +02:00
import Crafter.Graphics;
using namespace Crafter;
2026-01-28 01:06:48 +01:00
import std;
2026-01-29 19:46:53 +01:00
import Crafter.Event;
2026-01-29 20:35:55 +01:00
import Crafter.Math;
2025-06-13 23:59:36 +02:00
2026-05-18 18:43:30 +02:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
2025-06-13 23:59:36 +02:00
int main() {
feat(device): applications ask for the device features their shaders use Device - Device::Initialize(required, optional) takes DeviceFeatures, the five core feature structs vulkan10 to vulkan14. The library enables only what its own shaders and code use. Device::enabledFeatures says what was enabled, supportedFeatures what the GPU has, apiVersion the version in use. - shaderInt16, shaderFloat16, storageBuffer16BitAccess, scalarBlockLayout and the uniform-buffer, storage-buffer and storage-image non-uniform indexing bits are no longer enabled for everyone. An application whose shaders take uint16_t spec constants passes {.vulkan10 = {.shaderInt16 = VK_TRUE}}. scalarBlockLayout stays on with the NVIDIA workaround, whose TLAS address may sit in a struct's tail padding. - Every GPU is weighed before one is chosen: Vulkan 1.3, the swapchain and, below 1.4, maintenance5 extensions, the library's needs, the required features. One that can't run the application is skipped, saying why when it ranks higher. A CPU device runs it only when nothing else is listed, and CRAFTER_GRAPHICS_DEVICE never falls back. A GPU two drivers both list is tried through each. - When no GPU qualifies, Initialize throws naming each GPU's gaps. It destroys the instance it made, before any Wayland connection, so it can be called again asking for less. - maintenance5 is vulkan14's on a 1.4 GPU and VK_KHR_maintenance5's below. CRAFTER_GRAPHICS_NO_VULKAN_1_4 runs as a 1.3 application, to exercise that path on a 1.4 GPU. - VK_KHR_spirv_1_4 and VK_KHR_shader_float_controls, core since 1.2, are no longer enabled, nor VK_EXT_shader_atomic_float, which was enabled without its feature struct. memoryDecompression's feature bit is queried before it is enabled. Shaders - VulkanShader checks a module's capabilities, declared directly or implicitly, against the enabled core features, the GPU's subgroup operations and the optional groups, and throws naming the field to pass, or saying the GPU lacks it. The tables are generated from vk.xml and SPIR-V's grammar. - WorkaroundNvidiaAS::Patch sized a row-major matrix push member by its columns, so the TLAS address could land inside it. Window - The swapchain format is one whose own feature flags allow storage reads and writes without a format, which since Vulkan 1.3 each format says for itself; shaderStorageImageRead/WriteWithoutFormat are no longer required. Tests - DeviceFeatures: ResolveFeatures, ChooseDevice and CheckShaderCapabilities, without a GPU. - FeatureRequests: required and optional features end to end, the 1.3 path, and a retry after a refusal. - PushConstantRewrite: a row-major mat3x4 push member. - HeapASRead, HeapDynamicIndexHit, RTPassPushData and the ray-tracing examples ask for the features their shaders use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:40:02 +01:00
// The raygen takes the heap's buffer start as a uint16_t spec constant.
Device::Initialize({.vulkan10 = {.shaderInt16 = VK_TRUE}});
2026-03-09 20:10:19 +01:00
Window window(1280, 720, "HelloVulkan");
2026-01-31 21:08:42 +01:00
VkCommandBuffer cmd = window.StartInit();
2026-04-05 22:53:59 +02:00
DescriptorHeapVulkan descriptorHeap;
descriptorHeap.Initialize(1,1,0);
2026-01-31 21:08:42 +01:00
2026-04-05 22:53:59 +02:00
VkSpecializationMapEntry entry = {
.constantID = 0,
.offset = 0,
.size = sizeof(uint16_t)
};
2026-02-03 21:03:11 +01:00
2026-04-05 22:53:59 +02:00
VkSpecializationInfo specilizationInfo = {
.mapEntryCount = 1,
.pMapEntries = &entry,
.dataSize = sizeof(uint16_t),
.pData = &descriptorHeap.bufferStartElement
};
2026-02-03 21:03:11 +01:00
2026-04-05 22:53:59 +02:00
std::array<VulkanShader, 3> shaders{{
{"raygen.spv", "main", VK_SHADER_STAGE_RAYGEN_BIT_KHR, &specilizationInfo},
{"miss.spv", "main", VK_SHADER_STAGE_MISS_BIT_KHR, nullptr},
{"closesthit.spv", "main", VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, nullptr}
}};
2026-02-03 21:03:11 +01:00
2026-04-05 22:53:59 +02:00
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);
2025-06-13 23:59:36 +02:00
2026-01-28 18:51:11 +01:00
Mesh triangleMesh;
2026-02-24 02:32:37 +01:00
std::array<Vector<float, 3, 3>, 3> verts {{{-150, -150, 100}, {0, 150, 100}, {150, -150, 100}}};
2026-01-29 19:18:47 +01:00
std::array<std::uint32_t, 3> index {{2,1,0}};
2026-01-28 18:51:11 +01:00
triangleMesh.Build(verts, index, cmd);
2026-02-24 02:32:37 +01:00
2026-03-09 20:10:19 +01:00
RenderingElement3D renderer = {
2026-02-24 02:32:37 +01:00
.instance = {
.instanceCustomIndex = 0,
.mask = 0xFF,
.instanceShaderBindingTableRecordOffset = 0,
.flags = VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR,
.accelerationStructureReference = triangleMesh.blasAddr
}
};
2026-03-09 20:10:19 +01:00
RenderingElement3D::elements.emplace_back(&renderer);
2026-02-24 02:32:37 +01:00
2026-01-29 20:35:55 +01:00
MatrixRowMajor<float, 4, 3, 1> transform = MatrixRowMajor<float, 4, 3, 1>::Identity();
2026-05-18 18:43:30 +02:00
transform.Store(reinterpret_cast<float*>(renderer.instance.transform.matrix));
2026-03-09 20:10:19 +01:00
RenderingElement3D::BuildTLAS(cmd, 0);
2026-04-05 22:53:59 +02:00
RenderingElement3D::BuildTLAS(cmd, 1);
RenderingElement3D::BuildTLAS(cmd, 2);
window.FinishInit();
2026-05-01 23:35:37 +02:00
auto imgSlots = descriptorHeap.AllocateImageSlots(1);
auto bufSlots = descriptorHeap.AllocateBufferSlots(1);
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
// The output image is the swapchain image the frame draws into, which
// changes from frame to frame: the window writes it into the heap at this
// slot every frame.
descriptorHeap.AddSwapchainSlot(imgSlots.firstElement, window);
// Each frame in flight has its own TLAS and its own copy of the heap.
2026-04-05 22:53:59 +02:00
VkDeviceAddressRangeKHR tlasRange0 = {
.address = RenderingElement3D::tlases[0].address,
};
2025-06-13 23:59:36 +02:00
2026-04-05 22:53:59 +02:00
VkDeviceAddressRangeKHR tlasRange1 = {
.address = RenderingElement3D::tlases[1].address,
2026-01-29 02:05:18 +01:00
};
2026-04-05 22:53:59 +02:00
VkDeviceAddressRangeKHR tlasRange2 = {
.address = RenderingElement3D::tlases[2].address,
2026-01-29 02:05:18 +01:00
};
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
VkResourceDescriptorInfoEXT resources[3] = {
2026-01-29 02:05:18 +01:00
{
2026-04-05 22:53:59 +02:00
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRange0}
2026-01-29 02:05:18 +01:00
},
2026-02-24 02:32:37 +01:00
{
2026-04-05 22:53:59 +02:00
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRange1}
},
{
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRange2}
},
2026-01-29 02:05:18 +01:00
};
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
VkHostAddressRangeEXT destinations[3] = {
2026-04-05 22:53:59 +02:00
{
2026-05-01 23:35:37 +02:00
.address = descriptorHeap.resourceHeap[0].value + descriptorHeap.BufferByteOffset(bufSlots.firstElement),
2026-04-05 22:53:59 +02:00
.size = Device::descriptorHeapProperties.bufferDescriptorSize
},
{
2026-05-01 23:35:37 +02:00
.address = descriptorHeap.resourceHeap[1].value + descriptorHeap.BufferByteOffset(bufSlots.firstElement),
2026-04-05 22:53:59 +02:00
.size = Device::descriptorHeapProperties.bufferDescriptorSize
},
{
2026-05-01 23:35:37 +02:00
.address = descriptorHeap.resourceHeap[2].value + descriptorHeap.BufferByteOffset(bufSlots.firstElement),
2026-04-05 22:53:59 +02:00
.size = Device::descriptorHeapProperties.bufferDescriptorSize
},
};
2026-01-29 02:05:18 +01:00
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
Device::vkWriteResourceDescriptorsEXT(Device::device, 3, resources, destinations);
2026-04-05 22:53:59 +02:00
descriptorHeap.resourceHeap[0].FlushDevice();
descriptorHeap.resourceHeap[1].FlushDevice();
descriptorHeap.resourceHeap[2].FlushDevice();
window.descriptorHeap = &descriptorHeap;
2026-05-01 23:35:37 +02:00
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
2026-01-29 01:31:17 +01:00
fix(vulkan-rt): work around NVIDIA descriptor-heap AS-read device-loss (#15) Reading an acceleration structure through VK_EXT_descriptor_heap aborts with VK_ERROR_DEVICE_LOST on NVIDIA 610.43.02 — a brand-new-extension driver fault isolated in #7 (engine setup is correct and validation-clean; images/buffers through the same heap work, and both traceRayEXT and inline rayQuery fault identically on the AS read). An acceleration structure can equally be reached by its device address via OpConvertUToAccelerationStructureKHR, which reads no descriptor and so never touches the faulting heap path. glslang has no GLSL spelling for that conversion, so VulkanShader rewrites the compiled SPIR-V at module-load time: every `OpLoad %accelStruct <heap-ptr>` becomes a load of the TLAS device address from a synthesized push-constant block followed by the convert. RTPass pushes the active frame's TLAS address into that push constant. User GLSL and example code are unchanged; acceleration structures still bind into the heap normally. The workaround is gated on Device::workaroundDescriptorHeapAS (true only on the NVIDIA proprietary driver) and confined to one fenced block in Crafter.Graphics-ShaderVulkan.cppm plus the RTPass push and the shaderInt64 feature toggle — delete those once a fixed NVIDIA driver ships and the heap AS read becomes the direct path again. Verified: VulkanTriangle ray-traces correctly on native NVIDIA (RTX 4090), validation-layer-clean, no device loss. The SPIR-V rewrite was independently validated with spirv-val on both the VulkanTriangle and Sponza raygen modules. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 01:59:54 +00:00
// NOTE: reading the acceleration structure through VK_EXT_descriptor_heap
// aborts with VK_ERROR_DEVICE_LOST on NVIDIA 610.43.02 (a driver fault —
// see #7). The engine transparently works around it: on the NVIDIA driver
// VulkanShader rewrites the heap AS read into a TLAS-device-address +
// OpConvertUToAccelerationStructureKHR path and RTPass feeds the address in
// as push data. Nothing here (or in raygen.glsl) changes. See README.md
// ("Native status") and interfaces/Crafter.Graphics-ShaderVulkan.cppm.
2026-01-28 01:06:48 +01:00
window.Render();
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 04:47:00 +01:00
// 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();
2025-06-13 23:59:36 +02:00
window.StartSync();
}
2026-05-18 18:43:30 +02:00
#else
// DOM-mode port. Same scene (one triangle), software-emulated raytracing
// via compute. Shaders are read from .wgsl files shipped as static
// assets (see project.cpp). Renders barycentric colors via the
// hit/miss/raygen mega-switch in PipelineRTWebGPU.
int main() {
Device::Initialize();
static Window window(1280, 720, "HelloVulkan");
auto cmd = window.StartInit();
DescriptorHeapWebGPU heap;
heap.Initialize(/*images*/ 4, /*buffers*/ 4, /*samplers*/ 2);
std::array<WebGPUShader, 3> shaders {{
WebGPUShader(std::filesystem::path("raygen.wgsl"), "raygen_main", WebGPURTStage::Raygen),
WebGPUShader(std::filesystem::path("miss.wgsl"), "miss_main", WebGPURTStage::Miss),
WebGPUShader(std::filesystem::path("closesthit.wgsl"), "closesthit_main", WebGPURTStage::ClosestHit),
}};
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 },
}};
PipelineRTWebGPU pipeline;
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, sbt);
Mesh triangleMesh;
std::array<Vector<float, 3, 3>, 3> verts {{{-150, -150, 100}, {0, 150, 100}, {150, -150, 100}}};
std::array<std::uint32_t, 3> index {{2, 1, 0}};
triangleMesh.Build(verts, index, cmd);
static RenderingElement3D renderer;
renderer.instance.transform.matrix[0][0] = 1; renderer.instance.transform.matrix[0][1] = 0; renderer.instance.transform.matrix[0][2] = 0; renderer.instance.transform.matrix[0][3] = 0;
renderer.instance.transform.matrix[1][0] = 0; renderer.instance.transform.matrix[1][1] = 1; renderer.instance.transform.matrix[1][2] = 0; renderer.instance.transform.matrix[1][3] = 0;
renderer.instance.transform.matrix[2][0] = 0; renderer.instance.transform.matrix[2][1] = 0; renderer.instance.transform.matrix[2][2] = 1; renderer.instance.transform.matrix[2][3] = 0;
renderer.instance.instanceCustomIndex = 0;
renderer.instance.mask = 0xFF;
renderer.instance.instanceShaderBindingTableRecordOffset = 0;
renderer.instance.flags = kRTGeometryInstanceForceOpaque;
renderer.instance.accelerationStructureReference = triangleMesh.blasAddr;
RenderingElement3D::Add(&renderer);
RenderingElement3D::BuildTLAS(cmd, 0);
window.descriptorHeap = &heap;
window.FinishInit();
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
window.Render();
window.StartUpdate();
window.StartSync();
}
#endif