Skip to content

feature(vulkan): support per-dispatch push constants - #124

Merged
chuzcjoe merged 1 commit into
masterfrom
daily/feature-vulkan-dispatch-push-constants-20261022
Oct 23, 2026
Merged

chuzcjoe merged 1 commit into
masterfrom
daily/feature-vulkan-dispatch-push-constants-20261022

Conversation

@chuzcjoe

Copy link
Copy Markdown
Collaborator

Problem

VulkanBase::Init() fixes pushConstantRangeCount at zero. Derived compute and graphics pipelines cannot declare push constants while reusing the existing descriptor/pipeline initialization path. The existing barycentric rasterizer uploads one fixed triangle into a uniform buffer during initialization and exposes no per-dispatch triangle parameters. Recording several triangles against one repeatedly overwritten uniform buffer would not preserve a parameter snapshot for each dispatch.

This PR delivers per-dispatch push constants through the existing pipeline abstraction and uses them in the existing rasterizer. It is independently based on freshly fetched/reconfirmed origin/master at f7070c0d9648b2dc7e583fe07e4868b80a57f609. Recent commits, open issues/PRs and relevant closed PRs were checked; closed unmerged transfer-session #117, Mat-view #116 and result-API #118 are not dependencies or repeated here.

Solution

  • Add the protected GetPushConstantRanges() hook, with an empty default for existing derived pipelines. Validate nonzero stages, stage uniqueness across ranges, four-byte alignment, nonempty sizes and the physical-device size limit before creating resources. Use subtraction for the bounds check to avoid overflow. Initialize descriptor handles to null so rejected initialization remains safe to destroy.
  • Convert ComputeBarycentric to a 32-byte push-constant block containing dimensions and integer vertices. Retain Run(command) for the original triangle; add Run(command, Triangle) for independently recorded triangles. Remove its fixed uniform buffer and descriptor. The output buffer accumulates triangle coverage until the caller clears it; reusing the pipeline across completed submissions remains supported.
  • Order potentially overlapping rasterizer writes with a compute-to-compute write dependency. The runnable example records two distinct triangles in one command buffer/submission, adds the host-read dependency, waits for completion and writes rasterized.png.
  • Bound rasterizer dimensions to 1..16384 and coordinates to -16383..16383 before recording. This keeps the existing signed 32-bit indexing and edge products representable, including clipped triangles. Device allocation/storage-buffer limits still apply. Preserve the existing winding and edge-coverage rules.
  • Compile the actual example implementation and its shader into Vulkan integration tests on both platforms, independently of whether example targets are enabled. There is no duplicate test shader or parallel rasterizer implementation.

Usage

After the normal macOS build, run from the repository root:

./build/macos/examples/vk_rasterize_demo

The generated PNG contains the original triangle plus a second independently parameterized triangle. Callers can record additional triangles through the existing initialized rasterizer:

rasterizer.Run(command);
rasterizer.Run(command, core::example::ComputeBarycentric::Triangle{
    .a = glm::ivec2(50, 450),
    .b = glm::ivec2(150, 50),
    .c = glm::ivec2(250, 450)});

The complete example shows command recording, the final host-read barrier, submission and fence waiting. Triangle argument storage can be changed or released after Run returns; the rasterizer, output buffer and context must remain alive until execution completes. Clear or inspect the host-visible output only after completion.

Other VulkanBase subclasses can override GetPushConstantRanges(), match those ranges in their shaders and call native vkCmdPushConstants with the existing public pipeline_layout. Shader stage masks, byte layout and command/layout compatibility remain caller responsibilities. This follows the Khronos push-constant guide and range requirements.

Alternatives and candidate comparison

Candidate Evidence and tradeoff Decision
Per-dispatch push constants Base layout explicitly disables them; the existing rasterizer is a concrete consumer. Enables multiple parameter snapshots without per-triangle uniform buffers/descriptors. Deterministic GPU-output acceptance. Selected as a complete, bounded feature.
Image upload execution/layout consolidation, with region/pitch support Texture and cubemap loaders each use separate transition/copy/transition operations; CopyToImage only exposes whole-image geometry. A consolidated upload has real callers, while region/pitch support needs a concrete update workload. Requires a clear layout/ownership and batching contract. Retain for a focused upload design and measurements.
Gaussian blur shared-memory/separable optimization Existing Vulkan compute tests process 3000x4000 pixels with a 3x3 kernel. Representative varied inputs and repeatable GPU timing are needed before accepting halo barriers or an extra pass/scratch buffer. Defer until controlled baselines justify an algorithm.

A uniform-buffer ring would require buffer slices, alignment and descriptor-offset lifetimes for a 32-byte payload. Replacing all pipeline initialization in the example would duplicate the library path. The range hook keeps one initialization path, while the example uses native Vulkan command recording. No asynchronous ownership framework or external dependency is added. All changes are within Vulkan, its existing example and its tests/build support; no shared-module or other-backend implementation changes are included.

Validation

