Compare commits

...
Sign in to create a new pull request.

95 commits

Author SHA1 Message Date
42a479572d SPDX license update 2026-07-22 18:09:06 +02:00
a879c834c7 webgpu embedding 2026-07-19 01:38:25 +02:00
47bd4da0e3 Merge pull request 'test(bench): measure net perf gain from #40 to master in Sponza (#155)' (#156) from claude/issue-155 into master 2026-06-18 21:36:37 +02:00
catbot
619e39369d test(bench): SponzaBench harness + #40→HEAD perf measurement (#155)
Headless benchmark around the native Sponza RT scene: times setup and a
measured Render() loop over the full multi-mesh atrium, prints BENCH
metrics, and exits. Includes run-bench.sh and a README documenting the
methodology and the measured net gain from #40 to current master.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 19:35:54 +00:00
catbot
3e116e6e43 feat(window): env-gated uncapped present mode for benchmarking
CRAFTER_PRESENT_IMMEDIATE selects IMMEDIATE (then MAILBOX) when the
surface offers it, instead of the default FIFO. Needed to measure
steady-state frame throughput without the compositor's vblank cap; FIFO
remains the default when the variable is unset.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 19:35:54 +00:00
fc71eb36b9 Merge pull request 'fix(window): silence per-frame and setup-path Vulkan validation errors (#153)' (#154) from claude/issue-153 into master 2026-06-18 20:05:06 +02:00
catbot
7316e51dca fix(window): silence per-frame and setup-path Vulkan validation errors (#153)
Two distinct validation errors the native frame loop emitted, both
originating in Crafter.Graphics with no consumer-side influence.

Problem 1 — per-frame acquire-barrier access/stage mismatch. The
acquire->GENERAL barrier hardcoded dstAccessMask =
SHADER_WRITE|TRANSFER_WRITE but used the per-pass stage union as its dst
stage mask. For an all-compute frame the union narrows to COMPUTE_SHADER,
which does not support TRANSFER_WRITE, so VUID-02820 fired every frame.
Derive the access mask from the same stage union via a new
SwapchainWriterAccess() helper (mirroring SwapchainStageUnion), and apply
it to both the acquire dst and present src masks for symmetry.

Problem 2 — mid-session StartInit/FinishInit (and GetCmd/EndCmd) reuse the
shared drawCmdBuffers[currentBuffer]. With no steady-state wait-idle the
loop's last submission of that buffer may still be in flight when scene
setup runs (building map meshes / acceleration structures), so the old
code re-began (VUID-00049) and re-submitted (VUID-00071) a pending buffer,
and resources freed in the StartInit..FinishInit bracket could still be
referenced by it. Drain the queue at the start of StartInit/GetCmd before
re-recording; setup is rare, so a wait-idle is fine (FinishInit/EndCmd
already wait-idle at the end).

Tests: extend SwapchainBarrierScope with SwapchainWriterAccess coverage
(pure CPU), and add SetupCmdBufferReuse — a real-frame-loop regression
test driving a compute pass plus interleaved mid-session StartInit rounds,
asserting the validation layer stays silent. Verified both halves fail
(reproducing the exact VUIDs) when their respective fix is reverted.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 18:04:25 +00:00
7720f0a9bc Merge pull request 'perf(window): block message loop while paused on Win32 (#134)' (#152) from claude/issue-134 into master 2026-06-18 16:01:28 +02:00
23e2416ef0 Merge pull request 'perf(webgpu): byteCount-bounded readback for over-provisioned buffers (#133)' (#151) from claude/issue-133 into master 2026-06-18 16:01:18 +02:00
catbot
7df82e4fee perf(window): block message loop while paused on Win32 (#134)
When `updating` is false (paused / minimized / stopped), the FIFO
present no longer paces StartSync()'s message loop, so the bare
PeekMessage(PM_REMOVE) spin pinned a core at 100% while uselessly
re-running Gamepad::Tick() (mutex + per-pad COM reads) and
onBeforeUpdate every iteration.

Block on MsgWaitForMultipleObjectsEx with a short timeout while
!updating: the loop now wakes on input or every ~16ms, eliminating the
busy-spin while preserving gamepad polling / onBeforeUpdate at a sane
rate (e.g. to detect a controller button asking to resume). The
updating path is unchanged — present remains vsync-gated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 14:00:58 +00:00
catbot
931500ddc3 perf(webgpu): byteCount-bounded readback for over-provisioned buffers (#133)
WebGPUBuffer::EnqueueReadback / PollReadback always copied the full
buffer `size` GPU→staging→wasm. Over-provisioned event-queue buffers
(e.g. Forts3D's GPU physics event drain) paid the full-capacity copy
every drain even when only a small live prefix held data.

Add an optional `byteCount` parameter (default 0 = whole buffer, so the
existing full-buffer callers are unchanged) bounding the readback to the
live prefix. Pass the same byteCount to the paired PollReadback so the
matching number of bytes lands in `.value`.

JS bridge: the staging buffer is now sized to the full device-buffer
capacity (not the first call's byteSize) so a varying prefix length never
overflows it, while the copyBufferToBuffer + mapAsync/getMappedRange are
bounded to the requested prefix — that's where the copy saving lands.

Verified end-to-end in the browser via RayQueryPick: the full readback
still resolves correctly, and a follow-up 8-byte prefix read copies only
hit+customIndex while primitiveIndex keeps its poison sentinel, proving
the copy was bounded. Native `crafter-build test` suite: 24 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 14:00:36 +00:00
cd3a55a914 Merge pull request 'perf(rt): batch the WebGPU TLAS instance upload into one writeBuffer (#131)' (#150) from claude/issue-131 into master 2026-06-18 16:00:10 +02:00
catbot
10e07575fb perf(rt): batch the WebGPU TLAS instance upload into one writeBuffer (#131)
BuildTLASUpload pushed GPU-driven (transformOwnedByGpu) runs one element
at a time — a separate FlushDeviceRange of the 16 strided metadata bytes
per element — each paying WebGPU validation / encode / JS-boundary cost,
while the CPU-driven arm already batched contiguously.

Upload the whole active instance range in a single writeBuffer instead.
Pushing the (stale) transform bytes for GPU-driven slots is harmless: the
only supported way to drive a transform from the GPU is the manual
Upload -> physics compute pass -> Build sequence, and that compute pass
runs after this upload and rewrites the transform on the GPU before the
TLAS build reads it. For the in-repo (all-CPU) usage the bytes uploaded
are identical to before — with one CPU-driven run the old loop already
emitted exactly this single FlushDeviceRange(0, 0, primitiveCount*64).

Verified: native suite (24 passed) and the RTStress wasm example (512
ray-traced instances) render correctly through the new path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:59:26 +00:00
77bc6f7aec Merge pull request 'perf(webgpu): range-flush only live TLAS metadata slots (#130)' (#149) from claude/issue-130 into master 2026-06-18 15:56:46 +02:00
catbot
db35e78eaf perf(webgpu): range-flush only live TLAS metadata slots (#130)
The metadata mirror is padded to kNPadded (65536) but only primitiveCount
slots are live. metadataBuffer.FlushDevice() wgpuWriteBuffer'd all 256 KB
through the WASM->JS staging path every frame (~100-250x waste for a
few-hundred-instance scene). Switch to the existing FlushDeviceRange
overload — the same one the instanceBuffer loop directly above uses —
sized to primitiveCount * sizeof(uint32_t). The Vulkan parallel already
sizes its flush to primitiveCount, so this was WebGPU-specific.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:56:21 +00:00
4c659319cb Merge pull request 'perf(ui): reuse handles vector in WebGPU custom Dispatch (#132)' (#148) from claude/issue-132 into master 2026-06-18 15:54:36 +02:00
catbot
cb650f965d perf(ui): reuse handles vector in WebGPU custom Dispatch (#132)
UIRenderer::Dispatch built a fresh std::vector<uint32_t> with reserve on
every call, paying one malloc+free per dispatch. Custom compute dispatches
run per-frame, so make the vector thread_local and clear() it each call:
capacity grows to the high-water mark once and is reused thereafter,
eliminating the per-frame allocation churn. Behavior is identical.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:54:09 +00:00
a4fdbf7d30 Merge pull request 'perf(ui): per-shelf dirty spans for tight font-atlas uploads (#129)' (#147) from claude/issue-129 into master 2026-06-18 15:36:33 +02:00
catbot
16d291b0ad perf(ui): per-shelf dirty spans for tight atlas uploads (#129)
FontAtlas::Update used a single union bounding box for the dirty rect.
Scattered new glyphs landing on different shelves produced a tall union
box that re-uploaded mostly-unchanged texels between the shelves.

Track a dirty span per shelf instead and issue one tight UpdateRegion /
wgpuWriteAtlasRegion copy per armed span. A shelf packs glyphs
left-to-right at a fixed top, so each span stays a contiguous X run
capped by the shelf height. The whole-atlas zero-clear in Initialize
keeps using the existing dirtyRect span. `dirty` is now the OR of every
span and is cleared together with them in Update.

Verified: full test suite green (23 passed); HelloUI text renders
crisply on the WebGPU backend through the new multi-span upload path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:35:54 +00:00
9cf972016c Merge pull request 'perf(ui): memoize the input-field caret prefix width (#128)' (#146) from claude/issue-128 into master 2026-06-18 15:30:32 +02:00
80a69025eb Merge pull request 'perf(ui): LRU-evict the shaped-run cache instead of clearing it (#123)' (#143) from claude/issue-123 into master 2026-06-18 15:30:08 +02:00
catbot
a45e793da4 perf(ui): memoize the input-field caret prefix width (#128)
DrawInputField re-measured the cursor prefix via Font::GetLineWidth on
every frame of a focused field, even though only the blink (caretVisible)
changes frame-to-frame — value, cursorPos and fontSize are stable across
the vast majority of frames.

Cache the measured prefix WIDTH on the InputField, keyed on (prefix bytes,
fontSize). A cheap byte compare of the cached prefix guards the expensive
per-glyph UTF-8 decode + advance accumulation. The cache is mutable so the
const-ref draw fn can refresh it.

The absolute caretX is deliberately NOT cached: it adds the layout-
dependent textX (rect.x + paddingX) each frame, so caching it would give a
relocated field a stale caret. Caching the width keeps that correct.

Adds tests/InputFieldCaretCache pinning: the cached caret matches the
uncached GetLineWidth oracle across states, a redraw (cache hit) is
identical to the miss, the cache invalidates on value/cursorPos/fontSize
changes, the blink never moves the caret, and a relocated field shifts the
caret by exactly the rect delta.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:29:55 +00:00
catbot
88541bf44e Merge remote-tracking branch 'origin/master' into claude/issue-123
# Conflicts:
#	implementations/Crafter.Graphics-UI-Shared.cpp
#	interfaces/Crafter.Graphics-UI.cppm
2026-06-18 13:29:49 +00:00
9046562a90 Merge pull request 'perf(ui): subgroup prefix-sum stream compaction in the UI compute shaders (#124)' (#145) from claude/issue-124 into master 2026-06-18 15:27:30 +02:00
e1222c0ab7 Merge pull request 'perf(ui): skip the destination read-modify-write on empty tiles (#127)' (#144) from claude/issue-127 into master 2026-06-18 15:27:08 +02:00
catbot
da9f2a89e8 perf(ui): subgroup prefix-sum stream compaction, not lane-0 serial scan (#124)
uiCompactChunk ran the survivor scan entirely on gl_LocalInvocationIndex
== 0: ~64 serial iterations with 63/64 lanes idle, between two barriers,
4x per chunk in the fused kernel. It must emit a stable in-order
(buffer-order) exclusive prefix of the survivors so the per-pixel inner
loop still sees items in draw order.

Replace it with a per-subgroup subgroupExclusiveAdd of the keep bits plus
a carry across subgroups: each subgroup publishes its survivor total to
shared memory, then every lane sums the totals of all lower-id subgroups
for its base. A survivor's slot in s_order[] therefore equals the number
of survivors with a smaller local index — buffer (draw) order preserved
exactly, unlike an atomicAdd which would scramble it.

The carry makes the result correct for any subgroup width (2 subgroups on
the 32-wide descriptor_heap target, up to 8/16 on narrower parts), relying
only on the gl_LocalInvocationIndex <-> (gl_SubgroupID,
gl_SubgroupInvocationID) linear mapping every Vulkan compute
implementation provides. The feature is free at the device baseline
(apiVersion 1.4 + VK_EXT_descriptor_heap implies Vulkan 1.1 subgroup
arithmetic), so no correctness fallback is needed; WebGPU is unaffected
(separate embedded WGSL).

Applied to ui-fused.comp.glsl and the same pattern inlined in
ui-quads/circles/images/text.

Verified: all 23 tests pass (UIFusedShader recompiles + spirv-val +
pins push-constant offsets); a 140k-trial CPU simulation of the algorithm
matches the serial reference for subgroup sizes 1..64; HelloUI renders
correctly on an RTX 4090 (DispatchFused quads+circles+text) with draw
order intact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:26:37 +00:00
catbot
225556532a perf(ui): skip the destination read-modify-write on empty tiles (#127)
The standalone per-category UI shaders (quads/circles/images/text)
unconditionally imageLoad the destination pixel up front and imageStore
it at the end, paying a full read-modify-write even on tiles no item
touches — the common case for a sparse UI. The fused uber-kernel already
amortizes a single load/store across all four categories; the standalone
Dispatch* path has no such umbrella.

Defer the imageLoad to just before the first surviving blend (`loaded`
flag) and skip the imageStore unless something was actually blended.
Output is bit-identical: before the first blend `dst` is unused, and a
skipped store leaves the pixel exactly as a no-op load+store would have
rewritten it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:26:32 +00:00
catbot
1d7d9f7b8e perf(ui): LRU-evict the shaped-run cache instead of clearing it (#123)
At kMaxShapedRuns (8192) UIRenderer::ShapeText did a full shapedRuns_.clear().
A stream of unique strings (FPS counters, timers) alongside many stable labels
periodically nuked every stable entry, forcing a full-UI reshape the next frame.

Track recency with an auxiliary std::list<const ShapedRunKey*> (front = most
recently used) holding pointers to the keys owned by the node-based map. A hit
splices its entry to the front; an overflow pops the least-recently-used entry
from the back and erases just that one — both O(1). The hot set of labels,
reshaped every frame, stays at the front and survives, so the churn of unique
strings only recycles the cold tail. Output is byte-identical either way.

InvalidateFont now drops matching entries from both the map and the LRU list.
Adds ShapedRunCacheSize()/IsShapedRunCached() introspection hooks (the policy
isn't observable through output or atlas.dirty) and a ShapeTextCache test that
asserts the cache plateaus at a fixed cap (evict-one, not clear-all), the hot
label survives a churn past the cap, and an untouched cold string is evicted.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:23:34 +00:00
2c07abee00 Merge pull request 'perf(ui): hoist loop-invariant per-item/per-glyph math out of the per-pixel loop (#125)' (#142) from claude/issue-125 into master 2026-06-18 15:22:45 +02:00
catbot
ac9180076c perf(ui): hoist loop-invariant per-item math out of the per-pixel loop (#125)
The cooperative-load section already streams each item into shared memory
once per workgroup, but the per-pixel inner loop then recomputed values
that are constant for the whole item/glyph. The compiler can't hoist them
itself — they read shared memory at a varying index.

Precompute them once per item at load time into new shared slots:

  - ui-images / ui-text / ui-fused (images+text phases): invRectSize =
    1.0/rect.zw, turning the per-pixel `(sp-rect.xy)/rect.zw` vec2 divide
    into a multiply.
  - ui-text / ui-fused (text phase): the SDF AA `band` (a vec2 divide +
    two maxes depending only on the glyph's uv span and rect size).

In ui-fused the new slots (s_inv, s_band) are reused across phases like
the existing s_v* scratch, so the LDS bump is per-category, not summed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:22:07 +00:00
1b57f84348 Merge pull request 'perf(ui): transparent shaped-run cache lookup, no string copy on hit (#122)' (#141) from claude/issue-122 into master 2026-06-18 15:19:43 +02:00
catbot
c8495f548b perf(ui): transparent shaped-run cache lookup, no string copy on hit (#122)
ShapeText built ShapedRunKey{..., std::string(utf8)} before find()
unconditionally — even on cache hits, on the per-frame onBuild path.
N labels meant N string copies + hashes (+ frees for non-SSO strings)
every frame, partially defeating the run cache.

Add is_transparent hash + equality functors on shapedRuns_ and probe
with a borrowing ShapedRunViewKey {const Font*, float, array<float,4>,
string_view}. The owning std::string is now materialised only on a
miss, for emplace. Cache hits copy and hash no string.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:19:11 +00:00
2783e47674 Merge pull request 'perf(tlas): dirty-track the per-frame TLAS instance+metadata upload (#118)' (#140) from claude/issue-118 into master 2026-06-18 15:07:44 +02:00
catbot
b5b8c04237 perf(tlas): dirty-track the per-frame TLAS instance+metadata upload (#118)
BuildTLAS rebuilt the host instance+metadata buffers with an O(n) copy of
every 64 B VkAccelerationStructureInstanceKHR + metadata entry every frame,
unconditionally, then flushed the whole high-water capacity (VK_WHOLE_SIZE)
on both buffers. At the millions-of-instances target that copy dominates the
CPU frame, and the whole-buffer flush costs on non-coherent BAR/VRAM.

Add a generation counter so only changed host-authored fields are copied, and
feed the same dirty span into the ranged FlushDevice(offset, bytes) overload:

- RenderingElement3D::hostDataVersion + MarkHostDataDirty() (bumps a global
  monotonic counter). TlasWithBuffer::uploadedVersion records, per frame, the
  version last copied into each slot. A slot is copied only when its element
  advanced past the recorded version; version 0 ("untracked") reads dirty every
  frame, so callers that don't opt in keep the prior copy-every-frame behaviour.
  Globally-unique versions make this correct under relocation (Remove's
  swap-and-pop, and remove+add that nets the same count on the refit path)
  without tracking element identity. The reset on every topology change covers
  buffer reallocation and the reshuffled element->slot mapping.
- The dirty [first, last] envelope drives both the copy and the flush: a new
  VulkanBuffer::FlushDevice(cmd, access, stage, offset, bytes) overload flushes
  + barriers just that span for instanceBuffer, and the ranged
  FlushDevice(offset, bytes) for metadataBuffer. When nothing is dirty both are
  skipped — the skipped HOST->build barrier only ever ordered host writes, never
  the application's compute-written GPU-owned transform (that compute->build
  ordering is the caller's, and is unchanged).

Constraint honoured: transformOwnedByGpu transforms are still never host-copied.
The API field/method are mirrored on the WebGPU class for source portability
(the WebGPU build re-uploads its small mirror wholesale and ignores the version).

New test TLASInstanceDirtyTracking drives the real RT device and reads back the
host-mapped buffers to assert: tracked elements upload once then skip until
re-marked, untracked elements always upload, and relocation on the refit path
re-uploads exactly the moved slots — with zero validation-layer errors over the
ranged flush.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:58:45 +00:00
5a9d909f5d Merge pull request 'perf(buffer): reuse staging via a per-frame-in-flight ring in UploadDeviceLocal (#120)' (#139) from claude/issue-120 into master 2026-06-17 21:52:03 +02:00
catbot
85ca08047d perf(buffer): reuse staging via a per-frame-in-flight ring in UploadDeviceLocal (#120)
The staged branch of VulkanBuffer::UploadDeviceLocal did a full
Create (create+getreq+alloc+map) + DeferredClear (later free) per call.
Mesh::Refit / RecordProceduralBuild hit this every frame for deforming
meshes on no-/small-BAR hardware — a device-memory alloc/free cycle per
mesh per frame, on exactly the hardware the staged path targets.

Replace it with a persistent per-buffer staging ring sized to a
high-water mark, reallocated (via Resize, which defers the outgrown
allocation) only on growth — mirroring the TLAS instance/metadata reuse.

The ring is a per-frame-in-flight ring, not a single shared buffer: the
vkCmdCopyBuffer still reads staging after the call returns, and with
frames pipelined framesInFlight deep, overwriting one shared buffer next
frame would clobber data the previous frame's copy is still reading.
Indexing by frameCounter % framesInFlight gives each in-flight frame its
own slot, reused only after framesInFlight frames elapse — the same
window the #101 deletion queue relies on for GPU completion.

The ring is grown lazily, on first entry into the staged branch, so
ReBAR/UMA hardware (which always takes the direct-write branch) never
constructs a staging allocation it does not use — keeping this a runtime
no-op there and a straight upgrade on non-resizable-BAR machines.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:51:33 +00:00
e3edb87c0f Merge pull request 'perf(mesh): dirty-range vertex upload for deforming-mesh Refit (#119)' (#138) from claude/issue-119 into master 2026-06-17 21:51:26 +02:00
catbot
1f4c77000a perf(mesh): dirty-range vertex upload for deforming-mesh Refit (#119)
Mesh::Refit re-uploaded the entire vertex array every frame on the
in-place UPDATE path (full host write + flush + barrier on the direct
path; full re-stage + copy on the staged path), even when only a handful
of vertices moved.

Add VulkanBuffer::UploadDeviceLocalRange — a dirty-range counterpart to
UploadDeviceLocal that writes/flushes/stages/copies and barriers only the
half-open element range [offset, offset+count) of an already-allocated
device-local buffer. It picks direct-map vs staged-copy from the memory
type the buffer was actually allocated with (not the sub-range size, which
PreferDirectDeviceWrite would mis-route), and the direct path's ranged
flush is rounded to nonCoherentAtomSize and clamped to the allocation size
(mappedSize is now recorded for every buffer, not just mapped ones).

Add a dirty-range Refit overload taking the full vertex/index arrays plus
a (dirtyVertexOffset, dirtyVertexCount) window. The full-span Refit now
delegates to it with the whole array as the window. On the in-place UPDATE
path only the declared window is uploaded — the rest of the device buffer
retains last refit's positions; when an UPDATE isn't possible it falls
back to the full-span rebuild, which is why the full arrays are still
passed. The WebGPU/DOM backend keeps API symmetry: it has no hardware AS,
so it ignores the window and rebuilds the host BVH from the full geometry.

BLASBuildOptions exercises the dirty-range refit on the direct path, the
staged path, and the count-change rebuild fallback, asserting AS-handle /
blasAddr stability and zero Vulkan validation errors.

Resolves #119

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:50:48 +00:00
82fd6916d9 Merge pull request 'perf(sync): scope frame-loop barriers to swapchain image + real per-pass stages (#115)' (#137) from claude/issue-115 into master 2026-06-17 21:45:13 +02:00
catbot
9414863cff perf(sync): scope frame-loop barriers to swapchain image + real per-pass stages (#115)
The inter-pass and acquire/present barriers in the frame loop set both
stage masks to ALL_COMMANDS, and the inter-pass dependency used a
queue-wide VkMemoryBarrier — fully serialising against every pipeline
stage and flushing all caches every frame, when all the next pass needs
is the swapchain image the previous one wrote.

Replace the inter-pass global VkMemoryBarrier with an image memory
barrier scoped to the swapchain image's single colour subresource (as
the intra-pass UI barrier already does), and derive the barrier stage
masks per pass: RenderPass::SwapchainStage() is overridden by UIRenderer
(COMPUTE_SHADER) and RTPass (RAY_TRACING_SHADER), so a compute->compute
edge only serialises COMPUTE while an RT pass pulls in RAY_TRACING — the
acquire/present frame-edge masks use the real union of the frame's
passes (SwapchainStageUnion). The base default and the empty-passes
fallback are the conservative COMPUTE | RAY_TRACING | TRANSFER union, so
a polymorphic or un-overridden pass can only be over- not
under-synchronised.

Adds SwapchainBarrierScope (pure CPU) pinning the per-pass derivation,
the union narrowing, and the inter-pass barrier scope; FrameLoopSync
already drives the real GPU frame loop with validation enabled.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:44:33 +00:00
faf1e5f5e8 Merge pull request 'perf(image): release static texture staging after upload (#114)' (#136) from claude/issue-114 into master 2026-06-17 21:41:07 +02:00
catbot
b4fa6e596e perf(image): release static texture staging after upload (#114)
ImageVulkan kept its host-visible staging `buffer` (sized w*h, persistently
mapped) alive for the whole life of the image and Destroy() never freed it, so
static textures (e.g. Sponza albedo) pinned HOST_VISIBLE / small-BAR memory
forever.

Update now releases the staging via VulkanBuffer::DeferredClear() right after
recording the buffer→image copy — the same fence-keyed deletion queue
(#101/#102) the compressed Mesh path already uses — so it is freed once the
upload submit's frame has cleared. A new `streamed` flag (set by FontAtlas)
keeps the persistent map for images re-uploaded from a CPU-side staging buffer
every frame; its uploads go through UpdateRegion, which never releases. Destroy
now also frees any staging the image still owns, gated on a live handle so a
released static texture can't double-free.

Adds tests/ImageStagingRelease driving the real upload + readback on a headless
device: asserts the staging is enqueued (not pinned), the image reads back
byte-equal (released staging outlived the submit), the entry retires only after
framesInFlight frames, and a streamed image keeps then frees its staging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:40:35 +00:00
5948bb91c1 Merge pull request 'perf(device): pop retired deletions off the front in O(ready) (#116)' (#135) from claude/issue-116 into master 2026-06-17 21:38:28 +02:00
catbot
2460a66296 perf(device): pop retired deletions off the front in O(ready) (#116)
ReclaimDeletions ran an O(n) walk + survivor compaction over the whole
deletion queue every frame. frameCounter is monotonic, so retireAfter is
non-decreasing down the queue and the entries ready to reclaim are always
a contiguous prefix. Switch deletionQueue from std::vector to std::deque
and pop the ready prefix off the front, stopping at the first entry still
in flight — O(ready) instead of O(queue).

Resolves #116

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:37:58 +00:00
9d9f9d9d2c Merge pull request 'test(mesh): pin static-build deletion count for #67 staging-release (#110)' (#112) from claude/issue-110 into master 2026-06-17 20:51:18 +02:00
catbot
3655cd636c test(mesh): pin static-build deletion count in #67 staging-release test (#110)
Issue #110 reported `crafter-build test MeshDecompressStagingRelease` failing
deterministically on the GPU decompress path: the "exactly one allocation
handed to the deletion queue" assertion saw more than one entry.

Root cause (confirmed at Crafter.Graphics-Mesh.cpp:175-176): a static
(allowUpdate=false) Build cannot refit, so it DeferredClear()s its now-dead
per-mesh BLAS scratch in addition to the compressed staging (#67) — two
deferred allocations, not one. The original test built statically yet asserted
size==1, so the scratch was the unaccounted-for second entry. The behaviour
was already corrected on master by PR #109 (the #73 merge, ed9b3f6), which
switched the assertion's build to allowUpdate=true so the scratch is retained.

This hardens that fix: it adds a sibling case that Builds with allowUpdate=false
and asserts the queue holds exactly TWO entries (staging + dead scratch),
builds with zero validation errors, and that both retire on schedule. The count
the #67 assertion relies on is now a named, explicitly-tested quantity rather
than an implicit comment, so a future change to scratch deferral can't silently
shift it back.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 18:50:38 +00:00
8b1db01222 Merge pull request 'perf(mesh): place RT geometry device-local via #89 upload strategy (#73)' (#109) from claude/issue-73 into master 2026-06-17 20:05:57 +02:00
catbot
ed9b3f67a7 test+usage: device-local geometry readback + isolate #67 staging count
- Add TRANSFER_SRC to RT geometry usage so device-local geometry (now in
  VRAM, no longer host-mappable) stays copyable/inspectable.
- MeshDecompressStagingRelease: read decompressed vertex/index back via a
  device->host copy instead of the removed host-mapped .value/FlushHost, and
  build the mesh with allowUpdate=true so the retained per-mesh scratch (#66)
  doesn't also land in the deletion queue — isolating the assertion to the
  released compressed staging (#67).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 18:05:13 +00:00
catbot
aafa458d41 Merge remote-tracking branch 'origin/master' into claude/issue-73
# Conflicts:
#	interfaces/Crafter.Graphics-Mesh.cppm
2026-06-17 17:52:06 +00:00
1582b6ceb5 Merge pull request 'perf(rt): allocate TLAS metadata buffer in BAR/VRAM, not system RAM (#75)' (#111) from claude/issue-75 into master 2026-06-17 19:50:55 +02:00
catbot
801509d9d5 perf(rt): allocate TLAS metadata buffer in BAR/VRAM, not system RAM (#75)
The TLAS metadata buffer is CPU-written every frame (one userMetadata word
per element in BuildTLAS's copy loop) and read by the ray shaders as a
STORAGE_BUFFER via device address every frame. Allocated
HOST_VISIBLE | HOST_COHERENT (system RAM), every per-frame shader read
traversed PCIe — the same cost the sibling instance buffer paid before #65.

Upgrade the request to HOST_VISIBLE with a best-effort DEVICE_LOCAL preference
(BAR/VRAM), keeping the single persistently-mapped buffer. The CPU's writes are
write-only, sequential, never-read-back — the ideal write-combined BAR load —
and the shader reads now hit local VRAM.

Unlike the instance buffer there is no GPU co-write, so the direct upgrade is
unconditional. Staging is still deliberately avoided: this buffer is rewritten
by the CPU every frame, so a per-frame stage+copy+barrier would defeat the
purpose (#75 caveat 2).

Correctness:
- DEVICE_LOCAL is a preference only (depends on #59): GetMemoryType falls back
  to plain HOST_VISIBLE (the previous behaviour) on GPUs without resizable BAR.
- HOST_COHERENT is dropped from the required set — the combined type may not be
  coherent. A FlushDevice() is added after the copy loop to make the host writes
  available on a non-coherent type; it self-gates to a no-op on a coherent type
  (#60), so the previous behaviour is preserved wherever the type ends up
  coherent. The metadata buffer is not an AS build input and has no GPU
  co-write, so it needs neither the build-stage barrier the instance buffer
  takes nor a HOST->shader command barrier: the queue submit already orders host
  writes made available before it against every command in the submission,
  exactly as it did when this buffer was HOST_COHERENT.

Extends the TLASHighWaterMark hardware test with a metadata-buffer assertion
block mirroring #65's instance-buffer check: the chosen memory type must equal
what GetMemoryType resolves for the HOST_VISIBLE | prefer-DEVICE_LOCAL request,
and must be DEVICE_LOCAL wherever a host-visible device-local type is reachable.
The zero-validation-errors check covers the dropped HOST_COHERENT path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:50:01 +00:00
catbot
5f858509c8 perf(mesh): place RT geometry in device-local memory via #89 upload strategy (#73)
vertexBuffer/indexBuffer/aabbBuffer were HOST_VISIBLE (system RAM), so the
BLAS build, every refit, and any hit-shader geometry fetch read them over
PCIe. The usage flags (SHADER_DEVICE_ADDRESS, plus STORAGE on the index
buffer) exist precisely to expose geometry for hit-shader fetch, the dominant
RT shading pattern.

Add VulkanBuffer::UploadDeviceLocal, which places a CPU-written/GPU-read
buffer in device-local memory and picks the upload mechanism at runtime via
the #89 strategy (Device::PreferDirectDeviceWrite):
  - ReBAR/UMA: allocate HOST_VISIBLE|DEVICE_LOCAL (DEVICE_LOCAL preferred),
    map transiently, memcpy, flush-if-non-coherent. No staging buffer.
  - no/small BAR: allocate pure DEVICE_LOCAL + TRANSFER_DST, fill a transient
    HOST_VISIBLE staging buffer, vkCmdCopyBuffer, then DeferredClear the
    staging buffer onto the fence-keyed deletion queue (#101/#102) so it
    outlives the copy submit.

The geometry buffers become non-mapped so the destination is free to be
device-local-only. Same-size re-uploads reuse the allocation, so the device
address stays stable across an in-place AS UPDATE refit. The compressed Build
path now allocates vertex/index as pure DEVICE_LOCAL — the GPU decompressor
fills them directly, no host write.

Tests: BLASBuildOptions asserts device-local placement on the triangle,
procedural, and (budget-forced) staged paths, and exercises the staged copy +
deferred-deletion + in-place refit under GPU-assisted validation with zero
validation errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:49:25 +00:00
d77bd860ba Merge pull request 'perf(window): use HOST_CACHED readback staging in SaveFrame (#74)' (#108) from claude/issue-74 into master 2026-06-17 19:45:16 +02:00
catbot
1553f585a2 perf(window): use HOST_CACHED readback staging in SaveFrame (#74)
SaveFrame's readback staging buffer was allocated HOST_VISIBLE |
HOST_COHERENT, whose first matching type is write-combined (uncached) on
most discrete GPUs. The CPU then reads the entire frame back from it —
and reads from write-combined memory are pathologically slow.

Select a HOST_CACHED type instead (preferring a cached-coherent type
when one exists), falling back to any HOST_VISIBLE type if no cached type
is advertised (#59 mechanism). When the chosen type is cached-but-not-
coherent, invalidate the mapped range before the CPU read — the read-path
counterpart of FlushDevice (#60) — gated on the chosen type's actual
coherency, not the requested flags. Whole-range invalidate sidesteps
nonCoherentAtomSize.

Deliberately not routed through the #89 upload-strategy helper, which is
upload-only and steers toward write-combined DEVICE_LOCAL|HOST_VISIBLE —
the worst type for readback.

Verified by driving SaveFrame from the VulkanTriangle example: the
barycentric RGB triangle reads back with correct pixels and channel
order on an RTX 4090.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:44:37 +00:00
87264bb2ec Merge pull request 'perf(rt): place SBT in device-local memory via upload-strategy helper (#72)' (#107) from claude/issue-72 into master 2026-06-17 19:42:02 +02:00
catbot
b410f2d5aa perf(rt): place SBT in device-local memory via upload-strategy helper (#72)
The shader binding table is written once at pipeline creation and read by
the GPU on every vkCmdTraceRaysKHR thereafter, yet it was allocated plain
HOST_VISIBLE (system RAM) — so every trace dispatch read raygen/miss/hit
records over PCIe.

Route the SBT allocation through Device::PreferDirectDeviceWrite (#89):
when a DEVICE_LOCAL|HOST_VISIBLE type exists, prefer DEVICE_LOCAL on top
of the required HOST_VISIBLE so the buffer lands in mappable device
memory (GPU reads hit local VRAM; the one-time memcpy goes write-combined
over PCIe). When no combined type exists, the preferred hint is dropped
and GetMemoryType (#59) falls back to plain HOST_VISIBLE — current
behaviour. The SBT is tiny so a small BAR window's budget is never the
constraint.

The buffer stays mapped and the existing FlushDevice gates on the chosen
memory type's coherency flags (#60), so a direct-write type lacking
HOST_COHERENT is still flushed correctly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:41:34 +00:00
2c8a293b57 Merge pull request 'perf(decompress): release compressed staging after submit, not for the resource's life (#67)' (#106) from claude/issue-67 into master 2026-06-17 19:41:20 +02:00
catbot
b29b8f0371 test(decompress): cover compressed-staging release on the real GPU path
MeshDecompressStagingRelease drives the real VK_EXT_memory_decompression /
GDeflate path on a headless device and asserts the staging is handed to the
deferred-deletion queue (not pinned), the build is validation-clean with
byte-correct decompressed data, and the entry retires only after framesInFlight
frames. Skips the GPU-path assertions when the extension is absent (CPU fallback
never allocates the staging).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:40:39 +00:00
catbot
8a32f0d545 perf(decompress): release compressed staging after submit, not for the resource's life
The compressed Mesh::Build / ImageVulkan::Update paths kept their host-visible
`compressedStaging` (holding the GDeflate streams) alive for the whole life of
the mesh/image, pinning host-visible memory long after the single GPU decompress
that reads it has retired.

Release it via VulkanBuffer::DeferredClear() right after recording the decompress.
The recorded vkCmdDecompressMemoryEXT still references compressedStaging.address,
so it must outlive the submit — exactly what the fence-keyed deletion queue
(#101/#102) guarantees: it retires the allocation only after framesInFlight frames
have elapsed, by which point the submit's fence has cleared. Between Builds/Updates
the handle is null; the next call's Resize re-creates it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:40:39 +00:00
576a5eb717 Merge pull request 'perf(rt): allocate TLAS instance buffer in BAR/VRAM, not system RAM (#65)' (#105) from claude/issue-65 into master 2026-06-17 19:38:13 +02:00
catbot
d8bc8a4e45 perf(rt): allocate TLAS instance buffer in BAR/VRAM, not system RAM (#65)
The TLAS instance buffer is rebuilt/refit every frame and is co-written by
both the CPU (host-authored fields) and the GPU (the compute shader writes
the transform field in place for transformOwnedByGpu elements). Allocated
HOST_VISIBLE | HOST_COHERENT (system RAM), both GPU accesses crossed PCIe:
the compute write of the transform, and the AS build's read of the instances.

Upgrade the request to HOST_VISIBLE with a best-effort DEVICE_LOCAL preference
(BAR/VRAM), keeping the single shared, persistently-mapped buffer — no staging,
no copy, no extra barrier. A whole-buffer staging copy was rejected: it would
clobber the GPU-written transforms in this in-place co-write design. Now the
compute write and AS build stay in local VRAM; the CPU's write-only,
sequential, never-read-back field writes are the ideal write-combined BAR load.

Correctness:
- DEVICE_LOCAL is a preference only (depends on #59): GetMemoryType falls back
  to plain HOST_VISIBLE (the previous behaviour) on GPUs without resizable BAR.
- HOST_COHERENT is dropped from the required set — the combined type may not be
  coherent. The existing FlushDevice(cmd, ...) already establishes host->build
  visibility and gates its flush-skip on the *chosen* type's flags (#60), so a
  non-coherent BAR type still flushes correctly. The barrier is never removed.

metadataBuffer gets the same upgrade separately (#75).

Extends the TLASHighWaterMark hardware test to assert the chosen memory type
matches the HOST_VISIBLE | prefer-DEVICE_LOCAL request and lands on a
DEVICE_LOCAL type where one is reachable; the existing zero-validation-errors
check covers the dropped HOST_COHERENT path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:37:39 +00:00
39b882a9cb Merge pull request 'perf(mesh): release per-mesh scratch buffer for static BLAS (#66)' (#104) from claude/issue-66 into master 2026-06-17 19:36:44 +02:00
catbot
8b008b49d5 perf(mesh): release per-mesh scratch buffer for static BLAS (#66)
A static (!allowUpdate) mesh can never refit, so its per-mesh DEVICE_LOCAL
scratch buffer is dead weight the moment the build's GPU work completes —
yet it was kept alive for the mesh's whole lifetime. In many-mesh scenes
(where static meshes dominate) this is real, accumulating VRAM waste.

Release it via scratchBuffer.DeferredClear() right after recording a fresh
build for a static mesh. The old "free-after-build is a UAF, the GPU is
still building" hazard is gone: the fence-keyed deferred-deletion queue
(#101/#102) retires the allocation only once the build's frame has passed
its fence. A later Refit on a static mesh takes the rebuild fallback, whose
Resize sees the nulled handle and re-Creates the scratch. Refit-capable
(allowUpdate) meshes keep their scratch as before — an in-place UPDATE
reuses it each frame.

Extends the BLASBuildOptions hardware test to assert the scratch is retained
for allowUpdate meshes and released for static ones (including across a
static-mesh refit rebuild), with the validation layer confirming zero errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:36:10 +00:00
bafdd6b1e6 Merge pull request 'perf(mesh): skip immutable index re-upload on RT refit UPDATE (#68)' (#103) from claude/issue-68 into master 2026-06-17 19:34:57 +02:00
catbot
a55f15d332 perf(mesh): skip immutable index re-upload on RT refit UPDATE (#68)
A hardware acceleration-structure UPDATE cannot change topology, so the
index buffer is immutable on the Refit UPDATE path. Re-uploading it was a
wasted memcpy + FlushDevice + barrier of unchanged data every refit —
genuinely per-frame for deforming meshes.

Skip the index memcpy and its FlushDevice on the UPDATE branch; the
RecordBLASBuild call still reads the stable, unchanged indexBuffer.address.
The `indicies` span is now read only for its count. Document the API
nuance: a bitwise-different but topologically-equivalent index array is
ignored on refit, consistent with "a refit may only move vertex positions."
The full-rebuild fallback path still re-uploads both buffers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 17:34:29 +00:00
3e0a38fafb Merge pull request 'fix(device): fence-keyed deferred resource-deletion queue (#101)' (#102) from claude/issue-101 into master 2026-06-17 15:21:47 +02:00
catbot
cb012d7068 fix(device): fence-keyed deferred resource-deletion queue (#101)
Since #40 dropped the per-frame vkQueueWaitIdle, frames are pipelined:
a resource the CPU is done with may still be read by the GPU for up to
numFrames-1 more frames. VulkanBuffer::Resize's destroy-and-recreate
path was therefore a live use-after-free (#63), no longer masked by the
wait-idle.

Device gains a monotonic, frame-counter-keyed deletion queue:
EnqueueDeletion tags {buffer, memory} with the current frameCounter;
ReclaimDeletions (called per frame after the fence wait) frees entries
once framesInFlight frames have elapsed; DrainDeletions frees everything
after a wait-idle. VulkanBuffer::DeferredClear hands handles to the queue
and nulls the handle, and Resize uses it instead of immediate Clear().

Window::Render sets framesInFlight at init, reclaims after the per-image
fence wait, bumps Device::frameCounter once per frame, and drains on the
resize / OUT_OF_DATE wait-idle paths. The destructor keeps immediate
Clear() (callers destroying mid-flight remain responsible, unchanged).

Adds the DeferredDeletion test: drives the retire timing on a real
headless device with real buffers, stepping Device::frameCounter to pin
the exact reclaim frame, asserting validation stays silent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 13:21:12 +00:00
c3d7f52891 Merge pull request 'perf(ui): flush only the written descriptor range, not the whole heap (#61)' (#99) from claude/issue-61 into master 2026-06-16 20:56:46 +02:00
catbot
1f12f074b1 Merge remote-tracking branch 'origin/master' into claude/issue-61
# Conflicts:
#	interfaces/Crafter.Graphics-Device.cppm
#	interfaces/Crafter.Graphics-VulkanBuffer.cppm
#	project.cpp
2026-06-16 18:33:08 +00:00
e86facc2af Merge pull request 'perf(image): batch final mip-chain layout transition (#70)' (#100) from claude/issue-70 into master 2026-06-16 20:31:16 +02:00
catbot
518509aa0e perf(image): batch final mip-chain layout transition (#70)
The mip-generation upload path issued N+1 layout-transition barriers per
chain. The final blit's destination level is never read again, so its
dedicated TRANSFER_DST -> TRANSFER_SRC barrier was redundant: the level was
transitioned to SRC only to keep the final SRC -> consumer transition uniform.

Skip that last per-level barrier and fold the final level into the closing
transition, which now batches two VkImageMemoryBarrier entries
([0, mipLevels-1) from TRANSFER_SRC, the last level from TRANSFER_DST) into a
single vkCmdPipelineBarrier. One fewer barrier call per chain; the N-1
interleaved per-level barriers stay one-at-a-time since each is read by the
next blit. Applied to both the host-upload and GPU-decompress Update paths.

Adds the MipChainBarrierBatch regression test driving the pure barrier
builder (no GPU device needed).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:30:44 +00:00
catbot
6d7ad87e38 perf(ui): flush only the written descriptor range, not the whole heap (#61)
WriteBufferDescriptor / WriteSampledImageDescriptor / RegisterSampler /
WriteSwapchainDescriptors each FlushDevice()'d the entire multi-KB per-frame
descriptor heap after writing one few-byte descriptor. Add a ranged
VulkanBuffer::FlushDevice(offset, bytes) that flushes only the touched bytes,
rounding the range outward to nonCoherentAtomSize as vkFlushMappedMemoryRanges
requires (the WHOLE_SIZE path sidestepped that). The coherent-memory gate from
issue #60 is preserved — coherent memory still skips the flush entirely.

The descriptor writers now self-flush their written range, so the redundant
whole-heap flushes in UIRenderer::Initialize and the resize callback are gone.

Rounding lives in AlignMappedFlushRange (pure math) and is unit-tested without
a device in the new VulkanBufferRangedFlush test; the change was also verified
end-to-end by running HelloUI on a real GPU with validation layers (font-atlas
glyphs, sampler and storage-image descriptors all flush correctly, no VUIDs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:29:24 +00:00
00b84dd301 Merge pull request 'perf(rt): high-water-mark growth for TLAS host-input buffers (#64)' (#98) from claude/issue-64 into master 2026-06-16 20:24:48 +02:00
catbot
8e6ba49743 perf(rt): high-water-mark growth for TLAS host-input buffers (#64)
BuildTLAS reallocated the host-visible instanceBuffer and metadataBuffer
on every topology change. They only ever need to hold at least
primitiveCount entries (the AS build reads exactly primitiveCount via
tlasRangeInfo, and the copy loop writes [0, primitiveCount)), so a
shrink — or any growth that still fits the previous capacity — can reuse
the existing allocation. Gate the two Resize calls on a high-water-mark
check, removing two of the four reallocations on a count change. The AS
storage + scratch rebuild below is unchanged: it is tied to the AS
itself and dominates this path regardless.

Adds tests/TLASHighWaterMark driving the real hardware AS-build path: it
asserts a shrink (and within-capacity growth) reuses the buffers while a
growth past the high-water reallocates, that builtInstanceCount still
tracks the live count, and that feeding an oversized instance buffer to
the build produces zero Vulkan validation errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:24:09 +00:00
bd8076769a Merge pull request 'perf(pipeline): shared, disk-persisted VkPipelineCache (#69)' (#97) from claude/issue-69 into master 2026-06-16 20:24:03 +02:00
catbot
a728482731 test(pipeline): cover pipeline-cache header validation (#69)
PipelineCacheValidation drives Device::PipelineCacheDataCompatible
directly (no GPU): synthetic device identities + 32-byte cache headers
assert that a matching header is accepted while foreign vendor/device,
a bumped UUID (driver update), unknown version, undersized headerSize,
and short/empty blobs are all rejected. Mirrors the GPU-free style of
MemoryTypeFallback / UploadStrategy. Also gitignore the serialized
pipeline_cache.bin a real-device test run drops in the working dir.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:23:25 +00:00
catbot
a3a6dd2006 perf(pipeline): shared, disk-persisted VkPipelineCache (#69)
vkCreateComputePipelines and vkCreateRayTracingPipelinesKHR were passed
VK_NULL_HANDLE, so the driver couldn't reuse compiled shader binaries
across the pipelines built at startup (4 UI shaders + user/RT pipelines)
or across runs.

Add one process-wide Device::pipelineCache. LoadPipelineCache (called
from Initialize) seeds it from pipeline_cache.bin when the file's
VkPipelineCacheHeaderVersionOne header matches this device's
vendorID / deviceID / pipelineCacheUUID; a stale or foreign blob is
discarded so the driver never rejects it. SavePipelineCache is registered
with std::atexit, serialising the cache at process shutdown without any
explicit teardown hook. Both create sites now pass the cache; a null
handle stays valid, so no create-site null check is needed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:23:25 +00:00
b7500e1fd0 Merge pull request 'perf(buffer): capacity-reuse in VulkanBuffer::Resize (#63)' (#96) from claude/issue-63 into master 2026-06-16 20:22:38 +02:00
catbot
b6d0ec5cae perf(buffer): capacity-reuse in VulkanBuffer::Resize (#63)
Resize previously always destroyed + reallocated. It now reuses the
existing allocation in place when the new request still fits the created
capacity and the immutable-at-create properties match: usage flags are
fixed at create, and the chosen memory type must still satisfy the
required property flags. preferredPropertyFlags is a best-effort perf
hint and is intentionally not part of the guard. On reuse the buffer
handle, device address and mapped pointer are preserved; only `size`
shrinks to the new logical extent.

Tracks capacity and the created usage flags on VulkanBufferBase, set at
Create and carried through the move constructor.

Adds VulkanBufferResizeReuse, a device-free regression test that drives
the reuse guard directly and asserts the in-place path issues no Vulkan
call.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 18:22:09 +00:00
ab222ffa1f cache directwrite 2026-06-16 20:10:23 +02:00
69641f1c44 Merge pull request 'feat(device): runtime upload-strategy helper PreferDirectDeviceWrite (#89)' (#95) from claude/issue-89 into master 2026-06-16 19:23:59 +02:00
catbot
cfbe181d9e feat(device): runtime upload-strategy helper PreferDirectDeviceWrite (#89)
Add Device::PreferDirectDeviceWrite(size) so the memory-placement cluster
(#65/#72/#73/#75) no longer re-derives where a CPU-written, GPU-read buffer
should live. It picks the strategy at runtime from Device::memoryProperties:

  - No DEVICE_LOCAL|HOST_VISIBLE type (no resizable BAR) -> false (must stage).
  - ReBAR/UMA (BAR heap >= 90% of largest DEVICE_LOCAL heap) -> true: map and
    write directly; a staging copy would be pure overhead.
  - Small BAR window (BAR heap << VRAM) -> true only for buffers within a
    per-window budget (1/8 of the window); large buffers stage so they don't
    exhaust the window (#58).

Complements GetMemoryType (#59): #59 picks the memory *type*, this picks the
*strategy*. Upload-only — readback (#74) wants HOST_CACHED and stays separate.
A VK_EXT_memory_budget-driven remaining-space check is noted as a follow-up.

Tested by tests/UploadStrategy (pure CPU over synthetic ReBAR / UMA /
small-window / no-BAR layouts, no GPU device needed), mirroring
MemoryTypeFallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 17:23:27 +00:00
a19c2934c8 Merge pull request 'perf(ui): additive DispatchFused to collapse consecutive UI passes (#47)' (#93) from claude/issue-47 into master 2026-06-16 19:12:21 +02:00
catbot
c670bc70b7 Merge remote-tracking branch 'origin/master' into claude/issue-47
# Conflicts:
#	project.cpp
2026-06-16 17:10:39 +00:00
catbot
e8f1c7cff9 Merge remote-tracking branch 'origin/master' into claude/issue-47
# Conflicts:
#	interfaces/Crafter.Graphics-UI.cppm
#	project.cpp
2026-06-16 17:09:06 +00:00
df51a81db4 Merge pull request 'perf(vulkan-buffer): skip flush/invalidate on coherent memory (#60)' (#94) from claude/issue-60 into master 2026-06-16 19:07:43 +02:00
catbot
bdbe3bf568 Merge remote-tracking branch 'origin/master' into claude/issue-60
# Conflicts:
#	project.cpp
2026-06-16 17:07:32 +00:00
bda21979fd perf(vulkan-buffer): skip flush/invalidate on coherent memory (#60)
FlushDevice/FlushHost called vkFlushMappedMemoryRanges /
vkInvalidateMappedMemoryRanges unconditionally. Record the chosen
memory type's propertyFlags at Create time (via the index GetMemoryType
returns, not the requested flags) and early-return when HOST_COHERENT.

The cmd overload still always emits its pipeline barrier — only the
redundant host-side flush/invalidate is gated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 17:04:26 +00:00
f07bbc20f1 Merge pull request 'perf(font): cache per-codepoint advances in font units (#57)' (#92) from claude/issue-57 into master 2026-06-16 19:04:09 +02:00
catbot
574242dd30 perf(ui): add additive DispatchFused to collapse consecutive UI passes (#47)
Add a fifth UI compute path — DispatchFused — alongside the four
per-element Dispatch* calls. It composites quads → circles → images →
text (canonical back-to-front order) in ONE dispatch that loads the
destination image once and stores once, eliminating the per-pass
load+store and the inter-pass VkMemoryBarriers a run of consecutive
Dispatch* calls would pay. The win materialises at >= 2 non-empty
categories; an absent category is a zero-trip, push-constant-uniform
loop (~free).

The new uber-kernel (shaders/ui-fused.comp.glsl) reuses each category's
exact cooperative shared-memory tile-cull + per-pixel accumulate, so a
fused category is pixel-identical to its standalone pass. Categories run
sequentially per thread and share one set of shared-memory scratch, so
the VGPR/shared high-water mark stays at the per-category level, not the
sum.

Additive and non-breaking: the per-element Dispatch* calls and the
frozen 48-byte UIDispatchHeader are untouched. DispatchFused gets its own
128-byte push-constant layout (UIFusedHeader: four uvec4 headers + four
per-category clip vec4s). To interleave a custom ui.Dispatch() between
standard passes, bracket it with two DispatchFused calls — the dispatch
boundary is the explicit, app-declared flush point.

WebGPU (Vulkan-second): DispatchFused falls back to the per-element
Dispatch* calls in canonical order — one texture/sampler per dispatch
there can't feed the bindless image phase — so the result matches; only
the load/store fusion is Vulkan-only.

HelloUI now composites its background quads, mouse circle, and label
text in a single DispatchFused. Verified rendering identical on a live
Vulkan/Wayland session.

Resolves #47

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 17:03:24 +00:00
catbot
ce1eaf6366 Merge remote-tracking branch 'origin/master' into claude/issue-57
# Conflicts:
#	project.cpp
2026-06-16 17:02:48 +00:00
catbot
c169986835 perf(font): cache per-codepoint advances in font units (#57)
Font::GetLineWidth called stbtt_GetCodepointHMetrics for every glyph on
every invocation. InputField_HitTestCursor rescans the whole field once
per character, making caret hit-testing O(n²) in HMetrics lookups.

Memoise advances per Font via Font::AdvanceUnits: ASCII in a flat array,
the rest in a map. Advances are cached in unscaled font *units* and
rescaled per call — Glyph::advance in the FontAtlas is baked at kBaseSize
and is wrong at any other size, so it cannot be reused. The per-glyph
(int) truncation in GetLineWidth is preserved exactly.

Adds the FontAdvanceCache CPU-only regression test covering size
independence of the cached unit advance, the per-glyph-truncated rescale
pipeline, cache-hit determinism, width scaling with size, and the
non-ASCII map path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 17:00:48 +00:00
508f119cc6 Merge pull request 'perf(ui): gate per-pixel clip compares behind a flags bit (#50)' (#91) from claude/issue-50 into master 2026-06-16 18:59:48 +02:00
catbot
f2f5a770c0 Merge remote-tracking branch 'origin/master' into claude/issue-50
# Conflicts:
#	project.cpp
2026-06-16 16:59:05 +00:00
catbot
65c19ea84a perf(ui): gate per-pixel clip compares behind a flags bit (#50)
uiResolveScreenPixel ran four float compares against hdr.clipRectPx for
every pixel of every UI dispatch, even though the clip rect is the
full-surface default {0,0,1e9,1e9} in the overwhelmingly common case.

Reserve the high bit of the header flags word (UI_FLAG_CLIP) and have
FillHeader set it only when the clip rect is narrower than the surface
(extracted into the unit-testable UIRenderer::ClipFlags). The shader
gates the compares on the bit; the branch is push-constant-uniform so it
never diverges. When the rect covers the surface the skipped compares
could never reject an in-surface pixel, so output is pixel-identical.

Mirrored on the WebGPU/WGSL path (dom-webgpu.js) for parity. Adds the
UIClipFlag CPU test covering the gate decision.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 16:57:07 +00:00
185 changed files with 8134 additions and 1371 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
build/
bin/
pipeline_cache.bin

160
LICENSE
View file

@ -1,65 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

674
LICENSE.GPL Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -222,4 +222,13 @@ See [examples/](examples/). Quick map:
## License
LGPL 3.0. See per-file headers and `LICENSE`.
This library is licensed under the GNU Lesser General Public License, version 3 only (LGPL-3.0-only). See [LICENSE](LICENSE) for the license text. The LGPL supplements the GNU General Public License version 3, a copy of which is included as [LICENSE.GPL](LICENSE.GPL).
The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects.
The [lib/](lib/) directory contains vendored third-party code (stb, Wayland protocol bindings) that remains under its own permissive licenses; see the headers of those files.
## Copyright
Copyright (C) 2026 Catcrafts®
catcrafts.net

View file

@ -1,21 +1,5 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// JS bridge for the CRAFTER_GRAPHICS_WINDOW_DOM build of Crafter.Graphics.
// Populates `window.crafter_webbuild_env` (same global as Crafter.CppDOM

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter.Graphics WebGPU bridge DOM mode UI compute pipeline.
@ -54,6 +57,7 @@ function stub(name) {
"wgpuRegisterMeshBLAS", "wgpuRegisterMeshBLASDeviceAabbs", "wgpuRefitMeshBLASDeviceAabbs",
"wgpuLoadRTPipeline", "wgpuDispatchRT", "wgpuBuildTLAS",
"wgpuLoadComputePipeline", "wgpuDispatchCompute",
"wgpuSetCanvasMount",
]) {
// Read-write ints don't need a stub-throw; return 0 for the size queries.
e[n] = n.endsWith("Width") || n.endsWith("Height")
@ -85,6 +89,11 @@ canvas.style.cssText = "position:fixed;inset:0;width:100vw;height:100vh;display:
document.body.style.margin = "0";
document.body.appendChild(canvas);
// Optional mount target set via wgpuSetCanvasMount() (below). When null the
// canvas is a full-viewport fixed layer (the original, unchanged default);
// when set, the canvas is reparented into that element and sized to it.
let mountEl = null;
function syncCanvasSize() {
// Canvas pixel size = CSS size × devicePixelRatio so the GPU draws
// at physical pixel resolution on HiDPI displays — otherwise the
@ -98,8 +107,18 @@ function syncCanvasSize() {
// share the physical-pixel coordinate space with window.width/.height.
const dpr = window.devicePixelRatio || 1;
window.crafter_dpr = dpr;
const w = Math.max(1, Math.round(window.innerWidth * dpr));
const h = Math.max(1, Math.round(window.innerHeight * dpr));
// Mounted → track the host element's box; unmounted → the viewport.
let cssW, cssH;
if (mountEl) {
const r = mountEl.getBoundingClientRect();
cssW = r.width;
cssH = r.height;
} else {
cssW = window.innerWidth;
cssH = window.innerHeight;
}
const w = Math.max(1, Math.round(cssW * dpr));
const h = Math.max(1, Math.round(cssH * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
return { w, h };
@ -256,12 +275,17 @@ struct UIDispatchHeader {
@group(1) @binding(0) var outTex : texture_storage_2d<rgba8unorm, write>;
@group(1) @binding(1) var prevTex : texture_2d<f32>;
// Renderer-reserved high flag bit (mirrors ui-shared.glsl::UI_FLAG_CLIP).
const UI_FLAG_CLIP : u32 = 0x80000000u;
fn uiResolvePixel(coord: vec2<u32>) -> bool {
if (coord.x >= hdr.surfaceW || coord.y >= hdr.surfaceH) { return false; }
if ((hdr.flags & UI_FLAG_CLIP) != 0u) {
let fx = f32(coord.x); let fy = f32(coord.y);
if (fx < hdr.clipX || fy < hdr.clipY) { return false; }
if (fx >= hdr.clipX + hdr.clipW) { return false; }
if (fy >= hdr.clipY + hdr.clipH) { return false; }
}
return true;
}
@ -561,6 +585,40 @@ const env = window.crafter_webbuild_env;
env.wgpuGetCanvasWidth = () => canvas.width;
env.wgpuGetCanvasHeight = () => canvas.height;
// Reparent the render canvas into a host DOM element so a Crafter.Graphics
// scene can render inline inside an app's own layout instead of as a
// full-page layer. `idPtr`/`idLen` is a UTF-8 wasm string:
// - non-empty id of an existing element → move the canvas into it,
// position it to fill it (absolute inset:0), and size the render
// surface to that element's box (syncCanvasSize picks it up per frame).
// - empty string → detach back to <body> and hide it (display:none), so
// the host page is a plain DOM document again.
// The element is made position:relative if it is otherwise static, so the
// absolutely-positioned canvas anchors to it. Pointer events pass through
// (the inline use cases are non-interactive display surfaces).
env.wgpuSetCanvasMount = (idPtr, idLen) => {
const id = idLen > 0
? new TextDecoder().decode(memU8().subarray(idPtr, idPtr + idLen))
: "";
if (!id) {
mountEl = null;
if (canvas.parentNode !== document.body) document.body.appendChild(canvas);
canvas.style.cssText = "position:fixed;inset:0;width:100vw;height:100vh;display:none;";
return;
}
const el = document.getElementById(id);
if (!el) {
console.warn(`[crafter-wgpu] wgpuSetCanvasMount: no element #${id}`);
return;
}
mountEl = el;
if (getComputedStyle(el).position === "static") el.style.position = "relative";
if (canvas.parentNode !== el) el.appendChild(canvas);
canvas.style.cssText =
"position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;";
ensureSized();
};
env.wgpuCreateBuffer = (byteSize) => {
const h = newHandle();
const buf = device.createBuffer({
@ -608,7 +666,7 @@ env.wgpuWriteBufferRange = (handle, dstByteOffset, srcPtr, byteSize) => {
const READBACK_IDLE = 0;
const READBACK_PENDING = 1;
const READBACK_READY = 2;
const readbacks = new Map(); // device-buffer handle → { staging, size, state, pendingData }
const readbacks = new Map(); // device-buffer handle → { staging, capacity, readBytes, state, pendingData }
// Readbacks scheduled this frame that still need their mapAsync kicked
// off — done after the frame's queue.submit so the map waits for the
// compute writes that wrote to `buf` to finish, not just the standalone
@ -618,21 +676,30 @@ const pendingReadbackMaps = [];
env.wgpuReadbackEnqueue = (handle, byteSize, resetBytes) => {
const buf = buffers.get(handle);
if (!buf) return;
const aligned = (byteSize + 3) & ~3;
const resetAligned = resetBytes > 0 ? ((resetBytes + 3) & ~3) : 0;
let rb = readbacks.get(handle);
if (!rb) {
// Size the staging buffer to the FULL device-buffer capacity, not
// this first call's byteSize: a prefix readback (byteCount < size)
// is allowed to vary call-to-call, so the staging must cover any
// later full-size drain without re-allocating.
const capacity = Math.max(16, (buf.size + 3) & ~3);
rb = {
staging: device.createBuffer({
size: Math.max(16, aligned),
size: capacity,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
}),
size: aligned,
capacity,
readBytes: 0, // bytes copied/mapped by the in-flight enqueue
state: READBACK_IDLE,
pendingData: null,
};
readbacks.set(handle, rb);
}
// Copy/map only the requested prefix — that's the whole point of the
// byteCount path: skip the over-provisioned tail GPU→staging→wasm.
const aligned = Math.min((byteSize + 3) & ~3, rb.capacity);
rb.readBytes = aligned;
if (rb.state !== READBACK_IDLE) {
// Previous map still in flight (or has data nobody polled yet);
// skip this enqueue AND the paired reset. Events written by the
@ -676,8 +743,9 @@ env.wgpuReadbackEnqueue = (handle, byteSize, resetBytes) => {
if (resetAligned > 0) enc.clearBuffer(buf, 0, resetAligned);
queue.submit([enc.finish()]);
rb.state = READBACK_PENDING;
rb.staging.mapAsync(GPUMapMode.READ).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange()).slice();
const mapBytes = rb.readBytes;
rb.staging.mapAsync(GPUMapMode.READ, 0, mapBytes).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange(0, mapBytes)).slice();
rb.staging.unmap();
rb.state = READBACK_READY;
}).catch(e => {
@ -1005,8 +1073,9 @@ env.wgpuFrameEnd = () => {
// writes (not pre-substep state).
while (pendingReadbackMaps.length > 0) {
const rb = pendingReadbackMaps.pop();
rb.staging.mapAsync(GPUMapMode.READ).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange()).slice();
const mapBytes = rb.readBytes;
rb.staging.mapAsync(GPUMapMode.READ, 0, mapBytes).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange(0, mapBytes)).slice();
rb.staging.unmap();
rb.state = READBACK_READY;
}).catch(e => {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Custom UI compute shader. Demonstrates the Tier 1 dispatch path:
// the user defines their own item struct, writes their own GLSL alongside
// the standard shaders (sharing the same UIDispatchHeader contract via

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// DOM-mode port of inverse-circle.comp.glsl. Inverts RGB inside each
// user-supplied circle; passes through every other pixel so the
// ping-pong carries the prior dispatch's scene forward.

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Tier 1 demo: a user-authored compute shader dispatched alongside the
// standard ones. The custom shader inverts RGB in the area covered by a
// list of circles. The mouse-tracking circle moves; two static ones sit

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// End-to-end demo of GPU asset decompression via VK_EXT_memory_decompression.
//
// Walks the full compressed-asset pipeline:

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom blur pass (PlainComputeShader). Box-blurs the thresholded bloom
// mip into a second rgba16float target demonstrating an N-target float
// chain: this pass SAMPLES the texture the threshold pass wrote (storage

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom closest-hit (runs in SHADE). Half the cubes are "emitters" that
// accumulate a strongly super-1.0 radiance (the HDR signal a bloom pass
// extracts); the rest are dim Lambert-shaded fillers near/below 1.0 that the

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom composite (UI custom shader, dispatched via UIRenderer). Runs
// inside the per-frame UI compute pass, so it owns the ping-pong `out`
// texture that gets blitted to the canvas the app's compositeswapchain

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom — cross-backend-shaped HDR post-process on the WebGPU/DOM
// backend, exercising the primitives added for issue #27:
//

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom miss (runs in SHADE). Dark, sub-threshold background so the
// bloom pass only picks up the bright cubes, not the sky.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args). Primary rays only

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom threshold pass (PlainComputeShader). Reads the linear HDR scene
// (rgba16float, written by the RT RESOLVE stage), keeps only the radiance
// above 1.0, and writes it into the bloom mip (also rgba16float). This is

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
HelloDom exercises every public surface of the DOM partition that
absorbed Crafter.CppDOM:

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
HelloDom the minimum DOM-mode example. Build with:
crafter-build --local --target=wasm32-wasip1

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Smoke test for the Tier 1+2+3 UI architecture. Opens a window, draws a
// background, a button (Tier 3 component), a slider (Tier 3 component), a
// progress bar (Tier 3 component), and a circle that follows the mouse
@ -170,14 +173,20 @@ int main() {
0, 0, 0, 0,
};
// Flush + dispatch. The library inserts the inter-dispatch barriers.
// Flush the buffers the GPU is about to read, then composite all three
// categories — background quads, the mouse circle, and the button/label
// text — in ONE fused dispatch (issue #47). The frame runs these passes
// back-to-back with no custom shader interleaved, so DispatchFused loads
// and stores the swapchain image once instead of three times and skips
// the two inter-pass barriers DispatchQuads→Circles→Text would insert.
// Canonical order is quads → circles → images → text; here there are no
// images, so that category is a free no-op.
if (qc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
quadsBuf.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
#else
quadsBuf.FlushDevice();
#endif
ui.DispatchQuads(cmd, quadsSlot, qc);
}
if (cc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
@ -185,7 +194,6 @@ int main() {
#else
circlesBuf.FlushDevice();
#endif
ui.DispatchCircles(cmd, circlesSlot, cc);
}
if (gc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
@ -193,8 +201,12 @@ int main() {
#else
glyphsBuf.FlushDevice();
#endif
ui.DispatchText(cmd, glyphsSlot, gc);
}
ui.DispatchFused(cmd,
{quadsSlot, qc},
{circlesSlot, cc},
{}, // no images this frame
{glyphsSlot, gc});
});
window.FinishInit();

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import Crafter.Graphics;
import std;
using namespace Crafter;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// =====================================================================
// InputSystem — guided tour of Crafter::Input
// =====================================================================

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

21
examples/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2026 Catcrafts®
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow closest-hit (runs in SHADE). The multi-light counterpart
// of RTStress: EVERY light emits its own shadow ray from this single
// invocation, so several rays for the same pixel resolve in the next SHADE

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow — multi-light shadowing through the wavefront RT pipeline
// (issue #30). Five pillars on a checkered ground, lit by four colored
// point lights; the closest-hit emits one shadow ray PER LIGHT from the

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow miss (runs in SHADE). Shadow miss that light is visible
// from the surface, so add its pending contribution; up to LIGHT_COUNT of
// these resolve for the same pixel in one pass (atomic rtAccumulate, #30).

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the
// linear accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress closest-hit (runs in SHADE). Computes flat-shaded Lambert from
// the hit triangle's geometric normal, accumulates ambient, and if the
// surface faces the sun emits a shadow ray toward the sun. The shadow

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress — the standing many-instance wavefront RT benchmark. An
// N×N×N grid of a small cube mesh (one BLAS, many TLAS instances), shaded
// with primary + shadow rays through the wavefront pipeline. The grid edge

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress miss (runs in SHADE). Primary miss sky gradient. Shadow miss
// the sun is unoccluded, so add the pending direct contribution.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_buffer_reference : enable
#extension GL_EXT_scalar_block_layout : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Issue #37: GPU producer (WebGPU) for the procedural AABB build input.
// Writes the per-box bounding boxes straight into a device storage buffer
// that Mesh::BuildProcedural / RefitProcedural then consume by handle, with

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume any-hit shader (runs in TRACE on every candidate sphere hit,
// because the geometry is registered non-opaque). Punches a spherical
// checkerboard of holes: for half the cells it returns RT_ANYHIT_IGNORE,

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume closest-hit (runs in SHADE). Shades the procedural sphere by
// its surface normal with a fixed sun + ambient, tinted per instance.
//

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume intersection shader (runs in TRACE, per AABB the ray enters).
// Analytic ray-sphere test: the unit box [-1,1]^3 is treated as the
// bounding volume of a sphere of radius 1 centred at the box centre. The

View file

@ -1,3 +1,6 @@
//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:
//

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume miss (runs in SHADE). Vertical sky gradient also what shows
// through the any-hit cut-out cells.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress closest-hit (runs in SHADE). Computes flat-shaded Lambert from
// the hit triangle's geometric normal, accumulates ambient, and if the
// surface faces the sun emits a shadow ray toward the sun. The shadow

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RayQueryPick — regression test for the WebGPU software ray-query shim.
//
// Builds an 8³ = 512-instance TLAS (well below the 8193 threshold where a
@ -189,8 +192,17 @@ int main() {
push.origin[2] = origin0 + float(kHitZ) * kSpacing;
push.dir[0] = -1.0f; push.dir[1] = 0.0f; push.dir[2] = 0.0f;
// Drive byteCount-bounded prefix readback (issue #133) once the full read
// has verified the hit: re-read ONLY the first 8 bytes (hit +
// instanceCustomIndex) with byteCount=8 after poisoning the host mirror,
// and confirm the two prefix fields land while primitiveIndex (bytes 8..11)
// stays poisoned — i.e. the copy was actually bounded, not full-capacity.
constexpr std::uint32_t kPoison = 0xEEEEEEEEu;
constexpr std::uint32_t kPrefixLen = 2 * sizeof(std::uint32_t); // hit + customIndex
static int frame = 0;
static bool dispatched = false;
static bool prefixSent = false;
static bool reported = false;
EventListener<void> tick(&window.onBeforeUpdate, [&]() {
if (reported) return;
@ -199,7 +211,7 @@ int main() {
pickShader.Dispatch(&push, sizeof(push), pickHandles, 1, 1, 1);
pickBuf.EnqueueReadback();
dispatched = true;
} else if (dispatched && pickBuf.PollReadback()) {
} else if (dispatched && !prefixSent && pickBuf.PollReadback()) {
const PickResult& r = pickBuf.value[0];
const bool ok = (r.hit == 1u) && (r.instanceCustomIndex == kExpectedCustomIndex);
std::println("[RayQueryPick] result: hit={} customIndex={} prim={} t={}",
@ -210,6 +222,20 @@ int main() {
std::println("[RayQueryPick] FAIL — expected hit=1 customIndex={}, got hit={} customIndex={}",
kExpectedCustomIndex, r.hit, r.instanceCustomIndex);
}
// Now kick off the bounded prefix re-read. Poison the whole mirror
// first; the prefix poll must overwrite only bytes [0,8).
pickBuf.value[0] = { kPoison, kPoison, kPoison, 0.0f };
pickBuf.EnqueueReadback(/*resetBytes*/ 0, /*byteCount*/ kPrefixLen);
prefixSent = true;
} else if (prefixSent && pickBuf.PollReadback(/*byteCount*/ kPrefixLen)) {
const PickResult& r = pickBuf.value[0];
const bool prefixOk = (r.hit == 1u)
&& (r.instanceCustomIndex == kExpectedCustomIndex)
&& (r.primitiveIndex == kPoison); // tail untouched
std::println("[RayQueryPick] prefix readback (byteCount={}): hit={} customIndex={} prim=0x{:08X}",
kPrefixLen, r.hit, r.instanceCustomIndex, r.primitiveIndex);
std::println("[RayQueryPick] {} — byteCount-bounded readback copied only the live prefix",
prefixOk ? "PASS" : "FAIL");
// The render loop runs after main's _Exit, where stdio is never
// flushed implicitly — push the verdict out explicitly.
std::fflush(stdout);

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress miss (runs in SHADE). Primary miss sky gradient. Shadow miss
// the sun is unoccluded, so add the pending direct contribution.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// rayQuery picking smoke test (WebGPU/DOM software ray-query path).
//
// Shoots a single, fully-determined ray at a known TLAS instance through

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza closest-hit (runs in SHADE). In the wavefront model the lighting
// + shadow trace that used to live in raygen happens here: gather surface
// data, accumulate ambient, and emit a shadow ray toward the sun carrying

View file

@ -1,3 +1,6 @@
//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

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza miss (runs in SHADE). Primary miss two-stop sky gradient.
// Shadow miss the sun is unoccluded, so add the pending direct term.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza raygen (runs in GENERATE). Emits the pixel's primary ray; all
// shading + the shadow trace now happen in SHADE (closesthit/miss). Camera
// state comes from the host each frame via a storage buffer at

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator matches the tonemap the megakernel raygen applied inline.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -0,0 +1,131 @@
# SponzaBench — measuring the post-#40 performance work
This example exists to answer issue **#155**: *starting with #40 a lot of
performance-related issues were merged — what is the net performance gain,
measured in a representative scene (Sponza)?*
It is a headless benchmark harness built around the **native Vulkan**
Sponza ray-tracing scene. Same asset bundle and camera as
[`examples/Sponza`](../Sponza), but instead of opening an interactive
window it times the work and prints machine-readable `BENCH …` lines, then
exits.
## What it measures
* **setup** — process start through the first command submission: asset
decompression, BLAS build per mesh group, the multi-instance TLAS, the
RT pipeline, GPU memory placement and the descriptor writes. This is the
window most of the post-#40 *native* perf work acts on.
* **frames** — a warmup followed by a measured loop calling
`Window::Render()`, reporting per-frame wall-clock stats and throughput.
Unlike the interactive Sponza example — which is single-material on native
because of the hit-shader dynamic-`descriptor_heap`-index driver fault
(see `examples/Sponza/README.md`) — SponzaBench's closest-hit shades from
barycentric coordinates and samples **no** texture, so it can build the
**full multi-mesh atrium** (25 mesh groups, ~262 k triangles) as one
multi-instance TLAS. The albedo is still decompressed and uploaded during
setup (to keep that path in the measurement) but is not bound.
## Running
```bash
cd examples/SponzaBench
crafter-build # native Vulkan
# from the produced bin dir:
VK_LOADER_LAYERS_DISABLE='~all~' \
CRAFTER_PRESENT_IMMEDIATE=1 \
BENCH_WARMUP=200 BENCH_FRAMES=2000 BENCH_MESHES=25 ./SponzaBench
```
`run-bench.sh <bindir> <label> <meshes> <reps> [--cold]` runs it N times
and reports the median / min / max of each metric.
Environment knobs:
| var | effect |
|---|---|
| `CRAFTER_PRESENT_IMMEDIATE=1` | uncapped present mode — without it FIFO pins frame time to the compositor's vblank (~60 Hz) and steady-state throughput can't be seen. |
| `VK_LOADER_LAYERS_DISABLE='~all~'` | disable the validation layer. The engine enables Khronos validation **and GPU-assisted validation** unconditionally; that adds large, version-dependent overhead and must be off for a representative measurement. |
| `BENCH_WARMUP` / `BENCH_FRAMES` | warmup and measured frame counts (default 200 / 2000). |
| `BENCH_MESHES` | cap on mesh groups loaded (default: all 25). A small cap shrinks GPU work so per-frame **CPU** cost dominates; the full scene is GPU-traversal bound. |
| `BENCH_CLEAN_EXIT=1` | exit via `std::exit` (runs `atexit`, which writes the #69 pipeline cache) instead of the default hard `_Exit`. Used once to seed `pipeline_cache.bin` for a warm-cache measurement. |
## Results — #40 vs current master
Measured on this repo's CI box: **NVIDIA RTX 4090**, driver `610.43.02`,
1280×720, validation disabled, `IMMEDIATE` present, 200 warmup + 2000
measured frames, **median of 9 runs**. "#40" is commit `1451e3a` (the #40
merge); "HEAD" is current master. The *same* SponzaBench sources were
built against each library revision (a git worktree at #40).
### Full atrium — 25 meshes / ~262 k triangles (GPU-traversal bound)
| metric | #40 | HEAD | Δ |
|---|---:|---:|---:|
| setup (cold) ms | 322.7 | 316.6 | **1.9 %** |
| setup (warm pipeline cache, #69) ms | 322.7¹ | 313.9 | **2.7 %** |
| throughput fps | 7 560 | 7 637 | **+1.0 %** |
| frame time p50 ms | 0.1311 | 0.1298 | **1.0 %** |
| peak host RSS (cold) MB | 336.0 | 344.2 | +2.4 % |
| peak host RSS (warm cache) MB | 336.0¹ | 332.0 | **1.2 %** |
¹ #40 predates the disk pipeline cache (#69), so its setup is always the
cold-compile path.
### Light scene — 1 mesh (deliberately CPU-bound)
| metric | #40 | HEAD | Δ |
|---|---:|---:|---:|
| throughput fps | 15 022 | 15 237 | **+1.4 %** |
| frame time p50 ms | 0.0662 | 0.0650 | **1.8 %** |
## Interpretation
**The net measured gain in a static Sponza RT scene is small: ~12 %
faster frames, ~23 % faster setup, and roughly flat host memory.** That is
an honest result, and the reason is *what Sponza exercises*, not that the
perf work was ineffective:
* **Most post-#40 PRs don't touch this workload.** The largest block is UI
/ text rendering (shaped-run cache, font-atlas dirty uploads, the UI
compute-shader rewrites — #46#57, #61, #122#129, #132). Sponza has no
UI, so those contribute **zero**. A second block optimises **per-frame
dynamic uploads** (TLAS dirty-tracking #118, deforming-mesh refit #119,
the staging ring #120). A *static* scene builds its TLAS once and never
re-uploads, so these don't fire in steady state either. WebGPU-only
(#130/#131/#133) and Win32-only (#134) PRs don't apply to a native
Vulkan build at all.
* **The PRs that *do* apply act on setup and memory, not frame time.**
Device-local placement (#65/#72/#73/#75), staging release
(#66/#67/#114), the pipeline cache (#69) and the deferred-deletion queue
(#101/#116) move setup cost and peak memory — which is exactly where the
measured ~23 % setup change and the warm-cache RSS drop show up. The
pipeline cache itself saves ~3 ms here (one RT pipeline) and, more
visibly, ~12 MB of peak RSS by skipping the cold shader-compile
allocations.
* **Steady-state frame time is GPU-traversal bound.** With 262 k triangles
the per-frame CPU work (barrier scoping #48/#115, cached heap-bind
structs #42/#43) is hidden behind GPU traversal, so it can't move the
frame time. Shrinking the scene until it is CPU-bound (the light scene
above) surfaces the per-frame CPU savings — and even then they are only
~1.8 %, because that CPU path was already cheap.
**Takeaway:** the post-#40 work is real but concentrated in UI/text and
per-frame dynamic-upload paths; a static, UI-less RT scene is the wrong
workload to see most of it. To quantify the UI/text gains a separate
benchmark over a text-heavy `UIRenderer` scene (or an animated/deforming
scene for the dynamic-upload PRs) would be needed.
## Caveats / notes
* The stock `examples/Sponza` **native** path does not currently compile
against the (unpinned) Vulkan-Headers `main`: the
`VkResourceDescriptorDataEXT` union no longer has the
`pCombinedImageSampler` member the example uses. SponzaBench sidesteps
this by not binding a combined image+sampler. (Pre-existing, unrelated to
#155 — worth a follow-up to port Sponza to the split sampled-image +
sampler-heap model the engine's own UI renderer already uses.)
* Numbers are CPU/GPU specific. Re-run `run-bench.sh` locally for your
hardware; the *deltas* between revisions are the point, not the absolute
figures.

View file

@ -0,0 +1,19 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
// Benchmark closest-hit: shade from the hit's barycentric coordinates.
// SponzaBench deliberately avoids the descriptor-heap texture sample the
// interactive Sponza example uses — the point here is to measure the
// ray-tracing traversal + frame-loop cost, not texturing, and a
// texture-free hit keeps the host setup portable across library
// revisions (issue #155).
hitAttributeEXT vec2 hitAttrs;
layout(location = 0) rayPayloadInEXT vec3 hitValue;
void main() {
vec3 bary = vec3(1.0 - hitAttrs.x - hitAttrs.y, hitAttrs.x, hitAttrs.y);
hitValue = bary;
}

View file

@ -0,0 +1,309 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SponzaBench — headless benchmark around the native Sponza RT scene.
//
// Identical setup to examples/Sponza (native branch): load the Sponza
// .cmesh + albedo .ctex, build BLAS/TLAS, wire an RTPass. Instead of
// opening an interactive window and idling in StartSync(), it times two
// things and exits:
//
// * setup — process start through the first command submission
// (asset decompress + BLAS/TLAS build + pipeline + memory
// placement + descriptor writes), which the bulk of the
// post-#40 perf work targets (device-local placement,
// staging release, pipeline cache, decompress, ...).
// * frames — a warmup then a measured loop calling Window::Render(),
// reporting per-frame wall-clock stats. Run with
// CRAFTER_PRESENT_IMMEDIATE=1 to uncap from vblank.
//
// Tunables (env): BENCH_WARMUP (default 200), BENCH_FRAMES (default 2000).
// Output lines are prefixed "BENCH " for easy scraping.
#include "vulkan/vulkan.h"
import Crafter.Graphics;
import Crafter.Asset;
import Crafter.Math;
import Crafter.Event;
import std;
using namespace Crafter;
namespace fs = std::filesystem;
using Clock = std::chrono::steady_clock;
namespace {
struct RGBA8 { std::uint8_t r, g, b, a; };
void RequireAssets(const fs::path& mesh, const fs::path& tex) {
if (fs::exists(mesh) && fs::exists(tex)) return;
std::println(std::cerr, "[SponzaBench] missing asset(s): {} / {}",
mesh.string(), tex.string());
std::abort();
}
// Peak resident set size (high-water mark) in kB, from /proc/self/status.
long PeakRSSkB() {
std::ifstream st("/proc/self/status");
std::string line;
while (std::getline(st, line)) {
if (line.rfind("VmHWM:", 0) == 0) {
long kb = 0;
std::sscanf(line.c_str(), "VmHWM: %ld", &kb);
return kb;
}
}
return -1;
}
std::size_t EnvSize(const char* name, std::size_t fallback) {
if (const char* v = std::getenv(name)) {
char* end = nullptr;
unsigned long parsed = std::strtoul(v, &end, 10);
if (end != v) return static_cast<std::size_t>(parsed);
}
return fallback;
}
double Ms(std::chrono::nanoseconds ns) {
return std::chrono::duration<double, std::milli>(ns).count();
}
}
int main() {
const std::size_t warmup = EnvSize("BENCH_WARMUP", 200);
const std::size_t frames = EnvSize("BENCH_FRAMES", 2000);
const auto tProcStart = Clock::now();
const fs::path texPath = "tex_0.ctex";
RequireAssets("mesh_0.cmesh", texPath);
// scene.txt (from the asset bundle): line 1 albedoCount, line 2
// meshCount, then per-mesh albedo index. We render every mesh group —
// unlike the interactive Sponza example, which is single-material on
// native because of the hit-shader dynamic-heap-index driver fault.
// SponzaBench's hit shader samples no texture, so it can build the
// full multi-mesh atrium as one multi-instance TLAS.
std::uint32_t albedoCount = 0, meshCount = 0;
{
std::ifstream manifest("scene.txt");
if (!manifest) { std::println(std::cerr, "[SponzaBench] missing scene.txt"); std::abort(); }
manifest >> albedoCount >> meshCount;
}
// BENCH_MESHES caps the number of mesh groups loaded (default: all).
// A small cap (e.g. 1) shrinks GPU work so per-frame CPU cost dominates;
// the full scene is GPU (traversal) bound.
meshCount = std::min<std::uint32_t>(meshCount, EnvSize("BENCH_MESHES", meshCount));
CompressedTextureAsset loadedTex = LoadCompressedTexture(texPath);
std::println("[SponzaBench] scene: {} meshes, {} albedos, {}x{} probe albedo",
meshCount, albedoCount, loadedTex.sizeX, loadedTex.sizeY);
Device::Initialize();
Window window(1280, 720, "SponzaBench");
VkCommandBuffer cmd = window.StartInit();
DescriptorHeapVulkan descriptorHeap;
descriptorHeap.Initialize(/*images*/ 2, /*buffers*/ 1, /*samplers*/ 0);
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);
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, 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,
} }};
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);
// One Mesh + RenderingElement3D per mesh group → BLAS each, then a
// single multi-instance TLAS. Pointers handed to RenderingElement3D
// live in the static vectors, so reserve up-front: a reallocation
// would dangle every registered element.
static std::vector<Mesh> meshes;
static std::vector<RenderingElement3D> renderers;
meshes.reserve(meshCount);
renderers.reserve(meshCount);
std::uint64_t totalVerts = 0, totalIdx = 0;
for (std::uint32_t i = 0; i < meshCount; ++i) {
const fs::path mp = std::format("mesh_{}.cmesh", i);
if (!fs::exists(mp)) continue;
CompressedMeshAsset loaded = LoadCompressedMesh(mp);
totalVerts += loaded.vertexCount;
totalIdx += loaded.indexCount;
meshes.emplace_back();
meshes.back().Build(loaded, cmd);
renderers.emplace_back();
RenderingElement3D& r = renderers.back();
r.instance = {
.transform = {},
.instanceCustomIndex = 0,
.mask = 0xFF,
.instanceShaderBindingTableRecordOffset = 0,
.flags = VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR,
.accelerationStructureReference = meshes.back().blasAddr,
};
MatrixRowMajor<float, 4, 3, 1>::Identity()
.Store(reinterpret_cast<float*>(r.instance.transform.matrix));
RenderingElement3D::Add(&r);
}
std::println("[SponzaBench] built {} BLAS, {} verts, {} idx total",
renderers.size(), totalVerts, totalIdx);
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);
// The albedo is uploaded to keep the texture-decompress + staging
// setup path in the measured "setup" window, but is not bound — the
// closest-hit shades from barycentrics, so only the TLAS + per-frame
// output image need descriptors.
for (std::uint32_t f = 0; f < Window::numFrames; ++f)
RenderingElement3D::BuildTLAS(cmd, f);
window.FinishInit();
VkDeviceAddressRangeKHR tlasRanges[Window::numFrames];
VkImageDescriptorInfoEXT outImgInfos[Window::numFrames];
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
tlasRanges[f] = { .address = RenderingElement3D::tlases[f].address };
outImgInfos[f] = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT,
.pView = &window.imageViews[f],
.layout = VK_IMAGE_LAYOUT_GENERAL,
};
}
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_STORAGE_IMAGE,
.data = { .pImage = &outImgInfos[f] },
});
destinations.push_back({
.address = descriptorHeap.resourceHeap[f].value
+ descriptorHeap.ImageByteOffset(imgSlots.firstElement),
.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();
}
window.descriptorHeap = &descriptorHeap;
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
// ── Setup complete. Everything above is the per-run, one-time cost. ──
const auto tSetupDone = Clock::now();
const double setupMs = Ms(tSetupDone - tProcStart);
// ── Warmup: let the pipeline fill (frames-in-flight), caches warm. ──
for (std::size_t i = 0; i < warmup; ++i) window.Render();
// ── Measured loop: per-frame wall-clock around Render(). ────────────
std::vector<double> frameMs;
frameMs.reserve(frames);
const auto tLoopStart = Clock::now();
for (std::size_t i = 0; i < frames; ++i) {
const auto a = Clock::now();
window.Render();
const auto b = Clock::now();
frameMs.push_back(Ms(b - a));
}
const auto tLoopEnd = Clock::now();
// Drain so the loop's wall-clock isn't charged the GPU tail of the
// last few in-flight frames inconsistently across runs.
vkQueueWaitIdle(Device::queue);
const long peakRSS = PeakRSSkB();
// ── Stats. throughput uses the loop wall-clock (steady-state FPS);
// per-frame percentiles use the sorted per-frame samples. ─────────
const double loopWallMs = Ms(tLoopEnd - tLoopStart);
std::sort(frameMs.begin(), frameMs.end());
auto pct = [&](double p) {
if (frameMs.empty()) return 0.0;
std::size_t idx = static_cast<std::size_t>(p * (frameMs.size() - 1));
return frameMs[idx];
};
double sum = 0.0; for (double v : frameMs) sum += v;
const double meanMs = frameMs.empty() ? 0.0 : sum / frameMs.size();
std::println("");
std::println("BENCH setup_ms {:.3f}", setupMs);
std::println("BENCH frames {}", frames);
std::println("BENCH loop_wall_ms {:.3f}", loopWallMs);
std::println("BENCH fps {:.1f}", frames / (loopWallMs / 1000.0));
std::println("BENCH frame_mean_ms {:.4f}", meanMs);
std::println("BENCH frame_min_ms {:.4f}", pct(0.0));
std::println("BENCH frame_p50_ms {:.4f}", pct(0.50));
std::println("BENCH frame_p99_ms {:.4f}", pct(0.99));
std::println("BENCH frame_max_ms {:.4f}", pct(1.0));
std::println("BENCH peak_rss_kb {}", peakRSS);
// The interactive Sponza example never tears Device/Window down (it
// loops in StartSync forever); doing so here races GPU-still-in-flight
// resources at static-destruction time. The measurement is already
// printed, so skip destructors entirely with a hard exit.
//
// BENCH_CLEAN_EXIT=1 instead exits via std::exit, which runs atexit
// handlers (on builds that have the disk pipeline cache, #69, this is
// where it is written) before the destructor teardown. Used once to
// seed pipeline_cache.bin for a warm-cache setup measurement; the
// subsequent destructor race is irrelevant since the data is flushed.
std::cout.flush();
if (std::getenv("BENCH_CLEAN_EXIT")) std::exit(0);
std::_Exit(0);
}

View file

@ -0,0 +1,14 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
layout(location = 0) rayPayloadInEXT vec3 hitValue;
void main() {
// Soft sky gradient based on ray direction Y. The actual ray dir
// isn't accessible without an extra payload field; use a flat warm
// tone that matches Sponza's interior lighting.
hitValue = vec3(0.10, 0.08, 0.06);
}

View file

@ -0,0 +1,63 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// SponzaBench — a headless benchmark harness around the native Sponza
// ray-tracing scene. Same asset bundle and shaders as examples/Sponza,
// but main.cpp times setup + a fixed measured frame loop instead of
// opening an interactive window. Native (Vulkan) only — the point is to
// measure the native renderer's per-frame and setup cost across library
// revisions (issue #155: net perf gain from #40 to now).
constexpr std::string_view kSponzaGitUrl = "https://github.com/jimmiebergmann/Sponza.git";
constexpr std::string_view kSponzaCommitSHA = "222338979d32f4f4818466291bdbc29f192b86ba";
constexpr std::uint16_t kAlbedoSize = 1024u;
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
std::vector<std::string> graphicsArgs(args.begin(), args.end());
Configuration* graphics = LocalProject({
.projectFile = "../../project.cpp",
.args = graphicsArgs,
});
Configuration cfg;
cfg.path = "./";
cfg.name = "SponzaBench";
cfg.outputName = "SponzaBench";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
cfg.dependencies = { graphics };
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
fs::path sponzaRoot = GitFetch({
.url = std::string(kSponzaGitUrl),
.commit = std::string(kSponzaCommitSHA),
});
std::string bundleKey = std::format("{}|{}", kSponzaCommitSHA, kAlbedoSize);
auto bundleHash = std::hash<std::string>{}(bundleKey);
fs::path bundleDir = fs::path("build") / std::format("sponza-bundle-{:016x}", bundleHash);
if (auto err = BuildOBJBundle(
sponzaRoot / "sponza.obj",
sponzaRoot / "sponza.mtl",
bundleDir,
kAlbedoSize); !err.empty()) {
std::println(std::cerr, "Sponza bundle error: {}", err);
std::exit(1);
}
for (const auto& entry : fs::directory_iterator(bundleDir)) {
if (entry.is_regular_file()) cfg.files.push_back(entry.path());
}
cfg.shaders.emplace_back(fs::path("raygen.glsl"), std::string("main"), ShaderType::RayGen);
cfg.shaders.emplace_back(fs::path("closesthit.glsl"), std::string("main"), ShaderType::ClosestHit);
cfg.shaders.emplace_back(fs::path("miss.glsl"), std::string("main"), ShaderType::Miss);
return cfg;
}

View file

@ -0,0 +1,55 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : enable
#extension GL_EXT_descriptor_heap : enable
#extension GL_EXT_nonuniform_qualifier : enable
// Specialization constant set from descriptorHeap.bufferStartElement —
// shared with closesthit.glsl. The TLAS lives at descriptor_heap slot
// `bufferStart` (it's an SSBO-typed entry), the per-frame output image
// at heap slot 0.
layout(constant_id = 0) const uint16_t bufferStart = 0us;
layout(descriptor_heap) uniform accelerationStructureEXT topLevelAS[];
layout(descriptor_heap) uniform writeonly image2D image[];
layout(location = 0) rayPayloadEXT vec3 hitValue;
void main() {
uvec2 pixel = gl_LaunchIDEXT.xy;
uvec2 resolution = gl_LaunchSizeEXT.xy;
vec2 uv = (vec2(pixel) + 0.5) / vec2(resolution);
vec2 ndc = uv * 2.0 - 1.0;
// Camera positioned to look down the Sponza atrium axis. Sponza-OBJ
// from McGuire's archive is roughly 30 units wide × 13 tall × 18 deep,
// axis-aligned, with the floor near y=0 and the atrium centered on
// origin. -X faces the long end, so we sit inside looking +X.
vec3 origin = vec3(-10.0, 5.0, 0.0);
float aspect = float(resolution.x) / float(resolution.y);
float fov = radians(70.0);
float tanHalf = tan(fov * 0.5);
vec3 direction = normalize(vec3(
ndc.x * aspect * tanHalf,
-ndc.y * tanHalf,
1.0));
// Rotate +Z forward → +X forward (90° about Y).
direction = vec3(direction.z, direction.y, -direction.x);
traceRayEXT(
topLevelAS[bufferStart],
gl_RayFlagsNoneEXT,
0xff,
0, 0, 0,
origin,
0.001,
direction,
10000.0,
0);
imageStore(image[0], ivec2(pixel), vec4(hitValue, 1.0));
}

View file

@ -0,0 +1,43 @@
#!/usr/bin/env bash
#SPDX-License-Identifier: MIT
#SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# Repeated-measurement harness for SponzaBench. Runs the binary in $BINDIR
# REPS times for a given mesh cap and reports the median (and min/max) of
# each BENCH metric. Validation is force-disabled via the loader (it adds
# huge, version-dependent overhead) and present mode is uncapped so frame
# time reflects real work rather than the compositor's vblank.
#
# Usage: run-bench.sh <bindir> <label> <meshes> <reps> [--cold]
# --cold deletes pipeline_cache.bin before EACH run (cold-compile path).
set -u
BINDIR="$1"; LABEL="$2"; MESHES="$3"; REPS="$4"; COLD="${5:-}"
cd "$BINDIR" || exit 1
declare -A vals
metrics="setup_ms fps frame_mean_ms frame_p50_ms frame_p99_ms peak_rss_kb"
for m in $metrics; do vals[$m]=""; done
for ((i=0;i<REPS;i++)); do
[ "$COLD" = "--cold" ] && rm -f pipeline_cache.bin
out=$(VK_LOADER_LAYERS_DISABLE='~all~' CRAFTER_PRESENT_IMMEDIATE=1 \
BENCH_WARMUP=200 BENCH_FRAMES=2000 BENCH_MESHES="$MESHES" \
./SponzaBench 2>/dev/null)
for m in $metrics; do
v=$(echo "$out" | awk -v k="$m" '$1=="BENCH" && $2==k {print $3}')
vals[$m]="${vals[$m]} $v"
done
done
med() { tr ' ' '\n' | grep -v '^$' | sort -n | awk '{a[NR]=$1} END{print a[int((NR+1)/2)]}'; }
lo() { tr ' ' '\n' | grep -v '^$' | sort -n | head -1; }
hi() { tr ' ' '\n' | grep -v '^$' | sort -n | tail -1; }
echo "## $LABEL (meshes=$MESHES reps=$REPS ${COLD})"
printf "%-15s %12s %12s %12s\n" metric median min max
for m in $metrics; do
echo -n "$(printf '%-15s' "$m") "
printf "%12s %12s %12s\n" \
"$(echo "${vals[$m]}" | med)" "$(echo "${vals[$m]}" | lo)" "$(echo "${vals[$m]}" | hi)"
done
echo

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_nonuniform_qualifier : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Payload declared here so the WGSL assembler sees it before the wfPayload
// binding, the SHADE dispatch, and the raygen source.
//

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
#include "vulkan/vulkan.h"
#endif

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Wavefront miss: runs in SHADE for rays that hit nothing. Accumulate the
// white background directly.

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// WebGPU wavefront raygen. Runs in GENERATE: compute the pinhole camera
// ray and emit it as the pixel's primary ray. Shading happens later in
// SHADE (closesthit/miss). The Payload type is declared in closesthit.wgsl.

View file

@ -1,22 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <wayland-client.h>

View file

@ -1,21 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include "vulkan/vulkan.h"
module Crafter.Graphics:ComputeShader_impl;
@ -82,7 +67,7 @@ void ComputeShader::Load(const std::filesystem::path& spvPath) {
.layout = VK_NULL_HANDLE,
};
Device::CheckVkResult(vkCreateComputePipelines(
Device::device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline));
Device::device, Device::pipelineCache, 1, &info, nullptr, &pipeline));
}
void ComputeShader::Dispatch(VkCommandBuffer cmd,

View file

@ -1,22 +1,5 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
@ -136,6 +119,97 @@ void Device::CheckVkResult(VkResult result) {
}
}
bool Device::PipelineCacheDataCompatible(std::span<const std::byte> data) {
// VkPipelineCacheHeaderVersionOne is a fixed 32-byte little-endian header
// (Vulkan spec 16.5.2): u32 headerSize, u32 headerVersion, u32 vendorID,
// u32 deviceID, then VK_UUID_SIZE bytes of pipelineCacheUUID. Parse the
// fields by offset rather than reinterpret_cast'ing the struct so the
// check is independent of the C struct's alignment/padding.
constexpr std::size_t headerBytes = 16 + VK_UUID_SIZE;
if (data.size() < headerBytes) {
return false;
}
auto readU32 = [&](std::size_t offset) {
std::uint32_t value;
std::memcpy(&value, data.data() + offset, sizeof(value));
return value;
};
const std::uint32_t headerSize = readU32(0);
const std::uint32_t headerVersion = readU32(4);
const std::uint32_t vendorID = readU32(8);
const std::uint32_t deviceID = readU32(12);
if (headerSize < headerBytes) {
return false;
}
if (headerVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE) {
return false;
}
if (vendorID != deviceProperties.vendorID || deviceID != deviceProperties.deviceID) {
return false;
}
return std::memcmp(data.data() + 16, deviceProperties.pipelineCacheUUID, VK_UUID_SIZE) == 0;
}
void Device::LoadPipelineCache() {
std::vector<std::byte> initialData;
std::error_code ec;
if (std::filesystem::exists(pipelineCachePath, ec)) {
std::ifstream file(pipelineCachePath, std::ios::binary | std::ios::ate);
if (file) {
const std::streamoff size = file.tellg();
if (size > 0) {
initialData.resize(static_cast<std::size_t>(size));
file.seekg(0);
file.read(reinterpret_cast<char*>(initialData.data()), size);
if (!file) {
initialData.clear(); // partial/short read — start cold
}
}
}
}
// Drop a blob the current driver/device wouldn't accept: a header from a
// different GPU (or a corrupt/empty file) would at best be ignored and at
// worst rejected. Starting empty just costs a one-time cold compile.
if (!PipelineCacheDataCompatible(initialData)) {
initialData.clear();
}
VkPipelineCacheCreateInfo info {
.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
.initialDataSize = initialData.size(),
.pInitialData = initialData.empty() ? nullptr : initialData.data(),
};
CheckVkResult(vkCreatePipelineCache(device, &info, nullptr, &pipelineCache));
}
void Device::SavePipelineCache() {
if (pipelineCache == VK_NULL_HANDLE) {
return;
}
// Two-call idiom: query size, then fetch. Best-effort — a failure here only
// forfeits the next run's warm start, so it must never throw out of an
// atexit handler.
std::size_t size = 0;
if (vkGetPipelineCacheData(device, pipelineCache, &size, nullptr) != VK_SUCCESS || size == 0) {
return;
}
std::vector<std::byte> data(size);
if (vkGetPipelineCacheData(device, pipelineCache, &size, data.data()) != VK_SUCCESS) {
return;
}
std::ofstream file(pipelineCachePath, std::ios::binary | std::ios::trunc);
if (file) {
file.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(size));
}
}
VkBool32 onError(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData)
{
printf("Vulkan ");
@ -477,6 +551,12 @@ void Device::Initialize() {
// https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/12103
// Per spencer-lunarg (LunarG) that was fixed in the next SDK release.
// The validation layer is now 1.4.350 (> 1.4.341), so re-enable it.
// Validation (incl. GPU-Assisted Validation) is a DEVELOPER tool and is OFF
// by default: GPU-AV instruments shaders and has crashed vendor SPIR-V
// compilers (observed: NVIDIA libnvidia-glvkspirv segfault on the
// descriptor-heap compute pipelines). Opt in by setting the environment
// variable CRAFTER_GRAPHICS_VALIDATION.
bool enableValidation = std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr;
VkValidationFeatureEnableEXT enabledValidationFeatures[] = {
VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT,
};
@ -488,7 +568,7 @@ void Device::Initialize() {
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pNext = &validationFeatures;
instanceCreateInfo.pNext = enableValidation ? (const void*)&validationFeatures : nullptr;
instanceCreateInfo.pApplicationInfo = &app;
instanceCreateInfo.enabledExtensionCount = sizeof(instanceExtensionNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensionNames;
@ -512,7 +592,7 @@ void Device::Initialize() {
}
}
if (foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
if (enableValidation && foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
{
instanceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledLayerNames = layerNames;
@ -603,6 +683,13 @@ void Device::Initialize() {
.pNext = &rayTracingProperties
};
vkGetPhysicalDeviceProperties2(physDevice, &properties2);
// Keep the core properties around for the pipeline-cache identity check
// (vendorID / deviceID / pipelineCacheUUID).
deviceProperties = properties2.properties;
// Cache the flush/invalidate alignment for ranged host-memory flushes
// (VulkanBuffer::FlushDevice(offset,bytes)).
nonCoherentAtomSize = properties2.properties.limits.nonCoherentAtomSize;
// NVIDIA's brand-new VK_EXT_descriptor_heap acceleration-structure read
// path faults (see #7); enable the SPIR-V rewrite workaround there. Other
@ -780,6 +867,7 @@ void Device::Initialize() {
CheckVkResult(vkCreateCommandPool(device, &commandPoolcreateInfo, NULL, &commandPool));
vkGetPhysicalDeviceMemoryProperties(physDevice, &memoryProperties);
CacheUploadStrategy();
vkGetAccelerationStructureBuildSizesKHR = reinterpret_cast<PFN_vkGetAccelerationStructureBuildSizesKHR>(vkGetInstanceProcAddr(instance, "vkGetAccelerationStructureBuildSizesKHR"));
vkCreateAccelerationStructureKHR = reinterpret_cast<PFN_vkCreateAccelerationStructureKHR>(vkGetInstanceProcAddr(instance, "vkCreateAccelerationStructureKHR"));
@ -809,6 +897,14 @@ void Device::Initialize() {
memoryDecompressionSupported = false;
}
}
// Create the shared pipeline cache (seeded from disk when a compatible
// blob exists) and arrange for it to be written back at process exit. The
// device handle is a never-destroyed static, so it is still valid when the
// atexit handler runs. Registered once — Initialize is the single device
// bring-up.
LoadPipelineCache();
std::atexit(SavePipelineCache);
}
std::uint32_t Device::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) {
@ -841,3 +937,92 @@ std::uint32_t Device::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags req
throw std::runtime_error("Could not find a matching memory type");
}
void Device::CacheUploadStrategy() {
constexpr VkMemoryPropertyFlags directFlags =
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
// 1. Find a DEVICE_LOCAL | HOST_VISIBLE type and remember its heap. Without
// one (no resizable BAR), direct writes are impossible -> must stage.
bool haveDirectType = false;
std::uint32_t barHeapIndex = 0;
for (std::uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((memoryProperties.memoryTypes[i].propertyFlags & directFlags) == directFlags) {
haveDirectType = true;
barHeapIndex = memoryProperties.memoryTypes[i].heapIndex;
break;
}
}
if (!haveDirectType) {
directWriteBudget = 0;
return;
}
// 2. Compare the host-visible device-local heap against the largest plain
// DEVICE_LOCAL heap (the true VRAM size).
VkDeviceSize barHeap = memoryProperties.memoryHeaps[barHeapIndex].size;
VkDeviceSize vram = 0;
for (std::uint32_t i = 0; i < memoryProperties.memoryHeapCount; ++i) {
if (memoryProperties.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
vram = std::max(vram, memoryProperties.memoryHeaps[i].size);
}
}
// 3. ReBAR / UMA: the BAR heap covers (almost) all of VRAM -> map any size.
// barHeap >= 0.9 * vram, written to dodge floating point / overflow.
if (barHeap >= vram - vram / 10) {
directWriteBudget = std::numeric_limits<VkDeviceSize>::max();
return;
}
// 4. Small BAR window: direct only for buffers small enough that several
// still fit the window — large buffers stage so they don't exhaust it.
// The budget is tied to the actual window size rather than a magic
// constant so it adapts across devices (a fixed cap would be wrong for
// both a 256 MiB and a 4 GiB window). VK_EXT_memory_budget would refine
// this to the window's *remaining* space; see the header note.
constexpr VkDeviceSize barWindowFraction = 8;
directWriteBudget = barHeap / barWindowFraction;
}
bool Device::PreferDirectDeviceWrite(VkDeviceSize size) {
// directWriteBudget caches the size-independent decision (CacheUploadStrategy):
// 0 -> never direct, max -> ReBAR/UMA so any size, else the small-window cap.
return directWriteBudget != 0 && size <= directWriteBudget;
}
void Device::EnqueueDeletion(VkBuffer buffer, VkDeviceMemory memory) {
// Nothing to free for an already-null handle — avoids parking dead
// entries that ReclaimDeletions would have to skip over.
if (buffer == VK_NULL_HANDLE) return;
deletionQueue.push_back({ frameCounter, buffer, memory });
}
void Device::ReclaimDeletions() {
// Free every entry whose retire frame has been reached. An entry tagged at
// frame F retires at F + framesInFlight: by the time the CPU has begun that
// many later frames (each gated by a per-image fence wait), single-queue
// submission order guarantees all GPU work from frame F is complete.
//
// frameCounter is monotonic, so retireAfter is non-decreasing down the
// queue and the ready entries are a contiguous prefix: pop them off the
// front and stop at the first one still in flight (everything behind it is
// newer, hence also in flight). O(ready), not O(queue).
while (!deletionQueue.empty() &&
deletionQueue.front().retireAfter + framesInFlight <= frameCounter) {
const PendingDeletion& entry = deletionQueue.front();
vkDestroyBuffer(device, entry.buffer, nullptr);
vkFreeMemory(device, entry.memory, nullptr);
deletionQueue.pop_front();
}
}
void Device::DrainDeletions() {
// Unconditional: the caller has just wait-idled, so no in-flight GPU work
// can still reference any queued resource.
for (PendingDeletion& entry : deletionQueue) {
vkDestroyBuffer(device, entry.buffer, nullptr);
vkFreeMemory(device, entry.memory, nullptr);
}
deletionQueue.clear();
}

View file

@ -1,21 +1,5 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Implementation of the :Dom partition. Only ever built when
// CRAFTER_GRAPHICS_WINDOW_DOM is defined (project.cpp's DOM branch

View file

@ -1,22 +1,5 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#define STB_TRUETYPE_IMPLEMENTATION
@ -56,6 +39,23 @@ Font::Font(const std::filesystem::path& fontFilePath) {
this->ascent = ascent;
this->descent = descent;
this->lineGap = lineGap;
asciiAdvance_.fill(-1);
}
std::int32_t Font::AdvanceUnits(std::uint32_t cp) {
if (cp < asciiAdvance_.size()) {
if (asciiAdvance_[cp] < 0) {
int advance = 0, lsb = 0;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
asciiAdvance_[cp] = advance;
}
return asciiAdvance_[cp];
}
if (auto it = advanceUnits_.find(cp); it != advanceUnits_.end()) return it->second;
int advance = 0, lsb = 0;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
return advanceUnits_.emplace(cp, advance).first->second;
}
std::uint32_t Font::GetLineWidth(const std::string_view text, float size) {
@ -65,9 +65,7 @@ std::uint32_t Font::GetLineWidth(const std::string_view text, float size) {
while (i < text.size()) {
std::uint32_t cp = DecodeUtf8(text, i);
if (cp == 0) break;
int advance, lsb;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
lineWidth += (int)(advance * scale);
lineWidth += (int)(AdvanceUnits(cp) * scale);
}
return lineWidth;
}
@ -82,9 +80,7 @@ std::size_t Font::NearestCursorByte(std::string_view text, float size, float tar
while (i < text.size()) {
std::uint32_t cp = DecodeUtf8(text, i); // i advances to the next boundary
if (cp == 0) break;
int advance, lsb;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
cumWidth += (int)(advance * scale); // match GetLineWidth's per-glyph rounding
cumWidth += (int)(AdvanceUnits(cp) * scale); // match GetLineWidth's per-glyph rounding
float d = std::abs(target - cumWidth);
if (d < bestDist) {
bestDist = d;

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -39,7 +42,11 @@ void FontAtlas::Initialize(GraphicsCommandBuffer cmd) {
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
// The atlas is sampled by the UI text *compute* shader, not an RT
// pipeline — scope the upload barriers to the real consumer.
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
// Streamed: glyphs are rasterized into buffer.value on the CPU and
// re-uploaded every frame via UpdateRegion, so the persistent staging
// map must outlive the first upload rather than being released (#114).
/*streamed*/ true
);
std::memset(image.buffer.value, 0, kAtlasSize * kAtlasSize);
#else
@ -55,11 +62,13 @@ void FontAtlas::Initialize(GraphicsCommandBuffer cmd) {
MarkDirty(0, 0, kAtlasSize, kAtlasSize);
}
bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY) {
for (Shelf& s : shelves_) {
bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY, int& outShelf) {
for (std::size_t i = 0; i < shelves_.size(); ++i) {
Shelf& s = shelves_[i];
if (h <= s.height && s.cursorX + w <= kAtlasSize) {
outX = s.cursorX;
outY = s.y;
outShelf = static_cast<int>(i);
s.cursorX += w;
return true;
}
@ -71,6 +80,7 @@ bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY) {
s.cursorX = w;
outX = 0;
outY = s.y;
outShelf = static_cast<int>(shelves_.size());
shelves_.push_back(s);
nextShelfY_ += h;
return true;
@ -102,8 +112,8 @@ const Glyph* FontAtlas::EnsureAndGet(Font& font, std::uint32_t codepoint) {
g.yoff = static_cast<float>(yoff);
if (sdf && sw > 0 && sh > 0) {
int px = 0, py = 0;
if (!ShelfPlace(sw, sh, px, py)) {
int px = 0, py = 0, shelf = 0;
if (!ShelfPlace(sw, sh, px, py, shelf)) {
stbtt_FreeSDF(sdf, nullptr);
return nullptr;
}
@ -123,7 +133,10 @@ const Glyph* FontAtlas::EnsureAndGet(Font& font, std::uint32_t codepoint) {
g.v0 = static_cast<float>(py) / kAtlasSize;
g.u1 = static_cast<float>(px + sw) / kAtlasSize;
g.v1 = static_cast<float>(py + sh) / kAtlasSize;
MarkDirty(px, py, sw, sh);
// Mark the *shelf's* span, not one global box — keeps each upload
// tight when glyphs land on different shelves the same frame (#129).
shelves_[shelf].dirty.Add(px, py, sw, sh);
dirty = true;
}
return &cache_.emplace(key, g).first->second;
@ -137,18 +150,18 @@ const Glyph* FontAtlas::Lookup(Font& font, std::uint32_t codepoint) const {
void FontAtlas::Update(GraphicsCommandBuffer cmd) {
if (!dirty) return;
// Clamp the accumulated box to the atlas and convert to (origin,
// extent). Add() works in glyph coordinates that are always in-bounds,
// but clamping keeps the copy extent provably valid. The `dirty` guard
// above guarantees the rect is non-empty, so UploadBox always fills the
// outputs.
// Issue one tight copy per dirty span and reset it. Clamping to the atlas
// keeps each extent provably valid even though Add() already works in
// in-bounds glyph coordinates; UploadBox skips spans that never armed.
// The spans are the whole-atlas zero-clear (dirtyRect, Initialize only)
// plus each shelf's accumulated glyph run — so scattered glyphs upload as
// several small rects, not one tall union covering the gaps between them.
auto upload = [&](DirtyRect& r) {
std::uint32_t x = 0, y = 0, w = 0, h = 0;
dirtyRect.UploadBox(kAtlasSize, x, y, w, h);
if (!r.UploadBox(kAtlasSize, x, y, w, h)) return;
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
image.UpdateRegion(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, x, y, w, h);
#else
(void)cmd;
// The staging buffer keeps the full atlas row stride, so srcBytesPerRow
// stays kAtlasSize and (dstX, dstY) index the sub-rect's first texel.
WebGPU::wgpuWriteAtlasRegion(
@ -158,6 +171,14 @@ void FontAtlas::Update(GraphicsCommandBuffer cmd) {
static_cast<std::int32_t>(w), static_cast<std::int32_t>(h)
);
#endif
r.Reset();
};
#ifdef CRAFTER_GRAPHICS_WINDOW_DOM
(void)cmd;
#endif
upload(dirtyRect);
for (Shelf& s : shelves_) upload(s.dirty);
dirty = false;
dirtyRect.Reset();
}

View file

@ -1,22 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <libudev.h>

View file

@ -1,22 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
module Crafter.Graphics;
import std;

View file

@ -1,21 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
module Crafter.Graphics:InputField_impl;
import :InputField;
@ -150,7 +135,21 @@ void Crafter::DrawInputField(UIBuffer& buf, const InputField& f, Rect rect,
if (f.focused && caretVisible && *buf.quadCount < buf.quadCap) {
std::string_view sub(f.value.data(), std::min(f.cursorPos, f.value.size()));
float caretX = textX + (sub.empty() ? 0.0f : static_cast<float>(font.GetLineWidth(sub, fontSize)));
// Memoise the prefix width (issue #128): only the blink changes between
// frames, so re-walking the prefix every frame is wasted work. A byte
// compare of the cached prefix (plus fontSize) is far cheaper than the
// per-glyph UTF-8 decode + advance accumulation GetLineWidth does.
float width;
if (f.caretCacheFontSize_ == fontSize && f.caretCachePrefix_ == sub) {
width = f.caretCacheWidth_;
} else {
width = sub.empty() ? 0.0f
: static_cast<float>(font.GetLineWidth(sub, fontSize));
f.caretCachePrefix_.assign(sub);
f.caretCacheFontSize_ = fontSize;
f.caretCacheWidth_ = width;
}
float caretX = textX + width;
float caretH = fontSize * 1.1f;
float caretY = rect.y + (rect.h - caretH) * 0.5f;
float caretW = std::max(1.0f, fontSize / 16.0f);

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -377,6 +380,18 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> vertices,
Build(vertices, indices, cmd);
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> vertices,
std::span<std::uint32_t> indices,
std::uint32_t /*dirtyVertexOffset*/,
std::uint32_t /*dirtyVertexCount*/,
WebGPUCommandEncoderRef cmd) {
// No hardware AS, so there is no sub-range to update in place — the
// software path rebuilds the host BVH over the full geometry regardless.
// The dirty window only matters to the hardware backend's ranged upload
// (#119); here it is ignored and this is identical to the full-span Refit.
Build(vertices, indices, cmd);
}
void Mesh::RefitProcedural(std::span<const RTAabb> aabbs,
WebGPUCommandEncoderRef cmd) {
BuildProcedural(aabbs, opaque, cmd);

View file

@ -1,21 +1,5 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "vulkan/vulkan.h"
@ -32,10 +16,16 @@ using namespace Crafter;
namespace {
// Buffer-usage flag set shared by both Build paths. The compressed path
// appends VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT.
// appends VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT, and the staged
// upload path appends VK_BUFFER_USAGE_TRANSFER_DST_BIT. TRANSFER_SRC is in
// the base because the geometry is now device-local (#73): once it no longer
// lives in host-mappable memory, a transfer copy is the only way to read it
// back (debugging, GPU-driven workflows, decompression validation) — a free
// usage flag that keeps device-local geometry inspectable.
constexpr VkBufferUsageFlags2 kVertexUsageBase =
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT
| VK_BUFFER_USAGE_2_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
| VK_BUFFER_USAGE_2_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR
| VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
constexpr VkBufferUsageFlags2 kIndexUsageBase =
kVertexUsageBase | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
@ -152,6 +142,23 @@ namespace {
self.buildFlags = flags;
self.builtPrimitiveCount = primitiveCount;
// Static (!allowUpdate) meshes can never refit, so their per-mesh
// scratch is dead weight the moment this build's GPU work completes —
// release it instead of keeping a persistent DEVICE_LOCAL allocation
// per mesh (the waste that dominates many-mesh scenes, issue #66). The
// fresh build recorded above still reads scratchBuffer.address from
// this command buffer, so a plain Clear() would be a use-after-free;
// DeferredClear() retires the allocation only once the build's frame
// has passed its fence (the queue from #101/#102). A later Refit on a
// static mesh takes the rebuild fallback, whose Resize sees the nulled
// handle and re-Creates the scratch. Refit-capable meshes keep theirs:
// an in-place UPDATE reuses it every frame (build scratch ≥ update
// scratch, so no resize). Only applies to a fresh build — an UPDATE
// never reaches here for a static mesh.
if (!update && !self.allowUpdate) {
self.scratchBuffer.DeferredClear();
}
}
void RecordBLASBuild(Mesh& self, std::uint32_t vertexCount, std::uint32_t indexCount, VkBuildAccelerationStructureFlagsKHR flags, bool update, VkCommandBuffer cmd) {
@ -184,14 +191,13 @@ namespace {
}
void Mesh::Build(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, VkCommandBuffer cmd, RTBuildOptions options) {
vertexBuffer.Resize(kVertexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, verticies.size());
indexBuffer.Resize(kIndexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, indicies.size());
std::memcpy(vertexBuffer.value, verticies.data(), verticies.size() * sizeof(Vector<float, 3, 3>));
std::memcpy(indexBuffer.value, indicies.data(), indicies.size() * sizeof(std::uint32_t));
vertexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
// Place both inputs in device-local memory (direct map on ReBAR/UMA,
// staged copy otherwise — UploadDeviceLocal decides) and barrier the
// upload before the BLAS build reads them. Replaces the previous
// HOST_VISIBLE allocation that the build (and any hit-shader fetch) would
// read over PCIe every frame (#73).
vertexBuffer.UploadDeviceLocal(kVertexUsageBase, verticies.data(), static_cast<std::uint32_t>(verticies.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.UploadDeviceLocal(kIndexUsageBase, indicies.data(), static_cast<std::uint32_t>(indicies.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
allowUpdate = options.allowUpdate;
builtInputCount = static_cast<std::uint32_t>(verticies.size());
@ -218,13 +224,17 @@ void Mesh::Build(const CompressedMeshAsset& asset, VkCommandBuffer cmd, RTBuildO
return;
}
// The GPU decompressor writes vertex/index directly (the build input is
// never host-written on this path), so they want pure DEVICE_LOCAL — no
// host visibility, no map. This is where the BLAS build and any hit-shader
// fetch then read them from (#73).
vertexBuffer.Resize(
kVertexUsageBase | VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
asset.vertexCount);
indexBuffer.Resize(
kIndexUsageBase | VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
asset.indexCount);
compressedStaging.Resize(
@ -261,6 +271,16 @@ void Mesh::Build(const CompressedMeshAsset& asset, VkCommandBuffer cmd, RTBuildO
VK_PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR);
// The compressed staging is only read by the decompress recorded above; the
// subsequent BLAS build reads the decompressed vertex/index buffers, never
// this. So hand it to the fence-keyed deletion queue (#101/#102) now rather
// than pinning host-visible memory for the mesh's whole life. The recorded
// vkCmdDecompressMemoryEXT still references compressedStaging.address, so it
// must outlive this submit — which the queue guarantees: it retires the
// allocation only after framesInFlight frames have elapsed, by which point
// the decompress submit's fence has cleared.
compressedStaging.DeferredClear();
allowUpdate = options.allowUpdate;
builtInputCount = asset.vertexCount;
RecordBLASBuild(*this, asset.vertexCount, asset.indexCount, BlasFlags(options), /*update*/ false, cmd);
@ -300,14 +320,13 @@ namespace {
void RecordProceduralBuild(Mesh& self, std::span<const RTAabb> aabbs, VkBuildAccelerationStructureFlagsKHR flags, bool update, VkCommandBuffer cmd) {
// 24-byte-stride VkAabbPositionsKHR-compatible build input
// (static_assert'd in the interface). Same usage set as the triangle
// inputs: AS-build read-only + device address. A refit reuses the
// existing same-sized buffer (count is unchanged), so the device
// address — and the geometry it feeds — stays stable.
if (!update) {
self.aabbBuffer.Resize(kVertexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, static_cast<std::uint32_t>(aabbs.size()));
}
std::memcpy(self.aabbBuffer.value, aabbs.data(), aabbs.size() * sizeof(RTAabb));
self.aabbBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
// inputs: AS-build read-only + device address. UploadDeviceLocal places
// it in device-local memory (direct map on ReBAR/UMA, staged otherwise,
// #73) and barriers the upload before the build reads it. A refit
// re-uploads into the same same-sized buffer: Resize reuses the existing
// allocation (count unchanged), so the device address — and the geometry
// it feeds — stays stable for an in-place UPDATE.
self.aabbBuffer.UploadDeviceLocal(kVertexUsageBase, aabbs.data(), static_cast<std::uint32_t>(aabbs.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
RecordProceduralBuildFromAddress(self, self.aabbBuffer.address, static_cast<std::uint32_t>(aabbs.size()), sizeof(RTAabb), flags, update, cmd);
}
@ -336,6 +355,11 @@ void Mesh::BuildProcedural(VkDeviceAddress aabbAddress, std::uint32_t count, boo
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, VkCommandBuffer cmd) {
// Whole-vertex-array refit: the entire array is the dirty range.
Refit(verticies, indicies, 0, static_cast<std::uint32_t>(verticies.size()), cmd);
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, std::uint32_t dirtyVertexOffset, std::uint32_t dirtyVertexCount, VkCommandBuffer cmd) {
// A hardware in-place UPDATE is only valid when the original build asked
// for it, an AS already exists, and the topology is unchanged. Otherwise
// fall back to a full rebuild (mode BUILD) of the same buffers — still
@ -348,7 +372,9 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32
if (!update) {
// Counts may have changed (or update wasn't permitted): take the
// resizing build path, preserving the caller's original flags.
// resizing build path, preserving the caller's original flags. The
// dirty window is irrelevant here — a fresh build re-uploads the whole
// array, which is why the full arrays are passed even on this overload.
Build(verticies, indicies, cmd, RTBuildOptions{
.preference = (buildFlags & VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR)
? RTBuildPreference::FastBuild : RTBuildPreference::FastTrace,
@ -357,12 +383,29 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32
return;
}
// Same-sized buffers: overwrite in place so the device addresses (and
// thus the geometry the UPDATE reads) stay stable.
std::memcpy(vertexBuffer.value, verticies.data(), verticies.size() * sizeof(Vector<float, 3, 3>));
std::memcpy(indexBuffer.value, indicies.data(), indicies.size() * sizeof(std::uint32_t));
vertexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
// Same-sized buffers: overwrite the moved vertex positions in place so the
// device address (and thus the geometry the UPDATE reads) stays stable.
// The index buffer is deliberately left untouched: a hardware AS UPDATE
// cannot change topology, so the indices are immutable here — re-uploading
// them would be a wasted memcpy + flush + barrier of unchanged data every
// refit. This means a bitwise-different-but-topologically-equivalent index
// array passed on refit is ignored, consistent with the documented
// contract that a refit may only move vertex positions.
//
// Re-upload only the dirty sub-range [dirtyVertexOffset, +dirtyVertexCount):
// the rest of the vertex buffer already holds last refit's positions, so a
// ranged upload patches just the vertices that moved (#119). The window is
// clamped to the array — a caller window past the end would otherwise read
// out of bounds / overflow the copy. UploadDeviceLocalRange writes into the
// existing same-sized allocation (no Resize), so the address the UPDATE
// reads stays stable, then barriers just that sub-range before the build. On
// the staged path this re-stages only the dirty slice (the deforming-mesh
// fallback, #73).
std::uint32_t offset = std::min(dirtyVertexOffset, static_cast<std::uint32_t>(verticies.size()));
std::uint32_t count = std::min(dirtyVertexCount, static_cast<std::uint32_t>(verticies.size()) - offset);
if (count != 0) {
vertexBuffer.UploadDeviceLocalRange(verticies.data() + offset, offset, count, cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
}
RecordBLASBuild(*this, static_cast<std::uint32_t>(verticies.size()), static_cast<std::uint32_t>(indicies.size()), buildFlags, /*update*/ true, cmd);
}

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®

View file

@ -1,3 +1,6 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -108,9 +111,16 @@ void RenderingElement3D::BuildTLASUpload(WebGPUCommandEncoderRef /*cmd*/, std::u
auto& dst = tlas.instanceBuffer.value[i];
const auto& src = elements[i]->instance;
if (elements[i]->transformOwnedByGpu) {
// Preserve whatever the GPU compute shader most recently
// wrote into dst.transform. Update only the non-transform
// fields.
// GPU owns the transform: copy only the host-authored
// metadata fields and leave the host mirror's transform bytes
// alone (the application doesn't maintain them). The upload
// below pushes the whole struct, including these transform
// bytes, but the physics-tlas-transform compute pass — which
// runs after this Upload and before Build in the supported
// Upload -> compute -> Build flow — overwrites the transform
// on the GPU before the TLAS build reads it, so the host-side
// value is moot. (Nothing reads instanceBuffer between Upload
// and that compute pass.)
dst.instanceCustomIndex = src.instanceCustomIndex;
dst.mask = src.mask;
dst.instanceShaderBindingTableRecordOffset = src.instanceShaderBindingTableRecordOffset;
@ -122,44 +132,34 @@ void RenderingElement3D::BuildTLASUpload(WebGPUCommandEncoderRef /*cmd*/, std::u
tlas.metadataBuffer.value[i] = elements[i]->userMetadata;
}
// Upload the instance buffer with partial-write semantics: for runs
// of CPU-driven elements (transformOwnedByGpu=false) we push the
// whole 64-byte struct in one writeBuffer call; for GPU-driven runs
// we push only the trailing 16 metadata bytes per element, leaving
// the transform field intact for the physics-tlas-transform compute
// shader to update. The two arms below produce identical GPU state
// when every element is CPU-driven — this is a no-op refactor until
// 3DForts flips its physics elements to transformOwnedByGpu=true.
// Upload the active instance range in a single contiguous writeBuffer.
//
// An earlier version split this into per-run arms: contiguous runs of
// CPU-driven elements (transformOwnedByGpu=false) were pushed as one
// block, but GPU-driven runs pushed only the trailing 16 metadata
// bytes of each element — one FlushDeviceRange per element — to avoid
// clobbering the GPU-written transform. The metadata bytes are strided
// (one 16-byte chunk per 64-byte slot), so a GPU-driven run couldn't
// batch; each element paid a separate WebGPU validation / encode /
// JS-boundary cost.
//
// Pushing the whole struct for GPU-driven elements too is harmless:
// the only supported way to drive a transform from the GPU is the
// manual Upload -> physics compute pass -> Build sequence (see the
// file header), and that compute pass runs after this upload and
// rewrites the transform on the GPU before the TLAS build reads it.
// So the stale transform bytes this push carries for those slots are
// overwritten before they matter, and the whole run uploads in one
// call. (The combined BuildTLAS path runs no compute pass and is, as
// documented, only valid for CPU-driven transforms.)
constexpr std::uint32_t kInstSize = sizeof(RTInstance); // 64
constexpr std::uint32_t kTransformSize = sizeof(RTTransformMatrix); // 48
constexpr std::uint32_t kMetaSize = kInstSize - kTransformSize; // 16
tlas.instanceBuffer.FlushDeviceRange(0, 0, primitiveCount * kInstSize);
std::uint32_t runStart = 0;
bool runOwned = elements[0]->transformOwnedByGpu;
for (std::uint32_t i = 1; i <= primitiveCount; ++i) {
const bool atEnd = (i == primitiveCount);
const bool currOwned = atEnd ? !runOwned : elements[i]->transformOwnedByGpu;
if (currOwned == runOwned && !atEnd) continue;
if (runOwned) {
// GPU-driven run — metadata only, per element. Cannot batch
// because the metadata bytes are non-contiguous in the
// instance buffer (one 16-byte chunk per 64-byte slot).
for (std::uint32_t j = runStart; j < i; ++j) {
const std::uint32_t off = j * kInstSize + kTransformSize;
tlas.instanceBuffer.FlushDeviceRange(off, off, kMetaSize);
}
} else {
// CPU-driven run — one contiguous writeBuffer.
const std::uint32_t startOff = runStart * kInstSize;
const std::uint32_t bytes = (i - runStart) * kInstSize;
tlas.instanceBuffer.FlushDeviceRange(startOff, startOff, bytes);
}
runStart = i;
runOwned = currOwned;
}
tlas.metadataBuffer.FlushDevice();
// Only primitiveCount slots are live; the buffer is padded to kNPadded
// (65536). Flushing the whole thing wgpuWriteBuffers all 256 KB through
// the WASM->JS staging path every frame — ~100-250x waste for a
// few-hundred-instance scene. Range-flush just the live entries.
tlas.metadataBuffer.FlushDeviceRange(0, 0, primitiveCount * sizeof(std::uint32_t));
}
void RenderingElement3D::BuildTLASBuild(WebGPUCommandEncoderRef /*cmd*/, std::uint32_t index) {

Some files were not shown because too many files have changed in this diff Show more