Both full platform builds/tests completed on the final committed source tree, with the core warnings-as-errors configuration. The scripts request Debug, but current top-level CMake selects the actual Release -O3 -DNDEBUG flags. Final runs were repeated after the last code/formatting changes.

Platform Actual command Required executables and results
macOS host ./scripts/run.sh -t macos -r tests 6 executables: mat 3, threadpool 4, stb 4, opencl 8, vulkan 19, metal 1. 39 passed, 0 failed, 0 skipped; exit 0. All default examples built.
Android arm64-v8a physical device ./scripts/run.sh -t arm64-v8a -r tests 7 device executables: mat 3, threadpool 4, stb 4, opencl 8, vulkan 19, gles 2, ahardwarebuffer 1. 41 passed, 0 failed, 0 skipped; exit 0.

Environment:

  • macOS SDK 27.0, Apple Clang 21.0.0, Apple M6 / MoltenVK 1.4.1, Vulkan SDK 1.4.350.0, CMake 4.4.4. Khronos validation layer 1.4.350 was available and requested; no validation errors were observed.
  • Before each Android run, adb devices -l confirmed exactly one authorized physical USB device, 2210132C / nuwa, Android 13 / API 33. The emulator property was empty and hardware was qcom. ANDROID_SERIAL=1dda2807 fixed every subsequent adb operation to that device.
  • Reused installed NDK 28.2.13676358 / r28c, build target API 34, JDK 17 and ADB 37.0.1. Shell-local ANDROID_NDK_ROOT and SDK variables were explicit; sourced /Users/joechu/VulkanSDK/1.4.350.0/setup-env.sh and ensured CMake, adb, glslc, slangc and xxd resolved in PATH. No dependency installation, license acceptance, profile edit, APK installation or device-setting change.
  • Checked each required test executable's actual adb shell invocation, individual RUN/OK counts, GoogleTest start/completion/pass totals and the successful set-e runner exit. Android validation was requested; layer availability on the device was not independently confirmed.

Four new tests cover device-limit and overlapping-byte/distinct-stage layouts; invalid alignment/size/stage duplication/overflowing bounds; independent parameter snapshots, overlapping/clipped triangles and command-buffer/pipeline reuse across three submissions; all original-triangle pixels, single-pixel and extreme-coordinate output, invalid dimensions/coordinates and recording recovery after rejection. Existing pipelines exercise the unchanged empty-range default.

./build/macos/examples/vk_rasterize_demo also exited 0. An independent standard-library PNG decoder and integer edge oracle verified all 1,000,000 output pixels against the union of both triangles. The same rasterizer/shader code executed in Android integration tests; the standalone PNG-writing main is a macOS example target. Other graphical examples were built but not visually exercised.

git diff --check passed; reviewed the complete diff, staged files and source tree. No new code comments, generated binaries/assets or project documentation were committed. Separate final macOS/Android logs, exit codes, device listings, source-tree hash, example/pixel checks and result verifier are retained in this worktree's ignored build/daily-push-constants-20261022/; macOS tmp results were preserved before the Android script recreated tmp.

This is a feature acceptance result. No performance benchmark, latency/FPS improvement or process-memory measurement is claimed.

Changes

File Added Deleted
vulkan/include/VulkanBase.h 4 3
vulkan/src/VulkanBase.cpp 26 2
examples/vulkan/ComputeBarycentricRasterizer/Barycentric.comp 5 5
examples/vulkan/ComputeBarycentricRasterizer/ComputeBarycentric.cpp 59 28
examples/vulkan/ComputeBarycentricRasterizer/ComputeBarycentric.h 17 7
examples/vulkan/ComputeBarycentricRasterizer/main.cpp 12 0
tests/vulkan/CMakeLists.txt 9 1
tests/vulkan/VulkanPushConstantsTest.cpp 219 0
Total: 8 files 351 46

397 changed lines, below the 1000-line cap: implementation/API/example +123/-45; tests/build +228/-1; benchmark 0; documentation 0. Design, usage, compatibility and acceptance evidence are contained in this PR body; no docs Markdown or README link is added.

Risk

The library hook is additive with an empty default, and existing public method signatures remain available. Adding a virtual hook changes the C++ vtable ABI, so consumers must rebuild derived pipelines together with CORE; binary compatibility with previously compiled subclasses is not promised. The example's private shader interface changes with its rebuilt shader, retains the original triangle overload, and now rejects out-of-range geometry explicitly. It remains a coverage-mask rasterizer with the existing winding rule, not a general mesh renderer.

The conservative write barrier serializes overlapping dispatches; no throughput improvement is claimed. Callers still own command/queue synchronization and resource lifetimes, and native push-constant writes must obey the declared ranges and shader layout. No automatic merge, deployment or publication is part of this PR.

@chuzcjoe
chuzcjoe marked this pull request as ready for review October 23, 2026 17:23
@chuzcjoe
chuzcjoe merged commit ce686f8 into master Oct 23, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant